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
ci: faster checks and less brittle tests (#2030)
Sidb3e0c4fa0dc2
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex bce4c0141e..877e386216 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -694,7 +694,7 @@ refuse to save over a row it could not read.**Problem:** Five switches each had a `default:` or simply returned `undefined`for unhandled members, so adding a seventh node type produced **zero** compile-errors — verified with `tsgo --noEmit`. The new node type got default handles and+errors — verified with `tsc --noEmit`. The new node type got default handles andno validation at all, and would activate.**Rule:** For behaviour that must exist for every member of a union, prefer one@@ -759,7 +759,7 @@ and the plan specified FNV-1a via `BigInt`.**Problem:** `apps/erp/tsconfig.json` sets `"target": "ES2019"` and compilesworkspace package **source**, not built output. A `0xcbf29ce484222325n` literalin `packages/workflows` fails the erp typecheck with TS2737 even though the-package's own `tsgo --noEmit` passes — the package config targets `esnext`.+package's own `tsc --noEmit` passes — the package config targets `esnext`.**Rule:** Anything in a package `apps/erp` imports must be ES2019-safe. Reach for`Math.imul` and two 32-bit passes rather than one 64-bit BigInt pass. Always run@@ -1045,7 +1045,7 @@ canvas hosting Radix popovers/selects.**Context:** `upsertQuoteLinePrices` was converted from supabase-js to a Kysely transaction so its delete + reinsert would roll back as a unit. The conversion typechecked, and the shipped result silently stopped preserving `shippingCost`, `discountPercent` and `leadTime` on every markup change.-**Problem:** The function keys the snapshot of existing rows by quantity and looks each one up while building the reinsert. Through PostgREST a `NUMERIC` column arrives as a JS `number`, so `pricesByQuantity[10]` matched. Through node-postgres — which Kysely uses — the same column arrives as the string `"10.00000"`, because pg does not parse `NUMERIC` (oid 1700) to float and this repo sets no `setTypeParser` anywhere. Every `Map.get(10)` therefore missed, `existing` was always `undefined`, and each preserved field fell back to the caller's value: shipping to the column default `0`, discount and lead time to the zeros the recalculate route passes. The generated types say `number` on both paths, so `tsgo` cannot see it — the mismatch exists only at runtime.+**Problem:** The function keys the snapshot of existing rows by quantity and looks each one up while building the reinsert. Through PostgREST a `NUMERIC` column arrives as a JS `number`, so `pricesByQuantity[10]` matched. Through node-postgres — which Kysely uses — the same column arrives as the string `"10.00000"`, because pg does not parse `NUMERIC` (oid 1700) to float and this repo sets no `setTypeParser` anywhere. Every `Map.get(10)` therefore missed, `existing` was always `undefined`, and each preserved field fell back to the caller's value: shipping to the column default `0`, discount and lead time to the zeros the recalculate route passes. The generated types say `number` on both paths, so `tsc` cannot see it — the mismatch exists only at runtime.**Rule (updated by the numeric-precision standard):** NUMERIC (oid 1700) now decodes to a JS number — node-postgres via `setTypeParser`, registered once in `packages/database/src/client.ts` — so runtime finally matches the generated types for numerics. The caution below still applies to `BIGINT` and float8 (still strings), to any pool NOT built through the shared factory, and as history for why `Number(...)` coercions litter Kysely call sites (they are now harmless no-ops). Original rule: when porting a query from supabase-js to Kysely, treat every `NUMERIC`/`DECIMAL`/`BIGINT` read as a **string** regardless of what the generated type claims. Normalize with `Number(...)` only where the value has to be a number — an object/`Map` key, a `===` comparison, arithmetic — and only for bounded fields like a quantity or a precision. Do **not** normalize a whole row for tidiness: `Number()` on a `BIGINT` or a wide `NUMERIC` silently loses precision past `Number.MAX_SAFE_INTEGER`, and money is exactly where that matters. Writing values back untouched is both safe and preferable — pg accepts the canonical string for a numeric param, and passing it straight through preserves the stored value exactly. More generally: a client swap can change runtime value types without changing a single TypeScript type, so a typecheck is not evidence that a port behaves identically — exercise it against a real database.@@ -2658,7 +2658,7 @@ gate executes it.## Never `git checkout` a generated file to undo a local patch — the user may have regenerated it**Context:** Typechecking a new-column change in a worktree with no local database, the-generated `packages/database/src/types.ts` was patched by hand as a throwaway so `tsgo`+generated `packages/database/src/types.ts` was patched by hand as a throwaway so `tsc`could see the columns, then "restored" with `git checkout -- …/types.ts`. Meanwhile theuser had run `pnpm db:migrate`, which regenerated that file with the real columns.@@ -2869,8 +2869,8 @@ them away. Nothing was wrong in any single place; the waste was the sum.type) rather than writing every row and bumping `updatedAt`. The trigger is the backstop: anUPDATE that changes only `updatedAt` / `updatedBy` / `embedding` is not queued for AUDIT,SEARCH or EMBEDDING (`20261001195204`). When forking `dispatch_event_batch()` into a new-migration, fork the NEWEST definition; `packages/database/src/event-dispatch.test.ts` fails-if the filter is lost.+migration, fork the NEWEST definition; the `event-ignored-columns` check (`@carbon/checks`)+fails if the filter is lost.**Applies to:** `packages/planning/src/scheduling/`, any job or route that rewrites many rowsof a table with event subscriptions, and every migration that redefines@@ -3799,7 +3799,7 @@ The write was then removed (nothing reads it), so the rail always starts collaps**Problem:** `vi.mock` replaces a module's exports for importers in other files. A call from one function to another inside the same file goes to the real function, so tests that mocked the callee started calling the database, or passed while testing nothing.-**Rule:** Stub only a real boundary (the Supabase client, `fetch`, the clock), as `.claude/rules/testing-no-mock-theater.md` says. A test that only checks which internal functions were called gets deleted, not repointed.+**Rule:** Stub only a real boundary (the Supabase client, `fetch`, the clock), as `.claude/rules/testing.md` says. A test that only checks which internal functions were called gets deleted, not repointed.**Applies to:** tests under `apps/erp/test/` and `apps/erp/app/modules/**`.diff --git a/.claude/rules/database-patterns.md b/.claude/rules/database-patterns.mdindex d0003c941d..76ec631f6c 100644--- a/.claude/rules/database-patterns.md+++ b/.claude/rules/database-patterns.md@@ -109,7 +109,7 @@ Conventions (see also `conventions-services.md`):- Always scope list queries by `companyId` (`.eq("companyId", companyId)`) — defense in depth even though RLS also enforces it.- List endpoints take `GenericQueryFilters` and run through `setGenericQueryFilters(query, args, [...])` (`~/utils/query`) for search/sort/pagination.- Count/select for list endpoints: prefer `{ count: LIST_COUNT }` (`LIST_COUNT = "estimated"`, `~/utils/query`) over `count: "exact"`. `exact` is `COUNT(*) OVER ()`, which materializes the whole filtered set just to produce a total the UI shows approximately anyway — on 500k `trackedEntity` rows that is 652 ms vs 1.5 ms. `estimated` is a hybrid: PostgREST still returns an exact count below its threshold, so small tenants see no change. Currently used by the ten view-backed endpoints plus `getJobs` and `getTrackedEntities`.-- The ten endpoints backed by the big multi-join **views** (`parts`, `materials`, `tools`, `consumables`, `services`, `purchaseOrders`, `quotes`, `salesOrders`, `purchaseInvoices`, `salesInvoices`) additionally select an explicit `*_LIST_COLUMNS` constant instead of `select("*")`, so Postgres can prune the views' unreferenced computed columns. Adding a column to one of those tables means adding it to the constant — `apps/erp/test/list-select-columns.test.ts` fails if an `accessorKey` is missing, because the CSV export reads accessors untyped. The rationale lives once on `LIST_COUNT` in `apps/erp/app/utils/query.ts`, not at each constant.+- The ten endpoints backed by the big multi-join **views** (`parts`, `materials`, `tools`, `consumables`, `services`, `purchaseOrders`, `quotes`, `salesOrders`, `purchaseInvoices`, `salesInvoices`) additionally select an explicit `*_LIST_COLUMNS` constant instead of `select("*")`, so Postgres can prune the views' unreferenced computed columns. Adding a column to one of those tables means adding it to the constant — the `list-select-covers-columns` check (`@carbon/checks`) fails if an `accessorKey` is missing (a new constant needs a `LIST_TABLES` entry there), because the CSV export reads accessors untyped. The rationale lives once on `LIST_COUNT` in `apps/erp/app/utils/query.ts`, not at each constant.- Use `sanitize(...)` (re-exported from `@carbon/utils`) to strip empty values before insert/update.- Upserts are done either with a manual `id ? update : insert` branch or supabase's native `.upsert(...)`; both are in use.- `fetchAllFromTable(client, table, columns, qb)` (from `@carbon/database`) pages through large result sets:diff --git a/.claude/rules/document-template-customizer.md b/.claude/rules/document-template-customizer.mdindex 957ce23e8d..504b2d6e5e 100644--- a/.claude/rules/document-template-customizer.md+++ b/.claude/rules/document-template-customizer.md@@ -34,7 +34,7 @@ Created by `packages/database/supabase/migrations/20260609143732_document-templaJSON columns are untyped in generated DB types. `toDocumentTemplate(row, type)`(`template/schema.ts`) is the **one** cast point — callers use it instead of-re-deriving the shape. Expect tsgo `.blocks does not exist` errors until DB types+re-deriving the shape. Expect tsc `.blocks does not exist` errors until DB typesare regenerated; that's expected, not a bug.## Template model (`packages/documents/src/template/`)diff --git a/.claude/rules/environment-configuration.md b/.claude/rules/environment-configuration.mdindex f090aa837a..14a32a88b7 100644--- a/.claude/rules/environment-configuration.md+++ b/.claude/rules/environment-configuration.md@@ -38,8 +38,9 @@ description, optional zod `type`, `secret`, `browser`, `required` and `aliases`.a half-configured feature (some of a group's `needed` variables set, not all)are only printed for now and become errors in the next release.- Not validated under Vitest or with `SKIP_ENV_VALIDATION` set.-- `src/deployments.test.ts` reads what `sst.config.ts` and `crbn up` set and- fails when either would hit a startup error.+- The `deployments-set-required-env` check (`@carbon/checks`) reads what+ `sst.config.ts`, `crbn up` and the Vercel projects set and fails when any+ would hit a startup error.`window.env` is populated by `getBrowserEnv()`, injected via an inline script ineach app's `root.tsx` (`apps/erp/app/root.tsx`, `apps/mes/app/root.tsx`). Only thediff --git a/.claude/rules/event-system.md b/.claude/rules/event-system.mdindex f4d73d4b21..571a400431 100644--- a/.claude/rules/event-system.md+++ b/.claude/rules/event-system.md@@ -55,7 +55,7 @@ behaviour arrived, not where to read the current definition. Details:`handlerType` CHECK now allows all six: `WEBHOOK, WORKFLOW, SYNC, SEARCH, AUDIT, EMBEDDING` (widened across `20260204080000` → `20260212152709` → `20260326120000`).### PL/pgSQL functions (in `_event_system_impl` + later)-- `dispatch_event_batch()` — AFTER STATEMENT. Reads transition tables (`batched_new`/`batched_old`), filters by active subscriptions, builds payload, `pgmq.send_batch('event_system', ...)`. Captures `actorId := auth.uid()::TEXT` (added `20260212153753`; NULL for service-role) and `workflowRunId` from the `workflow_run_id` JWT claim (`20260810100000`). UPDATE pairs transition rows on the table's **full** primary key via `get_primary_key_columns()` (`20260717143448`, restored in `20260810100000` after `20260721184852` copied the older single-column pairing forward). `recordId` comes from the same key: `id` when the primary key has one, otherwise every primary-key column joined by `:` (`workCenterProcess`, `jobOperationDependency`); a table with no primary key keeps its single legacy column, because the audit log files `itemPlanning` under its `itemId`. `supabase/tests/event-record-id.test.sql` checks this and the UPDATE pairing for every evented table. `get_primary_key_columns()` read a unique index's columns from position 1 of a 0-based `indkey` until that test found it: `itemPlanning` paired on `locationId` alone and a bulk UPDATE queued rows × rows events. Uses `clock_timestamp()` per event so batched events get unique microsecond timestamps (`20260427120000`). An UPDATE that changes nothing but `updatedAt` / `updatedBy` / `embedding` is not queued for `AUDIT`, `SEARCH` or `EMBEDDING` subscriptions (`20261001195204`) — those handlers discard such an event anyway; `WEBHOOK`, `WORKFLOW` and `SYNC` still receive every UPDATE because their payload is a contract. The column list is `ignored_columns` in the function and must equal `auditConfig.skipFields`; `packages/database/src/event-dispatch.test.ts` reads `event-system/functions/dispatch_event_batch.sql` and fails when the two lists diverge.+- `dispatch_event_batch()` — AFTER STATEMENT. Reads transition tables (`batched_new`/`batched_old`), filters by active subscriptions, builds payload, `pgmq.send_batch('event_system', ...)`. Captures `actorId := auth.uid()::TEXT` (added `20260212153753`; NULL for service-role) and `workflowRunId` from the `workflow_run_id` JWT claim (`20260810100000`). UPDATE pairs transition rows on the table's **full** primary key via `get_primary_key_columns()` (`20260717143448`, restored in `20260810100000` after `20260721184852` copied the older single-column pairing forward). `recordId` comes from the same key: `id` when the primary key has one, otherwise every primary-key column joined by `:` (`workCenterProcess`, `jobOperationDependency`); a table with no primary key keeps its single legacy column, because the audit log files `itemPlanning` under its `itemId`. `supabase/tests/event-record-id.test.sql` checks this and the UPDATE pairing for every evented table. `get_primary_key_columns()` read a unique index's columns from position 1 of a 0-based `indkey` until that test found it: `itemPlanning` paired on `locationId` alone and a bulk UPDATE queued rows × rows events. Uses `clock_timestamp()` per event so batched events get unique microsecond timestamps (`20260427120000`). An UPDATE that changes nothing but `updatedAt` / `updatedBy` / `embedding` is not queued for `AUDIT`, `SEARCH` or `EMBEDDING` subscriptions (`20261001195204`) — those handlers discard such an event anyway; `WEBHOOK`, `WORKFLOW` and `SYNC` still receive every UPDATE because their payload is a contract. The column list is `ignored_columns` in the function and must equal `auditConfig.skipFields`; the `event-ignored-columns` check (`@carbon/checks`) fails when the two lists diverge.- `dispatch_event_interceptors()` — BEFORE ROW. Runs named sync interceptor functions inline (data-integrity, not async).- `dispatch_event_after_interceptors()` — AFTER ROW. Same but post-commit-of-row, safe for FK refs (added `20260410030406`).- Both dispatchers are SECURITY DEFINER (`20260925121735`), so interceptors run as the owner on every write. Write a new interceptor as **SECURITY INVOKER**: it still runs as the owner from the dispatcher, but a direct `/rpc/<interceptor>` call with a forged payload runs under the caller's RLS. A SECURITY DEFINER interceptor is callable by anyone with the anon key as the owner — `public-definer-function-authorizes-caller` fails on it.diff --git a/.claude/rules/module-files.md b/.claude/rules/module-files.mdindex eab2778735..1992979997 100644--- a/.claude/rules/module-files.md+++ b/.claude/rules/module-files.md@@ -89,7 +89,8 @@ function kept its logic as is:it checks the caller behind `client` first.- The operation keeps the function's permission exactly: a `<name>Permission`constant beside the body, passed as `as`. `apps/erp/test/posting-permissions.test.ts`- pins them.+ checks every one names a real module and none is open to every member+ without review.- Its live-database tests move to `apps/erp/test/database/`, on the fixtures in`apps/erp/test/database/fixtures/` (`always-post.ts`, whose `service` is asystem `ServiceContext`).diff --git a/.claude/rules/realtime-system.md b/.claude/rules/realtime-system.mdindex 3a3f00574d..0a8e97edfe 100644--- a/.claude/rules/realtime-system.md+++ b/.claude/rules/realtime-system.md@@ -64,8 +64,8 @@ a database without Supabase Realtime still accepts writes.| `broadcast_user_changes` | `user:<userId>:<table>` | notifications |- An UPDATE that changes only `updatedAt` / `updatedBy` / `embedding` sends- nothing (the same list `dispatch_event_batch` ignores; `event-dispatch.test.ts`- keeps the copies equal).+ nothing (the same list `dispatch_event_batch` ignores; the `event-ignored-columns`+ check keeps the copies equal).- `itemSupersession` has no `id`: its message carries the `itemId`.`implementationHub` has no `companyId`: its `id` is the company.- Which tables broadcast is declared in `event-system/attachments.ts`, never indiff --git a/.claude/rules/testing-no-mock-theater.md b/.claude/rules/testing-no-mock-theater.mddeleted file mode 100644index 5be1572d45..0000000000--- a/.claude/rules/testing-no-mock-theater.md+++ /dev/null@@ -1,50 +0,0 @@-----paths:- - "**/*.test.ts"- - "**/*.test.tsx"------# Tests: no mock theater--A test that fakes every collaborator and then asserts call counts against the-fakes proves the mocks work, not the code. One such file was deleted from a PR-on sight (`accounting-auth-failure.test.ts`, 2026-09-17: hand-rolled redis +-supabase + Inngest step fakes, assertions like "redis.del was called with these-keys"). Do not write tests like that.--## The rule--Stub only the **real external boundary** — the thing the code genuinely cannot-reach in a test process:--- an HTTP endpoint → stub global `fetch` (see `core/oauth-refresh.test.ts`:- four tests, one stub, pins real branching in `refresh()`)-- the wall clock → fake timers-- the filesystem → a temp dir--Everything between the test and that boundary runs real. If the unit under-test touches redis, the database, AND a runtime harness, and you would have to-fake all three to test it, **don't write the test** — either extract the pure-decision into its own function and test that (the codebase's established-pattern: `reconcile.ts`, `mrp-companies.ts`, `posting-policy` are all pure-cores with real tests), or leave it untested and let an integration path cover-it.--## Smells that mean delete-and-rethink, not refactor-the-test--- A hand-rolled in-memory fake of redis/supabase/Kysely inside a test file.-- `expect(mock).toHaveBeenCalledWith(...)` as the primary assertion — you are- pinning the implementation's call shape, not its behavior.-- The fake needs its own logic (NX semantics, builder chains) to make the test- pass — the fake is now a second implementation that can drift from the real- one.-- A loop driving the code N times purely to trip a threshold inside mocks.--## What a test must earn--A test exists to fail when the LOGIC breaks. Before keeping one, ask: "which-real bug flips this red?" If the only answer is "someone renamed the mock's-method", it has earned nothing. A branch worth testing is worth testing-through real values at a real boundary; a glue function that just wires-collaborators together is verified by typecheck + the integration that uses-it, not by a puppet show.diff --git a/.claude/rules/testing.md b/.claude/rules/testing.mdnew file mode 100644index 0000000000..eed6165190--- /dev/null+++ b/.claude/rules/testing.md@@ -0,0 +1,195 @@+---+paths:+ - "**/*.test.ts"+ - "**/*.test.tsx"+ - "**/*.test.sql"+ - "**/*-test-fixture.ts"+---++# Writing tests++How a Carbon test is written, and when one is written at all. A 2026-10 audit+of ~900 test files found most of them sound, but a recurring fifth that only+confirmed the change they shipped with: regexes over applied migrations, mock+call counts, constants echoed back, the same rule re-tested in three+providers. This page is the house style that keeps those out.++## Before you write one: three questions++1. **Which bug turns it red?** Name a plausible mistake a future change could+ make. "Someone renames a mock" or "someone edits an applied migration" is+ not an answer.+2. **What is the seam?** One of the homes below. Not a private helper, not+ the call shape between two of our own modules.+3. **Where do the expected values come from?** A worked example, a literal+ you computed by hand, the spec, an identity that must hold (debits =+ credits). Never the same formula the code uses.++If you cannot answer all three, the test is a **scratch proof**: it showed you+your change works, and it goes in your scratchpad or the run log+(`.ai/runs/`), not the repo. That is fine. A proof you needed once is not a+regression guard.++## Where a check lives++| What you are protecting | Home | Runs |+|---|---|---|+| A decision, calculation, parser, plan | **Pure core** test next to the code (`foo.ts` → `foo.test.ts`) | every `pnpm test` |+| Anything whose truth is in Postgres: posting, RLS, triggers, RPC results, ordering | **Database test**: `apps/erp/test/database/**` (vitest + `databaseTest`) or `packages/database/supabase/tests/*.test.sql` | local database only |+| A structural rule across many files ("every migration…", "no file imports…") | **Conformance check** in `packages/checks` | `pnpm test` (`@carbon/checks`) |+| A user flow across pages | **Browser playbook** via `/test`, cached in `.ai/playbooks/` | by hand / agents |+| "My change works" | **Scratch** | never committed |++`packages/checks` is the only place a test may read source or migration text.+Anywhere else, a regex over a `.sql` or `.ts` file is a change detector: an+applied migration never changes, and a later migration can redefine the+object while the test stays green.++## The house style++**Pull the decision out, test it by value.** Glue (load → decide → write)+gets its decision extracted into a pure function that returns plain data,+and the test asserts that data. The glue itself is covered by typecheck and+the database test or flow that uses it.++```ts+// packages/ee/src/oee/engine.test.ts+it("inserts a closed event for a run that starts and ends in one sync", () => {+ const result = planMachineTime(+ base({+ changes: [+ { state: "Running", changedAt: t("10:00:00") },+ { state: "Idle", changedAt: t("10:30:00") }+ ]+ })+ );+ expect(result.writes).toEqual([+ {+ kind: "insertMachineEvent",+ jobOperationId: "A",+ startTime: t("10:00:00"),+ endTime: t("10:30:00")+ }+ ]);+});+```++Other good models: `getJournalPostingDecision` in+`packages/jobs/.../accounting-sync-operations.test.ts`, `decideJobStep` in+`tasks/assembler-client.test.ts`, `supersession-pick.test.ts`.++**One fixture builder per file, with overrides.** `base({ ...overrides })`+holds the valid default; each test states only what differs. Never paste the+same 30-line literal into six tests.++**A table for inputs that hit one branch, an `it` per branch.**++```ts+it.each([undefined, null, Number.NaN, 12.34])(+ "rejects absent or ambiguous bare-number value %s",+ (value) => expect(parseVerifiedRampMinorAmount(value, "Amount").ok).toBe(false)+);+```++**Names are behaviour sentences.** "closes the open event when the machine+goes idle". Not "works", not "handles X correctly", not "regression for+#1234". The name must match what the test asserts.++**Assert the whole result.** `toEqual` on the returned value catches the+field you forgot. `toBeDefined()`, `toBeTruthy()` and `typeof x ===+"function"` prove almost nothing.++**Expected values are literals or identities.** `toBe(15)`, not+`toBe(items.reduce(...))`. For money, a worked example in the comment is+better than a computed expectation (`lease-liabilities.test.ts` starts from+the spec's example and checks maturity − interest = liability).++**Test a shared rule once, where it lives.** A label fallback in+`core/card-charge-source.ts` is tested there, not again in the QuickBooks,+Xero and Rillet tests.++**Don't pin copy.** UI text, descriptions and messages change for good+reasons. Assert a string only when it is a contract (an API error code, a+file name format, an external payload).++**Comments say why the rule exists, in one line.** Not the history of the+change, not which PR added it.++**Size follows the logic.** A test file larger than the code it tests usually+has duplicate cases or pasted setup. Look before adding more.++## Mocks++Stub only what a test process cannot reach:++- the network: stub global `fetch` (`core/oauth-refresh.test.ts`)+- the clock: fake timers or an injected `now`+- the filesystem: a temp dir+- randomness: an injected seed++Never mock a first-party module (`vi.mock("./x")`, `vi.mock("../x.service")`,+`vi.mock("~/...")`). If the code needs the database, a job runner and Redis+faked to be testable, extract the decision instead, or let a database test+cover it. Asserting `toHaveBeenCalledWith` on our own collaborators pins the+wiring and passes while the rule is wrong.++A **stateful in-memory fake** at a data boundary is fine when it keeps rows,+applies filters, and the assertions read the resulting state+(`rules/sales/invoice-shipto.test.ts`, `accounting-master-sync-loop.test.ts`).+A fake that replays a scripted queue of 18 responses in a fixed order is not:+any reorder of queries breaks it, and it cannot catch a filtering bug.++Mocks that exist only so the module can be imported (`@lingui/core/macro`,+`@carbon/env`, `@carbon/logger`) are an import-graph problem. Import the+smaller module, or fix the side effect at import time. Don't copy the mock+into the next file.++## Component tests++Test a component's rule by pulling it into a function (`deriveRows`,+`canSubmit`) and testing that. A test that replaces `React.useState`, mocks+the form kit, or greps rendered HTML for a library's markup tests the mocks.+Interaction belongs in a browser playbook.++## Database tests++- Use `databaseTest` and `connectLocalTestDatabase`+ (`apps/erp/test/database/fixtures/local-database.ts`). `databaseTest` skips+ cleanly with no local database; never `if (!client) return;` inside a test,+ which turns green without running. Each fixture makes its own company, so+ tests do not see each other's rows.+- `connectLocalTestDatabase` is ONE connection with triggers suppressed. Two+ `Promise.all` posts over it are serialized, so it cannot test a race: open a+ second connection (`post-payment-concurrency.test.ts`). And with triggers off,+ raw inserts can build states the app never produces; reach a state through+ the real operations where you can.+- Call the real operation (`postReceipt`, the RPC, an insert as a role) and+ assert the business outcome (ledger rows, balances, what the role may see).+ Re-reading a row the test itself just inserted proves nothing.+- Build setup from the shared fixtures in `fixtures/`; add to them rather than+ hand-building a company, item and location in each file.+- Never gate on an opt-in env var (`RUN_X_DB_TESTS`) nobody sets. Gate on the+ database being present, as `databaseTest` does.+- Run: `SUPABASE_DB_URL=… pnpm --filter erp exec vitest run test/database/<file>`.++## Bug fixes++Reproduce the bug first, red then green. Then ask the three questions. A bug+in a decision gets a committed test at that decision's seam. A wiring bug (a+wrong argument passed between two of our modules, a missing `await`) usually+has no honest committed test: typecheck or the database test covers it.+Record the proof in the run log and say so in the commit message.++## When a test breaks on a refactor++If behaviour did not change, the test was pinned to the implementation.+Delete it or move it to the seam. Don't edit it until it passes again.++## Enforced++`packages/checks` flags, outside its own directory:++- `test-reads-source`: a test reading `.sql`, `.ts` or `.tsx` files as text+- `test-mocks-own-module`: `vi.mock` / `vi.doMock` of a relative or `~/` path++Existing cases sit in the baseline. Don't add new ones.diff --git a/.claude/rules/workflow-actions.md b/.claude/rules/workflow-actions.mdindex 84a2da493e..f79703bf83 100644--- a/.claude/rules/workflow-actions.md+++ b/.claude/rules/workflow-actions.md@@ -65,7 +65,7 @@ may write. Adding a column to `watch` does not make it writable, and that is thepoint.Both maps are keyed by `ColumnOf<T>` for the entry's own table, so a migration-that renames a column fails `tsgo` at the registry line. `write` entries carry+that renames a column fails `tsc` at the registry line. `write` entries carrythe same `ref` escape hatch as `watch` for composite foreign keys, and a `ref`that disagrees with a present foreign key is a build error.diff --git a/.claude/rules/workflow-event-catalog.md b/.claude/rules/workflow-event-catalog.mdindex 7215f3d059..15cbabd5f7 100644--- a/.claude/rules/workflow-event-catalog.md+++ b/.claude/rules/workflow-event-catalog.md@@ -214,7 +214,7 @@ tenancy checks, webhook signing and the SSRF guard — is in2. **Every raise site names a declared moment** (the type system covers this too).3. **Every registry table, watched column and writable column still exists.** Also a compileerror, via type-only `TableName` / `ColumnOf<T>` from `@carbon/database/audit.config` — a- migration renaming a column fails `tsgo` at the registry line, naming the column. The+ migration renaming a column fails `tsc` at the registry line, naming the column. Thescript repeats it in plain English and catches skew between the two generated schemaartifacts. A writable column that is identity or audit (`id`, `companyId`, `createdBy`,`createdAt`, `updatedBy`, `updatedAt`) is refused outright.diff --git a/.claude/skills/README.md b/.claude/skills/README.mdindex da28a88efa..b6391b2f04 100644--- a/.claude/skills/README.md+++ b/.claude/skills/README.md@@ -67,8 +67,8 @@ in root-cause, BLOCKED in fix) always surface to the human.| `rust` | Rust reference for the cargo workspace (tokio+FFI discipline, state choices, perf) | knowledge (no artifact) || `carbon-docs` | Author reader-facing docs in the docs app | `docs/content/**` || `translate` | Fill missing i18n .po translations via cheap Haiku subagents | `packages/locale/locales/*/*.po` |-| `test-driven-development` | Red→green→refactor discipline (vitest) | tests-first code |-| `tdd` | External (mattpocock/skills, MIT, `d81f3a1`): what a good test is, seams agreed before testing, anti-patterns, rules of the loop. Pairs with `test-driven-development`, which holds the Carbon/vitest specifics | tests-first code |+| `test-driven-development` | Carbon red→green loop (vitest): prove first, commit a test only when it earns it (`.claude/rules/testing.md`) | tests-first code |+| `tdd` | External (mattpocock/skills, MIT, `d81f3a1`): what a good test is, seams agreed before testing, anti-patterns, rules of the loop. Pairs with `test-driven-development`, which holds the Carbon/vitest loop; house style is `.claude/rules/testing.md` | tests-first code || `resolving-merge-conflicts` | External (mattpocock/skills, MIT, `3216582`; since removed upstream): THE default for any in-progress merge or rebase conflict — find each side's intent, resolve every hunk, run the checks, finish | a finished merge/rebase || `writing-skills` | House guide for authoring skills | skills || `explain` | HTML explainer (STE-80 prose + one diagram) for a spec, plan or research file | `{source}.html` beside the `.md` |diff --git a/.claude/skills/fix/SKILL.md b/.claude/skills/fix/SKILL.mdindex 871a0711e6..4e314f2dd6 100644--- a/.claude/skills/fix/SKILL.md+++ b/.claude/skills/fix/SKILL.md@@ -1,6 +1,6 @@---name: fix-description: End-to-end bug-fix pipeline that diagnoses, implements, and proves the fix. It orchestrates /root-cause, /debugging-difficult-bugs, /test, and /check-and-commit, and performs the fix itself — the minimal code change from the proven cause plus a mandatory red→green regression test and scoped validation gates. At start it picks an autonomy mode (approval-before-each-phase vs fully autonomous) and a phase set (root-cause + fix are mandatory; runtime instrumentation is conditional on confidence, test is optional, commit runs only on explicit ask), auto-detected from the request and confirmed with the user when unclear. Keeps a structured run record at .ai/runs/{date}-{slug}.md. Use when fixing a bug, test failure, or unexpected behavior ("fix this bug", "why does X fail"). Do not use for building new features (use /feature). For a single watched item with explicit acceptance criteria, prefer /conductor.+description: End-to-end bug-fix pipeline that diagnoses, implements, and proves the fix. It orchestrates /root-cause, /debugging-difficult-bugs, /test, and /check-and-commit, and performs the fix itself — the minimal code change from the proven cause plus a mandatory red→green proof (committed as a regression test only when it pins logic at a seam) and scoped validation gates. At start it picks an autonomy mode (approval-before-each-phase vs fully autonomous) and a phase set (root-cause + fix are mandatory; runtime instrumentation is conditional on confidence, test is optional, commit runs only on explicit ask), auto-detected from the request and confirmed with the user when unclear. Keeps a structured run record at .ai/runs/{date}-{slug}.md. Use when fixing a bug, test failure, or unexpected behavior ("fix this bug", "why does X fail"). Do not use for building new features (use /feature). For a single watched item with explicit acceptance criteria, prefer /conductor.---<!-- Workflow pattern inspired by Open Mercato (MIT License)https://github.com/open-mercato/open-mercato@@ -9,7 +9,7 @@ description: End-to-end bug-fix pipeline that diagnoses, implements, and proves# fix — end-to-end bug-fix pipelineRuns the bug-fix lifecycle: diagnose → (instrument) → implement the minimal fix-with a red→green regression test → (verify) → (commit). This skill orchestrates+with a red→green proof → (verify) → (commit). This skill orchestratesthe surrounding phases **and performs the fix itself**. The diagnosis andverification phases delegate to their own skills; the fix implementation(Phase 3) is done inline here — that is the core of this skill.@@ -23,7 +23,7 @@ verification phases delegate to their own skills; the fix implementation| --- | ------------------ | --------------------------- | ---------------------------------------- | ------------------------ | ------------------------------------------------- || 1 | Root cause | `/root-cause` | root-cause brief | **always** | 🛑 three-strikes architectural → surface to human || 2 | Runtime instrument | `/debugging-difficult-bugs` | log-backed cause | conditional | none |-| 3 | Fix | **this skill (inline)** | ready change + red→green regression test | **always** | 🛑 BLOCKED (2 failed fix attempts) → surface |+| 3 | Fix | **this skill (inline)** | ready change + red→green proof | **always** | 🛑 BLOCKED (2 failed fix attempts) → surface || 4 | Browser verify | `/test` | pass/fail + playbook | optional | user-facing flow must pass || 5 | Commit | `/check-and-commit` | conventional commit | **only on explicit ask** | gates must be green |@@ -60,8 +60,8 @@ _after_ root-cause, not upfront:proves the cause.- **Test (`/test`)** — include when the fix is user-facing or the proof isinherently visual (layout, spacing, animation). Skip for a pure-logic fix- already covered by the Phase 3 red→green regression test — log the skip- ("browser test skipped — regression test covers it").+ already covered by the Phase 3 red→green proof — log the skip+ ("browser test skipped — red→green proof covers it").- **Commit (`/check-and-commit`)** — runs **only if the user explicitly asked tocommit** (e.g. "fix and commit"). Otherwise the pipeline ends at fix (+ test)with a READY summary and stops; offer to commit, don't do it unprompted.@@ -114,7 +114,7 @@ the Confidence line and branch per 0b before continuing.## Phase 3 in detail — implementing the fixThis is the mandatory core. Input: the proven root-cause brief. Output: the-smallest correct fix plus a regression test, all gates green. Execute the brief,+smallest correct fix plus a red→green proof, all gates green. Execute the brief,prove it, and stop.### 3.1 Prerequisites@@ -135,18 +135,25 @@ with the human.### 3.3 Write the failing test FIRST-Mandatory for every fix. Write a regression test that reproduces the bug, then-run it and **watch it fail** before changing any production code:+Mandatory for every fix: a check that reproduces the bug, run and **seen to+fail** before changing any production code:```bashpnpm --filter <pkg> exec vitest run <path/to/test># Expected: FAIL, for the reason the brief describes (not a typo/import error)```-A test that passes immediately proves nothing — it isn't testing the bug. Test-locations: `apps/erp/app/modules/{module}/__tests__/` or-`packages/{pkg}/src/__tests__/` (or next to the source, matching siblings). Copy-setup patterns from a sibling test file.+A check that passes immediately proves nothing — it isn't testing the bug.++Whether that check is **committed** is a separate decision. Commit it only if+it passes the three questions in `.claude/rules/testing.md` (which bug turns+it red, what seam, where the expected values come from). A bug in a decision+or calculation gets a committed test at that seam, in the existing file's+fixture builder or `it.each` table. A wiring bug (wrong argument between two+of our modules, a missing `await`, a call that no longer happens) usually has+no honest committed test: keep the proof in scratch, quote it in the run+record, and say how it was proven in the commit message. Never mock our own+modules or regex a migration to manufacture a committable test.If the bug is only provable in the browser (layout, visual state), the failingproof is a `/test` run + BEFORE screenshot instead — say so explicitly, and make@@ -203,7 +210,7 @@ to the human even in autonomous mode).**Status:** READY | BLOCKED <if BLOCKED: what and why>**Root-cause brief:** <path/link>**Files changed:** <path — what>-**Regression test:** <path — failed before fix (output), passes after (output)>+**Proof:** <committed test path, or scratch proof quoted here — failed before fix (output), passes after (output)>**Gates:** generate:types PASS|SKIP · biome PASS · typecheck(<pkgs>) PASS · test(<pkgs>) PASS**BC assessment:** NONE | <surfaces and how they comply>**Summary:** <2–3 sentences>diff --git a/.claude/skills/improve/SKILL.md b/.claude/skills/improve/SKILL.mdindex 28806926b0..5909ff0561 100644--- a/.claude/skills/improve/SKILL.md+++ b/.claude/skills/improve/SKILL.md@@ -18,7 +18,7 @@ This is the Carbon-adapted variant. Carbon is a pnpm + turbo monorepo (`apps/erp1. **Never modify source code yourself.** No edits, no fixes, no "quick wins while you're in there." The ONLY files you may create or modify live under `.ai/plans/improve/` (create it if absent). Never write to `.claude/rules/` — that's the committed-knowledge base, and plans describe uncommitted future work (per `AGENTS.md`: never cache plans or not-yet-committed code). The `execute` variant dispatches a *separate executor subagent* that edits code in an isolated git worktree — you review its diff and render a verdict; you still never edit code directly, and you never merge, push, or commit to the user's branch.2. **Never run commands that mutate the user's working tree or environment** — no installs in the main tree, no builds, no `pnpm format`/`biome ... --write`, no git commits. Read, search, and run read-only analysis only. **Carbon-specific command rules:**- - **NEVER run a whole-repo typecheck** (`pnpm typecheck`, `turbo run typecheck --filter='*'`, or `tsc --noEmit` across the repo) — it OOMs the machine. Scope every typecheck to one package: `turbo run typecheck --filter=<pkg>` (e.g. `--filter=erp`, `--filter=@carbon/react`). erp/mes typecheck via `tsgo --noEmit`.+ - **NEVER run a whole-repo typecheck** (`pnpm typecheck`, `turbo run typecheck --filter='*'`, or `tsc --noEmit` across the repo) — it OOMs the machine. Scope every typecheck to one package: `turbo run typecheck --filter=<pkg>` (e.g. `--filter=erp`, `--filter=@carbon/react`). erp/mes typecheck via `tsc --noEmit`.- **NEVER touch the database.** Do not run `pnpm db:migrate` (`crbn migrate`), `db:seed`, `db:migrate:new`, `db:types`, or anything that rebuilds/resets/reseeds the DB. Per `AGENTS.md`, the user rebuilds the DB; you wait. Audit migrations by reading the SQL only.- Lint read-only: `pnpm exec biome lint <paths>` or `biome check <paths>` (no `--write`). Carbon uses **Biome**, not ESLint/Prettier.- Tests are fine if cheap and side-effect free: `pnpm --filter <pkg> test` (vitest), or `pnpm --filter <pkg> exec vitest run <file>`.diff --git a/.claude/skills/improve/references/plan-template.md b/.claude/skills/improve/references/plan-template.mdindex 7cabb47758..a04ae13dcd 100644--- a/.claude/skills/improve/references/plan-template.md+++ b/.claude/skills/improve/references/plan-template.md@@ -85,7 +85,7 @@ NEVER run DB migrate/seed/rebuild commands.)executor's environment. Skip the section otherwise.)- Carbon skills the executor should invoke if available, and for what:- "use the `test-driven-development` skill for the regression test in step 2";+ "use the `test-driven-development` skill to prove step 2, and `.claude/rules/testing.md` to decide whether its test is committed";"use the `check-and-commit` skill to gate the final commit".- Workflow docs worth reading first by path:"`.claude/rules/workflow-database-migration.md` before writing the migration in step 4";diff --git a/.claude/skills/test-driven-development/SKILL.md b/.claude/skills/test-driven-development/SKILL.mdindex c1eba12952..c6750c3791 100644--- a/.claude/skills/test-driven-development/SKILL.md+++ b/.claude/skills/test-driven-development/SKILL.md@@ -1,94 +1,88 @@---name: test-driven-development-description: Red→green→refactor discipline for Carbon (vitest) — write the failing test first, watch it fail for the right reason, write minimal code to pass. Use when implementing any feature or bug fix, before writing implementation code. Exceptions (throwaway prototypes, generated code, config) require the user's explicit OK. For browser-only proofs use /test instead.+description: Carbon's red→green loop with vitest — prove a change with a failing test first, then decide whether that test earns a place in the repo or stays a scratch proof. Use when implementing a feature or bug fix test-first, or when about to add or change a committed test. The house style it enforces is `.claude/rules/testing.md`; `tdd` holds the general theory (seams, anti-patterns). For browser-only proofs use /test.----# test-driven-development — red, green, refactor+# test-driven-development — prove first, commit only what earns it-The rule: **no production code without a failing test first.** A test written-after the code passes immediately — and a test you never saw fail proves-nothing: it may test the wrong thing, test the implementation instead of the-behavior, or miss the exact case you got wrong.+Two separate things happen in this loop, and confusing them is how the repo+filled up with tests that only confirmed their own change:-Already wrote code before the test? Stash or delete it, write the test, watch-it fail, then re-implement. Don't keep it open "as reference" — that is-writing tests after, with extra steps.+1. **Proof.** Before you trust a change, see a check fail without it and pass+ with it. Always.+2. **Regression guard.** A test committed to the repo, run on every change+ forever. Only when it passes the three questions in+ `.claude/rules/testing.md` (which bug turns it red, what seam, where the+ expected values come from).-## The cycle+Every guard is a proof. Most proofs are not guards. A proof that is not a+guard lives in your scratchpad or the run log, never in the repo.-### 1. RED — write one failing test+Read `.claude/rules/testing.md` before writing a test that will be committed:+it is the house style (pure cores tested by value, fixture builders with+overrides, `it.each` tables, behaviour-sentence names, mocks only at the+network / clock / filesystem).-One behavior per test, named for the behavior-(`"rejects a receipt line with zero quantity"`, not `"test1"`). Test real code;-mock only what you cannot run (network, clock). Copy setup from a sibling test-file in the same package.+## The loop-Where tests live: `packages/{pkg}/src/**/*.test.ts` or-`apps/erp/app/modules/{module}/__tests__/` (match the neighbors). Runner is-vitest via the `@carbon/config` preset.+### 1. RED — one failing check-### 2. Verify RED — watch it fail (mandatory, never skip)+One behaviour, named as a sentence (`"rejects a receipt line with zero+quantity"`). Decide the home first (rule → "Where a check lives"): pure core,+database test, conformance check, browser playbook, or scratch.```bashpnpm --filter <pkg> exec vitest run <path/to/file.test.ts>-# Expected: FAIL — assertion failure for the missing behavior+# Expected: FAIL — an assertion about the missing behaviour```-- Fails with an assertion about the missing behavior → proceed.-- **Passes** → it tests existing behavior; rewrite the test.-- **Errors** (import/type/syntax) → fix the error, re-run until it *fails- correctly*.-- Carbon gotcha: vitest runs with `passWithNoTests: true` — a green run that- collected **0 tests** proves nothing. Check the test count in the output.+- Fails on the assertion → go on.+- **Passes** → it tests behaviour that already exists. Rewrite it.+- **Errors** (import, type, syntax) → fix until it fails for the right reason.+- vitest runs with `passWithNoTests: true`: a green run that collected **0+ tests** proves nothing. Read the count.-### 3. GREEN — minimal code to pass+If the logic you need to prove is buried in glue (load → decide → write),+extract the decision into a pure function first and prove that. Don't mock+our own modules to reach it.-Write the simplest code that makes the test pass. No extra options, no-speculative parameters, no refactoring of neighboring code, nothing the test-doesn't demand.+### 2. GREEN — the least code that passes++No extra options, no speculative parameters, nothing the check doesn't+demand. Then run the package:```bash-pnpm --filter <pkg> exec vitest run <path/to/file.test.ts> # your test passes-pnpm --filter <pkg> test # the package still passes+pnpm --filter <pkg> exec vitest run <path/to/file.test.ts>+pnpm --filter <pkg> test```-Test fails → fix the code, not the test. Other tests fail → fix now, not later.+Check fails → fix the code, not the check. Another test fails → fix it now.-### 4. REFACTOR — only while green+### 3. KEEP OR SCRATCH-Remove duplication, improve names, extract helpers. No new behavior. Re-run the-package tests after. Then loop to the next failing test.+Ask the three questions. Then:-After editing tests, also typecheck the package —-`pnpm exec turbo run typecheck --filter=<pkg>` (never whole-repo). The repo uses-`noUncheckedIndexedAccess`: indexed access in assertions needs optional chaining-(`rows[0]?.id`), and that only surfaces in typecheck, not in the test run.+- **Keep**: tidy it to the house style. Fold it into the existing file's+ fixture builder or `it.each` table rather than appending a near-duplicate.+- **Scratch**: move it out of the repo (scratchpad, or quote it in the run+ log), and say in the commit message how the change was proven.-## Bug fixes+Typical scratch proofs: a wiring fix between two of our modules, "this+function is now called with X", a regex showing a migration contains a+clause, a test that the new constant has the new value.-A bug fix is TDD with the test written from the bug report: the failing test-reproduces the bug, the fix turns it green, and the test stays as the-regression guard. Never fix a bug without one (see `/fix`, which enforces this).+### 4. Typecheck-## Rationalizations — all of them mean "write the test first"+```bash+pnpm exec turbo run typecheck --filter=<pkg>+```-| Excuse | Reality |-|--------|---------|-| "Too simple to test" | Simple code breaks; the test costs 30 seconds |-| "I'll test after" | Passing-immediately proves nothing |-| "I manually tested it" | Not repeatable, no record, gone on the next change |-| "Deleting X hours of work is wasteful" | Sunk cost; unverified code is the actual debt |-| "Just this once / this is different" | The exception becomes the habit |-| "Test is hard to write" | Hard to test = hard to use; simplify the interface |+The repo uses `noUncheckedIndexedAccess`: indexed access in assertions needs+`rows[0]?.id`, which only typecheck surfaces.## Done when-- [ ] Every new behavior has a test you watched fail, for the right reason-- [ ] `pnpm --filter <pkg> test` green, with a non-zero collected-test count+- [ ] Each new behaviour was proven by a check you watched fail, for the right reason+- [ ] Every committed test passes the three questions; the rest are scratch+- [ ] `pnpm --filter <pkg> test` green with a non-zero test count- [ ] `pnpm exec turbo run typecheck --filter=<pkg>` green-- [ ] Output pristine — no stray warnings/errors you introduced--When adding mocks or test utilities, read-[testing-anti-patterns.md](testing-anti-patterns.md) first — it covers testing-mock behavior instead of real behavior, test-only methods on production-classes, and mocking without understanding the dependency.diff --git a/.claude/skills/test-driven-development/testing-anti-patterns.md b/.claude/skills/test-driven-development/testing-anti-patterns.mddeleted file mode 100644index e77ab6b6d6..0000000000--- a/.claude/skills/test-driven-development/testing-anti-patterns.md+++ /dev/null@@ -1,299 +0,0 @@-# Testing Anti-Patterns--**Load this reference when:** writing or changing tests, adding mocks, or tempted to add test-only methods to production code.--## Overview--Tests must verify real behavior, not mock behavior. Mocks are a means to isolate, not the thing being tested.--**Core principle:** Test what the code does, not what the mocks do.--**Following strict TDD prevents these anti-patterns.**--## The Iron Laws--```-1. NEVER test mock behavior-2. NEVER add test-only methods to production classes-3. NEVER mock without understanding dependencies-```--## Anti-Pattern 1: Testing Mock Behavior--**The violation:**-```typescript-// ❌ BAD: Testing that the mock exists-test('renders sidebar', () => {- render(<Page />);- expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument();-});-```--**Why this is wrong:**-- You're verifying the mock works, not that the component works-- Test passes when mock is present, fails when it's not-- Tells you nothing about real behavior--**your human partner's correction:** "Are we testing the behavior of a mock?"--**The fix:**-```typescript-// ✅ GOOD: Test real component or don't mock it-test('renders sidebar', () => {- render(<Page />); // Don't mock sidebar- expect(screen.getByRole('navigation')).toBeInTheDocument();-});--// OR if sidebar must be mocked for isolation:-// Don't assert on the mock - test Page's behavior with sidebar present-```--### Gate Function--```-BEFORE asserting on any mock element:- Ask: "Am I testing real component behavior or just mock existence?"-- IF testing mock existence:- STOP - Delete the assertion or unmock the component-- Test real behavior instead-```--## Anti-Pattern 2: Test-Only Methods in Production--**The violation:**-```typescript-// ❌ BAD: destroy() only used in tests-class Session {- async destroy() { // Looks like production API!- await this._workspaceManager?.destroyWorkspace(this.id);- // ... cleanup- }-}--// In tests-afterEach(() => session.destroy());-```--**Why this is wrong:**-- Production class polluted with test-only code-- Dangerous if accidentally called in production-- Violates YAGNI and separation of concerns-- Confuses object lifecycle with entity lifecycle--**The fix:**-```typescript-// ✅ GOOD: Test utilities handle test cleanup-// Session has no destroy() - it's stateless in production--// In test-utils/-export async function cleanupSession(session: Session) {- const workspace = session.getWorkspaceInfo();- if (workspace) {- await workspaceManager.destroyWorkspace(workspace.id);- }-}--// In tests-afterEach(() => cleanupSession(session));-```--### Gate Function--```-BEFORE adding any method to production class:- Ask: "Is this only used by tests?"-- IF yes:- STOP - Don't add it- Put it in test utilities instead-- Ask: "Does this class own this resource's lifecycle?"-- IF no:- STOP - Wrong class for this method-```--## Anti-Pattern 3: Mocking Without Understanding--**The violation:**-```typescript-// ❌ BAD: Mock breaks test logic-test('detects duplicate server', () => {- // Mock prevents config write that test depends on!- vi.mock('ToolCatalog', () => ({- discoverAndCacheTools: vi.fn().mockResolvedValue(undefined)- }));-- await addServer(config);- await addServer(config); // Should throw - but won't!-});-```--**Why this is wrong:**-- Mocked method had side effect test depended on (writing config)-- Over-mocking to "be safe" breaks actual behavior-- Test passes for wrong reason or fails mysteriously--**The fix:**-```typescript-// ✅ GOOD: Mock at correct level-test('detects duplicate server', () => {- // Mock the slow part, preserve behavior test needs- vi.mock('MCPServerManager'); // Just mock slow server startup-- await addServer(config); // Config written- await addServer(config); // Duplicate detected ✓-});-```--### Gate Function--```-BEFORE mocking any method:- STOP - Don't mock yet-- 1. Ask: "What side effects does the real method have?"- 2. Ask: "Does this test depend on any of those side effects?"- 3. Ask: "Do I fully understand what this test needs?"-- IF depends on side effects:- Mock at lower level (the actual slow/external operation)- OR use test doubles that preserve necessary behavior- NOT the high-level method the test depends on-- IF unsure what test depends on:- Run test with real implementation FIRST- Observe what actually needs to happen- THEN add minimal mocking at the right level-- Red flags:- - "I'll mock this to be safe"- - "This might be slow, better mock it"- - Mocking without understanding the dependency chain-```--## Anti-Pattern 4: Incomplete Mocks--**The violation:**-```typescript-// ❌ BAD: Partial mock - only fields you think you need-const mockResponse = {- status: 'success',- data: { userId: '123', name: 'Alice' }- // Missing: metadata that downstream code uses-};--// Later: breaks when code accesses response.metadata.requestId-```--**Why this is wrong:**-- **Partial mocks hide structural assumptions** - You only mocked fields you know about-- **Downstream code may depend on fields you didn't include** - Silent failures-- **Tests pass but integration fails** - Mock incomplete, real API complete-- **False confidence** - Test proves nothing about real behavior--**The Iron Rule:** Mock the COMPLETE data structure as it exists in reality, not just fields your immediate test uses.--**The fix:**-```typescript-// ✅ GOOD: Mirror real API completeness-const mockResponse = {- status: 'success',- data: { userId: '123', name: 'Alice' },- metadata: { requestId: 'req-789', timestamp: 1234567890 }- // All fields real API returns-};-```--### Gate Function--```-BEFORE creating mock responses:- Check: "What fields does the real API response contain?"-- Actions:- 1. Examine actual API response from docs/examples- 2. Include ALL fields system might consume downstream- 3. Verify mock matches real response schema completely-- Critical:- If you're creating a mock, you must understand the ENTIRE structure- Partial mocks fail silently when code depends on omitted fields-- If uncertain: Include all documented fields-```--## Anti-Pattern 5: Integration Tests as Afterthought--**The violation:**-```-✅ Implementation complete-❌ No tests written-"Ready for testing"-```--**Why this is wrong:**-- Testing is part of implementation, not optional follow-up-- TDD would have caught this-- Can't claim complete without tests--**The fix:**-```-TDD cycle:-1. Write failing test-2. Implement to pass-3. Refactor-4. THEN claim complete-```--## When Mocks Become Too Complex--**Warning signs:**-- Mock setup longer than test logic-- Mocking everything to make test pass-- Mocks missing methods real components have-- Test breaks when mock changes--**your human partner's question:** "Do we need to be using a mock here?"--**Consider:** Integration tests with real components often simpler than complex mocks--## TDD Prevents These Anti-Patterns--**Why TDD helps:**-1. **Write test first** → Forces you to think about what you're actually testing-2. **Watch it fail** → Confirms test tests real behavior, not mocks-3. **Minimal implementation** → No test-only methods creep in-4. **Real dependencies** → You see what the test actually needs before mocking--**If you're testing mock behavior, you violated TDD** - you added mocks without watching test fail against real code first.--## Quick Reference--| Anti-Pattern | Fix |-|--------------|-----|-| Assert on mock elements | Test real component or unmock it |-| Test-only methods in production | Move to test utilities |-| Mock without understanding | Understand dependencies first, mock minimally |-| Incomplete mocks | Mirror real API completely |-| Tests as afterthought | TDD - tests first |-| Over-complex mocks | Consider integration tests |--## Red Flags--- Assertion checks for `*-mock` test IDs-- Methods only called in test files-- Mock setup is >50% of test-- Test fails when you remove mock-- Can't explain why mock is needed-- Mocking "just to be safe"--## The Bottom Line--**Mocks are tools to isolate, not things to test.**--If TDD reveals you're testing mock behavior, you've gone wrong.--Fix: Test real behavior or question why you're mocking at all.diff --git a/.github/workflows/check.yml b/.github/workflows/check.ymlindex 7ec9c95691..1deb0bdb9c 100644--- a/.github/workflows/check.yml+++ b/.github/workflows/check.yml@@ -13,56 +13,30 @@ concurrency:group: ${{ github.workflow }}-${{ github.ref }}cancel-in-progress: true+# Three jobs that need the workspace installed, started together: a job is a+# fresh runner, and its setup (about a minute) cost more than most checks.+# Test is the longest, so nothing waits in front of it.jobs:- install:- name: Install- runs-on: ubuntu-latest- steps:- - uses: actions/checkout@v7- - uses: pnpm/action-setup@v6- - uses: actions/setup-node@v7- with:- node-version-file: .nvmrc- cache: pnpm-- - uses: actions/cache@v6- id: node-modules-cache- with:- path: |- node_modules- apps/*/node_modules- docs/node_modules- packages/*/node_modules- key: node-modules-${{ hashFiles('pnpm-lock.yaml') }}-- # Turborepo's local cache, carried between runs: the postinstall- # (fonts), the MCP manifest, typecheck and test restore instead of re-running- # for packages whose inputs did not change. Keyed per job so each job- # saves its own tasks; it only ever grows, so bump the prefix to reset it.- - uses: actions/cache@v6- with:- path: .turbo/cache- key: turbo-v1-${{ github.job }}-${{ github.sha }}- restore-keys: |- turbo-v1-${{ github.job }}--- # Always install so the postinstall generates the gitignored font data.- - run: pnpm install --frozen-lockfile-lint:name: Lint- needs: installruns-on: ubuntu-lateststeps:- - uses: actions/checkout@v7- - uses: pnpm/action-setup@v6- - uses: actions/setup-node@v7+ # These jobs run the pull request's code, so the token is not left in+ # .git/config for it to read; nothing here talks to git afterwards.+ - &checkout+ uses: actions/checkout@v7+ with:+ persist-credentials: false+ - &pnpm+ uses: pnpm/action-setup@v6+ # No pnpm store cache: it is keyed on the lockfile, as node_modules+ # below is, so it only ever restored what node_modules already had.+ - &node+ uses: actions/setup-node@v7with:node-version-file: .nvmrc- cache: pnpm-- - uses: actions/cache@v6- id: node-modules-cache+ - &node-modules+ uses: actions/cache@v6with:path: |node_modules@@ -70,179 +44,60 @@ jobs:docs/node_modulespackages/*/node_moduleskey: node-modules-${{ hashFiles('pnpm-lock.yaml') }}-# Turborepo's local cache, carried between runs: the postinstall- # (fonts), the MCP manifest, typecheck and test restore instead of re-running- # for packages whose inputs did not change. Keyed per job so each job- # saves its own tasks; it only ever grows, so bump the prefix to reset it.- - uses: actions/cache@v6+ # (fonts), the MCP manifest, typecheck and test restore instead of+ # re-running for packages whose inputs did not change. Keyed per job so+ # each job saves its own tasks; it only ever grows, so bump the prefix+ # to reset it.+ - &turbo+ uses: actions/cache@v6with:path: .turbo/cachekey: turbo-v1-${{ github.job }}-${{ github.sha }}restore-keys: |turbo-v1-${{ github.job }}--# Always install so the postinstall generates the gitignored font data.- - run: pnpm install --frozen-lockfile+ - &install+ run: pnpm install --frozen-lockfile- run: pnpm exec biome check-- name: Conformance checksrun: |pnpm --filter @carbon/config buildpnpm --filter @carbon/checks exec vitest run src/run.test.ts+ - name: Lingui+ if: ${{ !cancelled() }}+ run: pnpm run lingui:check+ - name: Catalog+ if: ${{ !cancelled() }}+ run: pnpm run check:workflow-catalog+ - name: Audit+ if: ${{ !cancelled() }}+ run: pnpm audit --audit-level=criticaltypecheck:name: Typecheck- needs: installruns-on: ubuntu-lateststeps:- - uses: actions/checkout@v7- - uses: pnpm/action-setup@v6- - uses: actions/setup-node@v7- with:- node-version-file: .nvmrc- cache: pnpm-- - uses: actions/cache@v6- id: node-modules-cache- with:- path: |- node_modules- apps/*/node_modules- docs/node_modules- packages/*/node_modules- key: node-modules-${{ hashFiles('pnpm-lock.yaml') }}-- # Turborepo's local cache, carried between runs: the postinstall- # (fonts), the MCP manifest, typecheck and test restore instead of re-running- # for packages whose inputs did not change. Keyed per job so each job- # saves its own tasks; it only ever grows, so bump the prefix to reset it.- - uses: actions/cache@v6- with:- path: .turbo/cache- key: turbo-v1-${{ github.job }}-${{ github.sha }}- restore-keys: |- turbo-v1-${{ github.job }}--- # Always install so the postinstall generates the gitignored font data.- - run: pnpm install --frozen-lockfile-+ - *checkout+ - *pnpm+ - *node+ - *node-modules+ - *turbo+ - *install- run: pnpm run typegen- run: pnpm run typecheck- lingui:- name: Lingui- needs: install- runs-on: ubuntu-latest- steps:- - uses: actions/checkout@v7- - uses: pnpm/action-setup@v6- - uses: actions/setup-node@v7- with:- node-version-file: .nvmrc- cache: pnpm-- - uses: actions/cache@v6- id: node-modules-cache- with:- path: |- node_modules- apps/*/node_modules- docs/node_modules- packages/*/node_modules- key: node-modules-${{ hashFiles('pnpm-lock.yaml') }}-- # Turborepo's local cache, carried between runs: the postinstall- # (fonts), the MCP manifest, typecheck and test restore instead of re-running- # for packages whose inputs did not change. Keyed per job so each job- # saves its own tasks; it only ever grows, so bump the prefix to reset it.- - uses: actions/cache@v6- with:- path: .turbo/cache- key: turbo-v1-${{ github.job }}-${{ github.sha }}- restore-keys: |- turbo-v1-${{ github.job }}--- # Always install so the postinstall generates the gitignored font data.- - run: pnpm install --frozen-lockfile-- - run: pnpm run lingui:check-- catalog:- name: Catalog- needs: install- runs-on: ubuntu-latest- steps:- - uses: actions/checkout@v7- - uses: pnpm/action-setup@v6- - uses: actions/setup-node@v7- with:- node-version-file: .nvmrc- cache: pnpm-- - uses: actions/cache@v6- id: node-modules-cache- with:- path: |- node_modules- apps/*/node_modules- docs/node_modules- packages/*/node_modules- key: node-modules-${{ hashFiles('pnpm-lock.yaml') }}-- # Turborepo's local cache, carried between runs: the postinstall- # (fonts), the MCP manifest, typecheck and test restore instead of re-running- # for packages whose inputs did not change. Keyed per job so each job- # saves its own tasks; it only ever grows, so bump the prefix to reset it.- - uses: actions/cache@v6- with:- path: .turbo/cache- key: turbo-v1-${{ github.job }}-${{ github.sha }}- restore-keys: |- turbo-v1-${{ github.job }}--- # Always install so the postinstall generates the gitignored font data.- - run: pnpm install --frozen-lockfile-- - run: pnpm run check:workflow-catalog-test:name: Test- needs: installruns-on: ubuntu-lateststeps:- - uses: actions/checkout@v7- - uses: pnpm/action-setup@v6- - uses: actions/setup-node@v7- with:- node-version-file: .nvmrc- cache: pnpm-- - uses: actions/cache@v6- id: node-modules-cache- with:- path: |- node_modules- apps/*/node_modules- docs/node_modules- packages/*/node_modules- key: node-modules-${{ hashFiles('pnpm-lock.yaml') }}-- # Turborepo's local cache, carried between runs: the postinstall- # (fonts), the MCP manifest, typecheck and test restore instead of re-running- # for packages whose inputs did not change. Keyed per job so each job- # saves its own tasks; it only ever grows, so bump the prefix to reset it.- - uses: actions/cache@v6- with:- path: .turbo/cache- key: turbo-v1-${{ github.job }}-${{ github.sha }}- restore-keys: |- turbo-v1-${{ github.job }}--- # Always install so the postinstall generates the gitignored font data.- - run: pnpm install --frozen-lockfile-+ - *checkout+ - *pnpm+ - *node+ - *node-modules+ - *turbo+ - *install- run: pnpm testedge-functions:@@ -271,25 +126,12 @@ jobs:working-directory: packages/database/supabase/functionsrun: deno check --no-lock */index.ts- audit:- name: Audit- runs-on: ubuntu-latest- steps:- - uses: actions/checkout@v7- - uses: pnpm/action-setup@v6- - uses: actions/setup-node@v7- with:- node-version-file: .nvmrc-- - run: pnpm audit --audit-level=critical-# The result as a PR label, for filtering the PR list. Here rather than a# workflow_run, which GitHub pins to main's latest commit. Not on PRs from# forks: their token cannot edit the PR.label:name: Label- needs:- [install, lint, typecheck, lingui, catalog, test, edge-functions, audit]+ needs: [lint, typecheck, test, edge-functions]if: >-!cancelled() &&github.event.pull_request.head.repo.full_name == github.repositorydiff --git a/AGENTS.md b/AGENTS.mdindex ef729d6cce..6aaa6a137a 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -175,7 +175,8 @@ IMPORTANT: Before any research or coding, match the task to this table. A single| Repo audit → handoff plans | `.claude/skills/improve/SKILL.md` || Review your own branch before PR | `.claude/skills/self-review/SKILL.md` || Resolving a merge or rebase conflict (always) | `.claude/skills/resolving-merge-conflicts/SKILL.md` |-| Test-first work: good tests, seams, anti-patterns | `.claude/skills/tdd/SKILL.md` + `.claude/skills/test-driven-development/SKILL.md` |+| Writing, reviewing or deleting a test (house style, where a check lives) | `.claude/rules/testing.md` |+| Test-first work: the red→green loop, proof vs committed test | `.claude/skills/test-driven-development/SKILL.md` + `.claude/skills/tdd/SKILL.md` |## Core Principlesdiff --git a/Dockerfile b/Dockerfileindex b010e930e4..985e128c93 100644--- a/Dockerfile+++ b/Dockerfile@@ -71,7 +71,7 @@ RUN find node_modules/.pnpm -maxdepth 1 -type d \( \-name 'sst@*' -o -name 'sst-linux-*' -o -name 'sst-darwin-*' -o -name 'sst-win32-*' -o \-name '@biomejs+*' -o \-name 'turbo@*' -o -name '@turbo+*' -o \- -name 'typescript@*' -o -name '@typescript+native-preview*' -o \+ -name 'typescript@*' -o \-name 'ts-morph@*' -o -name '@ts-morph+*' -o \-name 'vite@*' -o -name 'rolldown@*' -o -name '@rolldown+*' -o \-name 'vitest@*' -o -name '@vitest+*' -o \@@ -100,42 +100,21 @@ CMD ["bash"]FROM bootstrap AS ops# --- Runtime dependency tree -----------------------------------------------# Runs in its own stage: done in `runner` after the COPY, a delete reclaims-# nothing. Strips build CLIs/binaries (the remaining Trivy CRITICAL/HIGHs; the-# `sst` JS package is kept, only its CLI binary goes; `tar`'s sole consumer is-# the supabase CLI and its fix is unpublished), packages the lockfile hydrates-# but nothing links (a frozen install materializes every importer, docs/-# included — hence next/@mui; react-icons is inlined via ssr.noExternal), and-# sourcemaps/.d.ts/readmes. react-email 6 ships its CLI in the runtime package:-# the runtime entry imports only @react-email/render, css-tree, marked, prismjs-# and tailwindcss, so the preview UI and the CLI-only deps nothing else in the-# lockfile uses go. Verify additions the same way — monaco-editor looks-# strippable but the server bundle imports @monaco-editor/react.-FROM deps AS pruned+# The app's production dependencies, installed on their own: what the built+# server loads from node_modules. The bundle inlines everything else, so that+# is @carbon/serve, which `pnpm start` runs from source, and whatever the+# bundle leaves external (erp's AI SDK). Every package lists in+# `dependencies` only what its runtime code imports, so no build tool, CLI or+# test runner is installed here. Its own stage, so the files it deletes leave+# no layer behind in `runner`.+FROM deps AS prod-deps+ARG APPARG SOURCEMAPS-RUN find node_modules/.pnpm -maxdepth 1 -type d \( \- -name 'sst-linux-*' -o -name 'sst-darwin-*' -o -name 'sst-win32-*' -o \- -name 'esbuild@*' -o -name '@esbuild+*' -o \- -name 'supabase@*' -o \- -name 'tar@*' -o \- -name 'npm@*' -o \- -name '@typescript+native-preview-*' -o \- -name '@biomejs+*' -o \- -name 'turbo@*' -o -name 'turbo-linux-*' -o -name 'turbo-darwin-*' -o \- -name '@turbo+*' -o \- -name '@rolldown+binding-*' -o \- -name 'vitest@*' -o -name '@vitest+*' -o \- -name '@react-email+ui@*' -o \- -name 'socket.io@*' -o -name 'socket.io-adapter@*' -o -name 'engine.io@*' -o \- -name 'conf@*' -o -name 'nypm@*' -o -name 'picospinner@*' -o -name 'prompts@*' -o \- -name 'tsconfig-paths@*' -o \- -name 'next@*' -o -name '@next+*' -o \- -name '@mui+*' -o \- -name 'react-icons@*' \- \) -prune -exec rm -rf {} + ; \- find node_modules -type d -name '@esbuild' -prune -exec rm -rf {} + 2>/dev/null || true ; \- find packages -type d \( -name '.ignored_*' -o -name '.vite' \) -prune -exec rm -rf {} + 2>/dev/null || true ; \- find node_modules -type f \( -name '*.d.ts' -o -name '*.d.mts' \+RUN rm -rf node_modules apps/*/node_modules packages/*/node_modules docs/content/node_modules+RUN --mount=type=cache,id=pnpm-store,target=/pnpm/store,sharing=locked \+ pnpm install --prod --frozen-lockfile --prefer-offline --ignore-scripts --filter-prod "${APP}..."+COPY --from=build /repo/apps/${APP}/build ./apps/${APP}/build+RUN find node_modules -type f \( -name '*.d.ts' -o -name '*.d.mts' \-o -name '*.d.cts' -o -name '*.md' \) -delete 2>/dev/null || true ; \if [ "${SOURCEMAPS}" != "1" ]; then \find node_modules -type f -name '*.map' -delete 2>/dev/null || true ; \@@ -151,9 +130,9 @@ ENV PORT=3000# Date derivation assumes UTC until company/location timezones are threaded everywhereENV TZ=UTCCOPY --from=deps /repo/package.json /repo/pnpm-lock.yaml /repo/pnpm-workspace.yaml /repo/.npmrc ./-COPY --from=pruned /repo/node_modules ./node_modules-COPY --from=pruned /repo/packages ./packages-COPY --from=build /repo/apps/${APP} ./apps/${APP}+COPY --from=prod-deps /repo/node_modules ./node_modules+COPY --from=prod-deps /repo/packages ./packages+COPY --from=prod-deps /repo/apps/${APP} ./apps/${APP}# The base image's npm is unused (corepack/pnpm only) and vendors the last Trivy CRITICALs.RUN rm -rf /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npxEXPOSE 3000diff --git a/apps/academy/package.json b/apps/academy/package.jsonindex 99ce388942..586b33e6c3 100644--- a/apps/academy/package.json+++ b/apps/academy/package.json@@ -61,7 +61,7 @@"dev": "NODE_EXTRA_CA_CERTS=$HOME/.portless/ca.pem react-router dev","lint": "biome lint --write","start": "react-router-serve ./build/server/index.js",- "typecheck": "react-router typegen && tsgo --noEmit",+ "typecheck": "react-router typegen && tsc --noEmit","typegen": "react-router typegen"},"sideEffects": [diff --git a/apps/erp/app/components/CSVLink.tsx b/apps/erp/app/components/CSVLink.tsxindex 551c1c9ba1..4da4c4a657 100644--- a/apps/erp/app/components/CSVLink.tsx+++ b/apps/erp/app/components/CSVLink.tsx@@ -6,7 +6,7 @@ import type { ComponentType } from "react";import { CSVLink as BaseCSVLink } from "react-csv";// `@types/react-csv` types CSVLink as a class whose `React.Component` signature is-// incompatible with the current React types under tsgo ("Property 'refs' is missing+// incompatible with the current React types under TypeScript 7 ("Property 'refs' is missing// in type Component<LinkProps>" → TS2786). Re-export it cast to a plain component// type so it's usable as JSX. Props stay loose — callers already pass the right shape.export const CSVLink = BaseCSVLink as unknown as ComponentType<diff --git a/apps/erp/app/modules/accounting/AGENTS.md b/apps/erp/app/modules/accounting/AGENTS.mdindex c3e3c1dabc..de6faef63c 100644--- a/apps/erp/app/modules/accounting/AGENTS.md+++ b/apps/erp/app/modules/accounting/AGENTS.md@@ -317,7 +317,7 @@ pnpm exec turbo run typecheck --filter=erppnpm --dir apps/erp exec vitest run app/modules/accounting```-`lease-run-posting.test.ts` (a lease run stamps `leaseScheduleLine.journalId` / `postedAt`, Reverse Run clears them) runs `postRevenueRecognitionRun` / `reverseRevenueRecognitionRun` against the local database. `vitest.config.ts` stubs `SUPABASE_DB_URL` for every ERP test, so it reads the URL from the repository's `.env.local` and skips when there is none or it is not local. It builds on `leaseFixture` and `holdInDraftRun` (`apps/erp/test/database/fixtures/lease.ts`, `run.ts`).+`apps/erp/test/database/post-lease/lease-run.test.ts` (a lease run stamps `leaseScheduleLine.journalId` / `postedAt`, Reverse Run clears them) runs `postRevenueRecognitionRun` / `reverseRevenueRecognitionRun` against the local database through `databaseTest`, which skips unless `SUPABASE_DB_URL` points at a local host. It builds on `leaseFixture` and `holdInDraftRun` (`apps/erp/test/database/fixtures/lease.ts`, `run.ts`).## Key Data Modeldiff --git a/apps/erp/app/modules/accounting/accounting.defaults.test.ts b/apps/erp/app/modules/accounting/accounting.defaults.test.tsindex b3cbc1de36..d5e3248eea 100644--- a/apps/erp/app/modules/accounting/accounting.defaults.test.ts+++ b/apps/erp/app/modules/accounting/accounting.defaults.test.ts@@ -2,60 +2,9 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import type { Database } from "@carbon/database";import type { SupabaseClient } from "@supabase/supabase-js";import { describe, expect, it, vi } from "vitest";--vi.mock("~/modules/settings/settings.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- getNextSequence: vi.fn()-}));-vi.mock("@carbon/content/glossary", () => ({- terms: {},- glossaryEntries: () => []-}));-vi.mock("@carbon/auth", async (importOriginal) => ({- ...(await importOriginal<object>()),- assertIsPost: () => undefined,- getMESUrl: () => "http://localhost",- getAppUrl: () => "http://localhost",- CARBON_API_URL: "http://localhost",- error: (cause: unknown, message: string) => ({ cause, message }),- success: (message: string) => ({ message })-}));-vi.mock("@carbon/auth/auth.server", () => ({ requirePermissions: vi.fn() }));-vi.mock("@carbon/auth/session.server", () => ({- flash: vi.fn(async () => ({}))-}));-vi.mock("@carbon/react", () => ({- ScrollArea: () => null,- VStack: () => null-}));-vi.mock("@carbon/form", () => ({- validator: (schema: {- safeParse: (input: unknown) => {- success: boolean;- data?: unknown;- error?: unknown;- };- }) => ({- validate: async (form: FormData) => {- const parsed = schema.safeParse(Object.fromEntries(form));- return parsed.success ? { data: parsed.data } : { error: parsed.error };- }- }),- validationError: (error: unknown) => ({ error })-}));-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("~/hooks", () => ({ useRouteData: vi.fn() }));-vi.mock("~/modules/accounting/ui/AccountDefaults", () => ({- AccountDefaultsForm: () => null-}));-import {defaultAccountValidator,defaultIncomeAcountValidator@@ -144,30 +93,6 @@ function payload(overrides: Record<string, string> = {}) {}describe("shipping revenue defaults", () => {- it("the real defaults action rejects an invalid shipping mapping before either section writes", async () => {- const { client, writes } = database({ ...shipping, active: false });- vi.mocked(requirePermissions).mockResolvedValue({- client,- companyId: "company",- userId: "user"- } as never);- const body = new FormData();- for (const field of Object.keys(defaultAccountValidator.shape))- body.set(field, `${field}-id`);- body.set("salesAccount", "sales");- body.set("salesShippingRevenueAccount", "shipping");- body.set("intent", "all");- const { action } = await import("~/routes/x+/accounting+/defaults");- await action({- request: new Request("http://localhost/x/accounting/defaults", {- method: "POST",- body- }),- params: {},- context: {}- } as never);- expect(writes).not.toHaveBeenCalled();- });it("preserves the incoming shipping field and rejects present empty values", () => {expect(defaultIncomeAcountValidator.parse({@@ -261,63 +186,3 @@ describe("shipping revenue defaults", () => {expect(writes).not.toHaveBeenCalled();});});--describe("combined defaults action", () => {- async function submit(client: SupabaseClient<Database>) {- vi.mocked(requirePermissions).mockResolvedValue({- client,- companyId: "company",- userId: "user"- } as never);- const body = new FormData();- for (const field of Object.keys(defaultAccountValidator.shape))- body.set(field, `${field}-new`);- body.set("salesAccount", "sales");- body.set("salesShippingRevenueAccount", "shipping");- body.set("intent", "all");- const { action } = await import("~/routes/x+/accounting+/defaults");- return action({- request: new Request("http://localhost/x/accounting/defaults", {- method: "POST",- body- }),- params: {},- context: {}- } as never);- }-- it("saves the full form as one statement", async () => {- const { client, writes } = database();- await expect(submit(client)).rejects.toMatchObject({ status: 302 });- expect(writes).toHaveBeenCalledOnce();- expect(writes).toHaveBeenCalledWith(- "accountDefault",- expect.objectContaining({- companyId: "company",- salesShippingRevenueAccount: "shipping",- receivablesAccount: "receivablesAccount-new"- })- );- });-- it("leaves both sections unchanged when the mapping is rejected", async () => {- const { client, writes, rows } = database({ ...shipping, active: false });- const original = structuredClone(rows.accountDefault);- await submit(client);- expect(writes).not.toHaveBeenCalled();- expect(rows.accountDefault).toEqual(original);- });-- it("shows the actual shipping mapping validation error", async () => {- vi.mocked(flash).mockClear();- const { client } = database({ ...shipping, active: false });- await submit(client);- expect(flash).toHaveBeenCalledWith(- expect.any(Request),- expect.objectContaining({- message:- "Shipping revenue must be an active Revenue leaf account in this company group"- })- );- });-});diff --git a/apps/erp/app/modules/accounting/accounting.journals.test.ts b/apps/erp/app/modules/accounting/accounting.journals.test.tsindex c5cb17762b..0b24352609 100644--- a/apps/erp/app/modules/accounting/accounting.journals.test.ts+++ b/apps/erp/app/modules/accounting/accounting.journals.test.ts@@ -2,81 +2,29 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { describe, expect, it, vi } from "vitest";--// The settings barrel re-exports its UI, which pulls Lingui `msg` macros that-// vitest does not transform; the glossary evaluates them at module load.-// Nothing under test touches either.-vi.mock("~/modules/settings/settings.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- getNextSequence: vi.fn()-}));-vi.mock("@carbon/content/glossary", () => ({- getDefinitionText: () => "",- getEntry: () => undefined,- getTermText: () => "",- glossaryEntries: () => [],- hasEntry: () => false,- listEntries: () => [],- lookupEntry: () => undefined,- termSlug: (t: string) => t,- terms: {}-}));--import { getJournalEntries } from "./accounting.service";--/** A query builder that records every filter call made on it. */-function recordingClient() {- const calls: [string, ...unknown[]][] = [];- const builder: any = new Proxy(- {},- {- get: (_target, method: string) => {- if (method === "then") return undefined;- return (...args: unknown[]) => {- calls.push([method, ...args]);- return builder;- };- }- }- );- return { client: { from: () => builder } as any, calls };-}--const listArgs = { search: null, status: null, limit: 25, offset: 0 };--describe("getJournalEntries", () => {- it("hides Superseded journals when no status is asked for", async () => {- const { client, calls } = recordingClient();- await getJournalEntries(client, "C1", listArgs);- expect(calls).toContainEqual(["neq", "status", "Superseded"]);- });-- it("shows Superseded journals when the status param asks for them", async () => {- const { client, calls } = recordingClient();- await getJournalEntries(client, "C1", {- ...listArgs,- status: "Superseded"- });- expect(calls).toContainEqual(["eq", "status", "Superseded"]);- expect(calls).not.toContainEqual(["neq", "status", "Superseded"]);- });-- it("leaves the status to a table filter on status", async () => {- const { client, calls } = recordingClient();- await getJournalEntries(client, "C1", {- ...listArgs,- filters: [{ column: "status", operator: "eq", value: "Superseded" }]- });- expect(calls).not.toContainEqual(["neq", "status", "Superseded"]);- });+import { expect, it } from "vitest";+import { hidesSupersededJournals } from "./accounting.utils";++it.each([+ ["no status is asked for", { status: null }],+ [+ "a filter on another column has a value",+ { status: null, filters: [{ column: "sourceType", value: "Manual" }] }+ ],+ [+ "a status filter has no value",+ { status: null, filters: [{ column: "status", value: "" }] }+ ]+])("hides Superseded journals when %s", (_label, args) => {+ expect(hidesSupersededJournals(args)).toBe(true);+});- it("still hides them when a filter on another column has a value", async () => {- const { client, calls } = recordingClient();- await getJournalEntries(client, "C1", {- ...listArgs,- filters: [{ column: "sourceType", operator: "eq", value: "Manual" }]- });- expect(calls).toContainEqual(["neq", "status", "Superseded"]);- });+it.each([+ ["the status param asks for one", { status: "Superseded" }],+ [+ "a table filter on status has a value",+ { status: null, filters: [{ column: "status", value: "Superseded" }] }+ ]+])("shows Superseded journals when %s", (_label, args) => {+ expect(hidesSupersededJournals(args)).toBe(false);});diff --git a/apps/erp/app/modules/accounting/accounting.periods.test.ts b/apps/erp/app/modules/accounting/accounting.periods.test.tsindex 625f08c49f..8073f258c4 100644--- a/apps/erp/app/modules/accounting/accounting.periods.test.ts+++ b/apps/erp/app/modules/accounting/accounting.periods.test.ts@@ -2,440 +2,22 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-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-// getNextSequence from it, which these tests never exercise — stub it to keep-// the import graph light and macro-free.-vi.mock("~/modules/settings/settings.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- getNextSequence: vi.fn()-}));--// @carbon/content/glossary's terms.ts evaluates Lingui `msg` macros at module load,-// which vitest doesn't transform. Nothing under test touches the glossary, so-// stub the whole package.-vi.mock("@carbon/content/glossary", () => ({- getDefinitionText: () => "",- getEntry: () => undefined,- getTermText: () => "",- glossaryEntries: () => [],- hasEntry: () => false,- listEntries: () => [],- lookupEntry: () => undefined,- termSlug: (t: string) => t,- terms: {}-}));-+import { describe, expect, it } from "vitest";import type {PeriodCloseTaskRow,PeriodReadinessCheck,PeriodRunPreview} from "./accounting.service";import {- ACCOUNTING_NOT_STARTED,checklistTasksToCreate,- closeAccountingPeriod,- computePeriodReadiness,- createFiscalYearPeriods,- deleteAccountingPeriod,evaluateCloseChecklist,- getAccountingPeriodDeletability,- getFiscalCalendarCommitted,- getOrCreateAccountingPeriod,- lockAccountingPeriod,- postJournalEntry,- reopenAccountingPeriod,- requireAccountingCutover,- skipCloseTask+ periodRunChecks} from "./accounting.service";--// ----------------------------------------------------------------------------// Sequential close / reverse-sequential reopen gates (acceptance criteria 4/5)-//-// These exercise the real service functions against a scripted fake supabase-// client. Each awaited query (or `.single()`) shifts the next scripted result-// off the queue, in the exact order the function issues them:-// close: getAccountingPeriodById -> earlierOpen count -> update-// reopen: getAccountingPeriodById -> laterClosed count -> update-// -----------------------------------------------------------------------------type Scripted = { data?: unknown; count?: number; error?: unknown };--function makeClient(responses: Scripted[]) {- let i = 0;- const next = () => responses[i++] ?? { data: null, error: null };- const builder: any = {- select: () => builder,- insert: () => builder,- update: () => builder,- delete: () => builder,- eq: () => builder,- neq: () => builder,- in: () => builder,- lt: () => builder,- gt: () => builder,- gte: () => builder,- lte: () => builder,- or: () => builder,- order: () => builder,- limit: () => builder,- not: () => builder,- is: () => builder,- range: () => builder,- single: () => Promise.resolve(next()),- maybeSingle: () => Promise.resolve(next()),- then: (resolve: (v: Scripted) => unknown) => resolve(next())- };- return { from: () => builder } as any;-}--// Like makeClient but records every `.update(values)` keyed by table, so tests-// can assert which rows a service persisted (and in what state), not just its-// return value. The shared response queue advances in issue order exactly as in-// makeClient; a fresh builder per `from(table)` carries the table name through.-function makeRecordingClient(responses: Scripted[]) {- let i = 0;- const next = () => responses[i++] ?? { data: null, error: null };- const updates: { table: string; values: any }[] = [];- const makeBuilder = (table: string) => {- const builder: any = {- select: () => builder,- insert: () => builder,- upsert: () => builder,- update: (values: any) => {- updates.push({ table, values });- return builder;- },- eq: () => builder,- neq: () => builder,- in: () => builder,- lt: () => builder,- gt: () => builder,- gte: () => builder,- lte: () => builder,- or: () => builder,- order: () => builder,- limit: () => builder,- not: () => builder,- is: () => builder,- range: () => builder,- single: () => Promise.resolve(next()),- maybeSingle: () => Promise.resolve(next()),- then: (resolve: (v: Scripted) => unknown) => resolve(next())- };- return builder;- };- return { client: { from: (t: string) => makeBuilder(t) } as any, updates };-}--// The close path flips periodCloseTask + accountingPeriod through the Kysely-// client inside a single transaction. This records every `.set(values)` keyed-// by table so tests can assert the persisted state, mirroring the supabase-// recording client above. `.execute()` resolves empty — the service ignores the-// result and returns `{ id: periodId }` on a clean transaction.-function makeKyselyRecorder() {- const updates: { table: string; values: any }[] = [];- // Raw statements executed on the transaction. The close path snapshots GL- // balances via `sql`SELECT "snapshotAccountingPeriodBalances"(...)`.execute(trx)`- // after the period flip, so `tx` must satisfy Kysely's RawBuilder.execute- // (which reads `trx.getExecutor()`). We don't parse the SQL — recording that a- // raw statement ran is enough to assert the snapshot fired. The executor is a- // Proxy so it tolerates whatever internal methods RawBuilder.execute calls.- const rawExecutions: unknown[] = [];- const executor = new Proxy(- {},- {- get(_t, prop) {- if (prop === "executeQuery")- return async (compiled: unknown) => {- rawExecutions.push(compiled);- return { rows: [] };- };- if (prop === "transformQuery") return (node: unknown) => node;- if (prop === "compileQuery")- return (node: unknown) => ({ sql: "", parameters: [], query: node });- if (prop === "provideConnection")- return async (fn: (c: unknown) => unknown) =>- fn({- executeQuery: async (compiled: unknown) => {- rawExecutions.push(compiled);- return { rows: [] };- }- });- return () => undefined;- }- }- );- const tx = {- updateTable(table: string) {- const builder: any = {- set: (values: any) => {- updates.push({ table, values });- return builder;- },- where: () => builder,- execute: () => Promise.resolve([])- };- return builder;- },- getExecutor: () => executor- };- const db: any = {- transaction: () => ({- execute: async (fn: (t: unknown) => Promise<unknown>) => {- await fn(tx);- }- })- };- return { db, updates, rawExecutions };-}--const args = {- periodId: "P2",- companyId: "C1",- companyGroupId: "G1",- userId: "U1"-};--// What new runs would hold. The close path takes it as a function so these-// tests need no server function or depreciation reads.-const nothingDue: PeriodRunPreview = {- revenue: { count: 0, amount: 0, error: null },- lease: { count: 0, amount: 0, error: null },- depreciation: { count: 0, amount: 0, error: null }-};-const noRunsDue = async () => nothingDue;--describe("closeAccountingPeriod — sequential close", () => {- it("rejects closing period N while an earlier period is not Closed", async () => {- const client = makeClient([- { data: { accountingCutoverDate: "2026-01-01" } }, // requireAccountingCutover- { data: { id: "P2", startDate: "2026-02-01", closeStatus: "Locked" } },- { count: 1 } // one earlier period still open- ]);- const { db } = makeKyselyRecorder();-- const result = await closeAccountingPeriod(client, db, args, noRunsDue);-- expect(result.error).toBeTruthy();- expect(result.error?.message).toMatch(/sequential close/i);- expect(result.data).toBeNull();- });-- it("rejects closing a period that is not yet Locked", async () => {- const client = makeClient([- { data: { accountingCutoverDate: "2026-01-01" } }, // requireAccountingCutover- { data: { id: "P2", startDate: "2026-02-01", closeStatus: "Open" } }- ]);- const { db } = makeKyselyRecorder();-- const result = await closeAccountingPeriod(client, db, args, noRunsDue);-- expect(result.error?.message).toMatch(/must be locked/i);- expect(result.data).toBeNull();- });-- it("allows closing when earlier periods are closed and the checklist is clear", async () => {- // Query order after the sequential gate:- // getPeriodCloseChecklist: getAccountingPeriodById -> [definitions, tasks]- // -> readiness (4 parallel) ; then the period-flip update.- const client = makeClient([- { data: { accountingCutoverDate: "2026-01-01" } }, // requireAccountingCutover- { data: { id: "P2", startDate: "2026-02-01", closeStatus: "Locked" } },- { count: 0 }, // no earlier open periods- {- data: {- id: "P2",- startDate: "2026-02-01",- endDate: "2026-02-28",- closeStatus: "Locked"- }- },- { data: [] }, // active definitions (none configured)- { data: [] }, // existing tasks (none)- { data: { timezone: "America/New_York" } }, // company business calendar- { data: [] }, // external GL readiness: no active integrations- { count: 0 }, // readiness: draft journals- { data: [] }, // readiness: posted journals in period- { data: [] }, // readiness: Draft depreciation runs- { count: 0 }, // readiness: unmatched intercompany- { count: 0 }, // readiness: pending receipts- { count: 0 }, // readiness: pending shipments- { count: 0 }, // readiness: pending sales invoices- { count: 0 }, // readiness: pending purchase invoices- { count: 0 }, // readiness: draft payments- { count: 0 } // readiness: draft memos- ]);- // The period-flip write goes through the Kysely transaction, not supabase.- const { db } = makeKyselyRecorder();-- const result = await closeAccountingPeriod(client, db, args, noRunsDue);-- expect(result.error).toBeNull();- expect(result.data).toEqual({ id: "P2" });- });-});--// ----------------------------------------------------------------------------// closePeriodWithChecklist — the UI entry point (acceptance criteria 1/4).-//-// Delegates to closeAccountingPeriod, so it drives the full query graph:-// getAccountingPeriodById -> earlierOpen count-// -> getPeriodCloseChecklist(getAccountingPeriodById -> [definitions, tasks]-// -> readiness: [draftJournals, journalsInPeriod, draftDepreciation, IC,-// pendingReceipts, pendingShipments, pendingSalesInv, pendingPurchInv])-// -> (per differing Auto task) periodCloseTask update-// -> accountingPeriod flip.-// makeRecordingClient (above) records every `.update()` keyed by table so we can-// assert both the close-gate outcome and that final Auto-task states persist.-// -----------------------------------------------------------------------------// Close requires the period to already be Locked (Open -> Locked -> Closed).-const lockedPeriod = {- id: "P2",- startDate: "2026-02-01",- closeStatus: "Locked"-};-const lockedPeriodWithRange = {- ...lockedPeriod,- endDate: "2026-02-28"-};--describe("closeAccountingPeriod — Blocker gate + Auto-task persistence", () => {- it("rejects the close when a Blocker auto-check (draft JEs) is failing", async () => {- const { client, updates } = makeRecordingClient([- { data: { accountingCutoverDate: "2026-01-01" } }, // requireAccountingCutover- { data: lockedPeriod }, // getAccountingPeriodById- { count: 0 }, // no earlier open periods- { data: lockedPeriodWithRange }, // checklist: getAccountingPeriodById- { data: [] }, // active definitions (already instantiated)- {- data: [- {- id: "auto1",- companyId: "C1",- accountingPeriodId: "P2",- definitionId: "d1",- name: "Post or re-date draft journal entries",- taskType: "Auto",- autoCheckKey: "draft-journals",- sortOrder: 1,- required: true,- severity: "Blocker",- status: "Open",- assigneeId: null,- completedBy: null,- completedAt: null,- skippedReason: null,- notes: null- }- ]- }, // existing tasks — no instantiation needed- { data: { timezone: "America/New_York" } }, // company business calendar- { data: [] }, // external GL readiness: no active integrations- { count: 2 }, // readiness: draft journals present -> Blocker failing- { data: [] }, // readiness: posted journals in period- { data: [] }, // readiness: Draft depreciation runs- { count: 0 }, // readiness: unmatched intercompany- { count: 0 }, // readiness: pending receipts- { count: 0 }, // readiness: pending shipments- { count: 0 }, // readiness: pending sales invoices- { count: 0 }, // readiness: pending purchase invoices- { count: 0 }, // readiness: draft payments- { count: 0 } // readiness: draft memos- ]);- const { db, updates: txUpdates } = makeKyselyRecorder();-- const result = await closeAccountingPeriod(client, db, args, noRunsDue);-- expect(result.data).toBeNull();- expect(result.error?.message).toMatch(/draft journal/i);- // The close is rejected before the transaction opens, so nothing is- // persisted through either client.- expect(txUpdates).toHaveLength(0);- expect(- updates.some(- (u) =>- u.table === "accountingPeriod" && u.values.closeStatus === "Closed"- )- ).toBe(false);- });-- it("persists the resolved Auto-task state, then closes, when checks pass", async () => {- const { client } = makeRecordingClient([- { data: { accountingCutoverDate: "2026-01-01" } }, // requireAccountingCutover- { data: lockedPeriod }, // getAccountingPeriodById- { count: 0 }, // no earlier open periods- { data: lockedPeriodWithRange }, // checklist: getAccountingPeriodById- { data: [] }, // active definitions- {- data: [- {- id: "auto1",- companyId: "C1",- accountingPeriodId: "P2",- definitionId: "d1",- name: "Post or re-date draft journal entries",- taskType: "Auto",- autoCheckKey: "draft-journals",- sortOrder: 1,- required: true,- severity: "Blocker",- status: "Open", // stale Open; readiness now passes -> flips to Done- assigneeId: null,- completedBy: null,- completedAt: null,- skippedReason: null,- notes: null- }- ]- },- { data: { timezone: "America/New_York" } }, // company business calendar- { data: [] }, // external GL readiness: no active integrations- { count: 0 }, // readiness: no draft journals -> Blocker passing- { data: [] }, // readiness: posted journals in period- { data: [] }, // readiness: Draft depreciation runs- { count: 0 }, // readiness: unmatched intercompany- { count: 0 }, // readiness: pending receipts- { count: 0 }, // readiness: pending shipments- { count: 0 }, // readiness: pending sales invoices- { count: 0 }, // readiness: pending purchase invoices- { count: 0 }, // readiness: draft payments- { count: 0 } // readiness: draft memos- ]);- // The task persist + period flip both run inside the Kysely transaction.- const { db, updates: txUpdates, rawExecutions } = makeKyselyRecorder();-- const result = await closeAccountingPeriod(client, db, args, noRunsDue);-- expect(result.error).toBeNull();- expect(result.data).toEqual({ id: "P2" });-- // The GL balance snapshot is written (snapshotAccountingPeriodBalances) via a- // raw statement inside the same transaction, after the period is flipped.- expect(rawExecutions.length).toBeGreaterThan(0);-- // Final Auto-task state persisted to periodCloseTask as Done.- const taskUpdate = txUpdates.find((u) => u.table === "periodCloseTask");- expect(taskUpdate?.values.status).toBe("Done");-- // Period flipped to Closed after the task state was flushed.- const periodUpdate = txUpdates.find((u) => u.table === "accountingPeriod");- expect(periodUpdate?.values.closeStatus).toBe("Closed");- // The task write precedes the period flip within the transaction.- expect(txUpdates.map((u) => u.table)).toEqual([- "periodCloseTask",- "accountingPeriod"- ]);- });-});--// ----------------------------------------------------------------------------// Close checklist gating (acceptance criteria 6/9/10) — exercised as pure logic-// so the gate is verified without scripting a full query graph.-// ---------------------------------------------------------------------------+import {+ fiscalYearPeriodDates,+ periodDeletionRefusal,+ periodPostingRefusal+} from "./accounting.utils";function task(overrides: Partial<PeriodCloseTaskRow>): PeriodCloseTaskRow {return {@@ -459,37 +41,46 @@ function task(overrides: Partial<PeriodCloseTaskRow>): PeriodCloseTaskRow {};}-const draftBlockerFailing: PeriodReadinessCheck = {+const draftJournalsTask = task({+ id: "auto1",+ taskType: "Auto",autoCheckKey: "draft-journals",severity: "Blocker",- label: "Draft journal entries dated in this period",- failing: true,- count: 2-};-const draftBlockerPassing: PeriodReadinessCheck = {- ...draftBlockerFailing,- failing: false,- count: 0-};--describe("checklistTasksToCreate — idempotent instantiation (criterion 6)", () => {- it("creates a task per definition on first run, none on re-run", () => {- const defs = [{ id: "d1" }, { id: "d2" }, { id: "d3" }];+ name: "Post or re-date draft journal entries"+});- const first = checklistTasksToCreate(defs, []);- expect(first.map((d) => d.id)).toEqual(["d1", "d2", "d3"]);+function draftJournalsCheck(failing: boolean): PeriodReadinessCheck {+ return {+ autoCheckKey: "draft-journals",+ severity: "Blocker",+ label: "Draft journal entries dated in this period",+ failing,+ count: failing ? 2 : 0+ };+}- // Simulate the tasks that first-run would have created, then re-run.- const existing = first.map((d) => ({ definitionId: d.id }));- const second = checklistTasksToCreate(defs, existing);- expect(second).toEqual([]);+describe("checklistTasksToCreate", () => {+ it("creates a task per definition on first run and none on a re-run", () => {+ const defs = [{ id: "d1" }, { id: "d2" }, { id: "d3" }];+ expect(checklistTasksToCreate(defs, []).map((d) => d.id)).toEqual([+ "d1",+ "d2",+ "d3"+ ]);+ expect(+ checklistTasksToCreate(defs, [+ { definitionId: "d1" },+ { definitionId: "d2" },+ { definitionId: "d3" }+ ])+ ).toEqual([]);});});-describe("evaluateCloseChecklist — close gate (criteria 7/10)", () => {- it("blocks close when a required manual task is still Open", () => {+describe("evaluateCloseChecklist", () => {+ it("blocks the close while a required manual task is Open, naming it", () => {const result = evaluateCloseChecklist(- [task({ taskType: "Manual", status: "Open", name: "Review financials" })],+ [task({ name: "Review financials" })],[],"Locked");@@ -497,743 +88,288 @@ describe("evaluateCloseChecklist — close gate (criteria 7/10)", () => {expect(result.blockingReason).toMatch(/Review financials/);});- it("blocks close when a Blocker auto-check is failing", () => {+ it("blocks the close while a Blocker auto-check is failing", () => {const result = evaluateCloseChecklist(- [- task({- taskType: "Auto",- autoCheckKey: "draft-journals",- severity: "Blocker",- status: "Open",- name: "Post or re-date draft journal entries"- })- ],- [draftBlockerFailing],+ [draftJournalsTask],+ [draftJournalsCheck(true)],"Locked");expect(result.canClose).toBe(false);- expect(result.blockingReason).toMatch(/draft journal/i);+ expect(result.autoTaskStates).toEqual([]);});- it("fails closed when an Auto task has no registered evaluator", () => {+ it("fails closed when an Auto task has no evaluator for its key", () => {const result = evaluateCloseChecklist(- [- task({- taskType: "Auto",- autoCheckKey: "future-custom-check",- severity: "Blocker",- status: "Open",- name: "Some future auto check"- })- ],- [], // no evaluator produced for this key+ [task({ ...draftJournalsTask, autoCheckKey: "future-custom-check" })],+ [],"Locked");expect(result.canClose).toBe(false);- expect(result.blockingReason).toMatch(/Some future auto check/);});- it("allows close and persists the resolved Auto-task state when checks pass", () => {+ it("does not let a skipped task hold the close", () => {const result = evaluateCloseChecklist(- [- task({- id: "auto1",- taskType: "Auto",- autoCheckKey: "draft-journals",- severity: "Blocker",- status: "Open"- }),- task({ taskType: "Manual", status: "Done" })- ],- [draftBlockerPassing],+ [task({ ...draftJournalsTask, status: "Skipped" })],+ [draftJournalsCheck(true)],"Locked");expect(result.canClose).toBe(true);- expect(result.autoTaskStates).toEqual([{ id: "auto1", status: "Done" }]);- });-- it("derives the Lock task status from closeStatus and gates the close on it", () => {- const lockTask = task({- taskType: "Action",- status: "Open",- name: "Lock the period"- });-- const openState = evaluateCloseChecklist([lockTask], [], "Open");- expect(openState.tasks[0]?.effectiveStatus).toBe("Open");- expect(openState.canClose).toBe(false);- expect(openState.blockingReason).toMatch(/Lock the period/);-- const lockedState = evaluateCloseChecklist([lockTask], [], "Locked");- expect(lockedState.tasks[0]?.effectiveStatus).toBe("Done");- expect(lockedState.canClose).toBe(true);- });-});--describe("reopenAccountingPeriod — reverse-sequential reopen", () => {- it("rejects reopening period N while a later period is still Closed", async () => {- const client = makeClient([- { data: { id: "P2", startDate: "2026-02-01", closeStatus: "Closed" } },- { count: 1 } // a later period is still closed- ]);-- const result = await reopenAccountingPeriod(client, args);-- expect(result.error).toBeTruthy();- expect(result.error?.message).toMatch(/later periods must be reopened/i);- expect(result.data).toBeNull();- });-- it("allows reopening when no later period is Closed", async () => {- const client = makeClient([- {- data: {- id: "P2",- startDate: "2026-02-01",- endDate: "2026-02-28",- closeStatus: "Closed"- }- },- { count: 0 }, // no later closed periods- { error: null }, // delete cumulative snapshots (invariant #3)- { data: { id: "P2" }, error: null } // update- ]);-- const result = await reopenAccountingPeriod(client, args);-- expect(result.error).toBeNull();- expect(result.data).toEqual({ id: "P2" });- });-- // Records which table each terminal op hit, so we can assert the reopen both- // deletes the stale cumulative snapshots and orders the delete before the flip.- function makeReopenTracker(responses: Scripted[]) {- const ops: string[] = [];- let i = 0;- const next = () => responses[i++] ?? { data: null, error: null };- const makeBuilder = (table: string) => {- const builder: any = {- select: () => builder,- update: () => {- ops.push(`update:${table}`);- return builder;- },- delete: () => {- ops.push(`delete:${table}`);- return builder;- },- eq: () => builder,- neq: () => builder,- gt: () => builder,- gte: () => builder,- lt: () => builder,- lte: () => builder,- or: () => builder,- order: () => builder,- limit: () => builder,- single: () => Promise.resolve(next()),- then: (resolve: (v: Scripted) => unknown) => resolve(next())- };- return builder;- };- return { client: { from: (t: string) => makeBuilder(t) } as any, ops };- }-- it("deletes cumulative snapshots at/after the period end before flipping to Open", async () => {- const { client, ops } = makeReopenTracker([- {- data: {- id: "P2",- startDate: "2026-02-01",- endDate: "2026-02-28",- closeStatus: "Closed"- }- },- { count: 0 }, // no later closed periods- { error: null }, // delete snapshots- { data: { id: "P2" }, error: null } // update- ]);-- const result = await reopenAccountingPeriod(client, args);-- expect(result.error).toBeNull();- // Snapshot rows are cleared, and the delete precedes the status flip.- expect(ops).toEqual([- "delete:accountingPeriodBalance",- "update:accountingPeriod"- ]);- });-- it("aborts the reopen (period stays Closed) if snapshot deletion fails", async () => {- const { client, ops } = makeReopenTracker([- {- data: {- id: "P2",- startDate: "2026-02-01",- endDate: "2026-02-28",- closeStatus: "Closed"- }- },- { count: 0 }, // no later closed periods- { error: { message: "snapshot delete failed" } } // delete fails- ]);-- const result = await reopenAccountingPeriod(client, args);-- expect(result.error?.message).toBe("snapshot delete failed");- // The period was never flipped — no update issued after the failed delete.- expect(ops).toEqual(["delete:accountingPeriodBalance"]);- });-});--// ----------------------------------------------------------------------------// Source-aware posting gate (acceptance criteria 2/3)-//-// getOrCreateAccountingPeriod issues one query (getCurrentAccountingPeriod's-// `.single()`) to resolve the current period, then applies the close-status-// gate. An Active + Locked period rejects "operational" posting but still-// accepts "accounting" adjustments.-// -----------------------------------------------------------------------------describe("getOrCreateAccountingPeriod — locked-period source gate", () => {- it("rejects operational posting into a Locked period", async () => {- const client = makeClient([- { data: { id: "P2", status: "Active", closeStatus: "Locked" } }- ]);-- const result = await getOrCreateAccountingPeriod(- client,- "C1",- "2026-02-15",- "operational"- );-- expect(result.data).toBeNull();- expect(result.error?.message).toMatch(/locked/i);});- it("allows accounting posting into a Locked period", async () => {- const client = makeClient([- { data: { id: "P2", status: "Active", closeStatus: "Locked" } }- ]);-- const result = await getOrCreateAccountingPeriod(- client,- "C1",- "2026-02-15",- "accounting"+ it("allows the close and reports the Auto tasks whose stored status is stale", () => {+ const result = evaluateCloseChecklist(+ [draftJournalsTask, task({ status: "Done" })],+ [draftJournalsCheck(false)],+ "Locked");-- expect(result.error).toBeNull();- expect(result.data).toBe("P2");- });-});--// ----------------------------------------------------------------------------// postJournalEntry now routes through the period gate (source "accounting").-// A balanced manual JE dated in a Closed period must be rejected — before the-// gate was wired in, the status flip proceeded regardless of period state.-//-// Query order: getJournalEntry `.single()` -> getCurrentAccountingPeriod-// `.single()` -> (only if the gate passes) the status-flip update `.single()`.-// -----------------------------------------------------------------------------describe("postJournalEntry — period gate wiring", () => {- const draftEntry = {- data: {- id: "J1",- status: "Draft",- companyId: "C1",- postingDate: "2026-02-15",- journalLine: [- { amount: 100, account: { class: "Asset" } },- { amount: 100, account: { class: "Liability" } }- ]- },- error: null- };-- it("rejects posting a balanced manual JE into a Closed period", async () => {- const client = makeClient([- draftEntry,- { data: { accountingCutoverDate: "2026-01-01" } }, // requireAccountingCutover- { data: { id: "P2", status: "Active", closeStatus: "Closed" } }- ]);-- const result = await postJournalEntry(client, "J1", "U1");-- expect(result.data).toBeNull();- expect(result.error?.message).toMatch(/closed/i);- });-- it("posts a balanced manual JE into a Locked period (accounting source)", async () => {- const client = makeClient([- draftEntry,- { data: { accountingCutoverDate: "2026-01-01" } }, // requireAccountingCutover- { data: { id: "P2", status: "Active", closeStatus: "Locked" } },- { data: { id: "J1" }, error: null }- ]);-- const result = await postJournalEntry(client, "J1", "U1");-- expect(result.error).toBeNull();- expect(result.data).toEqual({ id: "J1" });- });-});--// ----------------------------------------------------------------------------// skipCloseTask — Blocker skip rejection + empty-reason rejection (criteria 8/9)-// Query order: getPeriodCloseTaskById `.single()` -> (only if allowed) update.-// -----------------------------------------------------------------------------describe("skipCloseTask — skip guards", () => {- it("rejects an empty skip reason before touching the database", async () => {- const client = makeClient([]);- const result = await skipCloseTask(client, {- taskId: "T1",- companyId: "C1",- userId: "U1",- skippedReason: " "- });- expect(result.data).toBeNull();- expect(result.error?.message).toMatch(/reason is required/i);- });-- it("rejects skipping a Blocker task", async () => {- const client = makeClient([- {- data: {- id: "T1",- taskType: "Auto",- severity: "Blocker",- status: "Open"- }- }- ]);- const result = await skipCloseTask(client, {- taskId: "T1",- companyId: "C1",- userId: "U1",- skippedReason: "not applicable this month"- });- expect(result.data).toBeNull();- expect(result.error?.message).toMatch(/cannot be skipped/i);- });-- it("skips a Warning task with a recorded reason", async () => {- const client = makeClient([- {- data: {- id: "T2",- taskType: "Auto",- severity: "Warning",- status: "Open"- }- },- { data: { id: "T2" }, error: null } // update- ]);- const result = await skipCloseTask(client, {- taskId: "T2",- companyId: "C1",- userId: "U1",- skippedReason: "intercompany matched manually"+ expect(result).toMatchObject({+ canClose: true,+ blockingReason: null,+ autoTaskStates: [{ id: "auto1", status: "Done" }]});- expect(result.error).toBeNull();- expect(result.data).toEqual({ id: "T2" });- });-});--// ----------------------------------------------------------------------------// Period deletability + deletion guard, the fiscal-calendar "committed" check,-// and fiscal-year generation. These exercise the real service functions against-// the scripted fake supabase client; each awaited query / `.single()` shifts the-// next scripted result off the queue in the order the function issues them.-// -----------------------------------------------------------------------------// Like makeClient but records every `.insert(values)` so a test can assert the-// rows a service generated (createFiscalYearPeriods' month math).-function makeInsertRecordingClient(responses: Scripted[]) {- let i = 0;- const next = () => responses[i++] ?? { data: null, error: null };- const inserts: any[] = [];- const builder: any = {- select: () => builder,- insert: (values: any) => {- inserts.push(values);- return builder;- },- eq: () => builder,- single: () => Promise.resolve(next()),- then: (resolve: (v: Scripted) => unknown) => resolve(next())- };- return { client: { from: () => builder } as any, inserts };-}--describe("getAccountingPeriodDeletability", () => {- // Query order: getAccountingPeriodById (.single) -> journal count.- it("allows deleting an open period with no journals", async () => {- const client = makeClient([- { data: { id: "P1", closeStatus: "Open", startDate: "2026-03-01" } },- { count: 0 }- ]);- const result = await getAccountingPeriodDeletability(client, "P1", "C1");- expect(result.data?.canDelete).toBe(true);- expect(result.data?.reason).toBeNull();- });-- it("blocks an open period that has journals posted to it", async () => {- const client = makeClient([- { data: { id: "P1", closeStatus: "Open", startDate: "2026-03-01" } },- { count: 3 }- ]);- const result = await getAccountingPeriodDeletability(client, "P1", "C1");- expect(result.data?.canDelete).toBe(false);- expect(result.data?.reason).toMatch(/3 journal entries/);});- it("blocks a Locked/Closed period regardless of journals", async () => {- const client = makeClient([- { data: { id: "P1", closeStatus: "Locked", startDate: "2026-03-01" } },- { count: 0 }- ]);- const result = await getAccountingPeriodDeletability(client, "P1", "C1");- expect(result.data?.canDelete).toBe(false);- expect(result.data?.reason).toMatch(/Locked/);- });+ it.each([+ ["Open", "Open", false],+ ["Locked", "Done", true],+ ["Closed", "Done", true]+ ] as const)(+ "treats the Lock task as done only once the period is locked (%s)",+ (closeStatus, effectiveStatus, canClose) => {+ const result = evaluateCloseChecklist(+ [task({ taskType: "Action", name: "Lock the period" })],+ [],+ closeStatus+ );+ expect(result.tasks[0]?.effectiveStatus).toBe(effectiveStatus);+ expect(result.canClose).toBe(canClose);+ }+ );});-describe("deleteAccountingPeriod — server-side guard", () => {- it("refuses to delete a non-open period (never issues the DELETE)", async () => {- const client = makeClient([- { data: { id: "P1", closeStatus: "Closed", startDate: "2026-03-01" } },- { count: 0 }- ]);- const result = await deleteAccountingPeriod(client, {- periodId: "P1",- companyId: "C1"- });- expect(result.error?.message).toMatch(/Closed/);- expect(result.data).toBeNull();+describe("periodPostingRefusal", () => {+ it.each([+ ["Open", "operational"],+ ["Open", "accounting"],+ ["Locked", "accounting"]+ ] as const)("lets a %s period take an %s posting", (status, source) => {+ expect(periodPostingRefusal(status, source)).toBeNull();});- it("deletes an open, empty period", async () => {- const client = makeClient([- { data: { id: "P1", closeStatus: "Open", startDate: "2026-03-01" } },- { count: 0 },- { data: null, error: null } // the DELETE result- ]);- const result = await deleteAccountingPeriod(client, {- periodId: "P1",- companyId: "C1"- });- expect(result.error).toBeNull();+ it.each([+ ["Locked", "operational"],+ ["Closed", "operational"],+ ["Closed", "accounting"]+ ] as const)("refuses a %s period an %s posting", (status, source) => {+ expect(periodPostingRefusal(status, source)).not.toBeNull();});});-describe("getFiscalCalendarCommitted", () => {- // committed = (non-open periods) OR (postings); the OR is order-independent,- // so these assertions hold regardless of how the two counts are scripted.- it("is not committed when every period is Open and there are no postings", async () => {- const client = makeClient([{ count: 0 }, { count: 0 }]);- const result = await getFiscalCalendarCommitted(client, "C1");- expect(result.data?.committed).toBe(false);- });-- it("is committed once a Locked/Closed period or a posting exists", async () => {- const client = makeClient([{ count: 1 }, { count: 0 }]);- const result = await getFiscalCalendarCommitted(client, "C1");- expect(result.data?.committed).toBe(true);+describe("periodDeletionRefusal", () => {+ it("allows deleting an open period with no journals", () => {+ expect(periodDeletionRefusal("Open", 0)).toBeNull();});- it("counts only Posted and Reversed journals, never a Provisional one", async () => {- const statusFilters: unknown[] = [];- const builder: any = {- select: () => builder,- eq: () => builder,- neq: () => builder,- in: (column: string, values: unknown[]) => {- if (column === "status") statusFilters.push(values);- return builder;- },- then: (resolve: (v: Scripted) => unknown) => resolve({ count: 0 })- };- const client = { from: () => builder } as any;- await getFiscalCalendarCommitted(client, "C1");- expect(statusFilters).toEqual([["Posted", "Reversed"]]);+ it.each([+ ["an open period with journals posted to it", "Open", 3],+ ["a Locked period", "Locked", 0],+ ["a Closed period", "Closed", 0]+ ])("refuses %s", (_label, status, journals) => {+ expect(periodDeletionRefusal(status, journals)).not.toBeNull();});});-describe("createFiscalYearPeriods", () => {- // Query order: getFiscalYearSettings (.single) -> existing periodNumbers ->- // insert (only when there are rows to create).- it("is idempotent — creates nothing when all 12 periods already exist", async () => {- const existing = Array.from({ length: 12 }, (_, p) => ({- periodNumber: p + 1- }));- const client = makeClient([- { data: { startMonth: "January" } },- { data: existing }- ]);- const result = await createFiscalYearPeriods(client, {- companyId: "C1",- fiscalYear: 2027,- userId: "U1"- });- expect(result.error).toBeNull();- expect(result.data).toEqual([]);- });-- it("generates 12 periods anchored on the fiscal start month (March)", async () => {- const { client, inserts } = makeInsertRecordingClient([- { data: { startMonth: "March" } },- { data: [] }, // none exist yet- { data: [{ id: "x" }] } // insert result- ]);- await createFiscalYearPeriods(client, {- companyId: "C1",- fiscalYear: 2027,- userId: "U1"- });- const rows = inserts[0] as {- periodNumber: number;- startDate: string;- fiscalYear: number;- }[];+describe("fiscalYearPeriodDates", () => {+ it("runs a March-start FY2027 from March 2026 to February 2027", () => {+ const rows = fiscalYearPeriodDates(2027, 3, new Set());expect(rows).toHaveLength(12);- // FY2027 with a March start spans Mar 2026 .. Feb 2027.- expect(rows[0]).toMatchObject({+ expect(rows[0]).toEqual({periodNumber: 1,startDate: "2026-03-01",- fiscalYear: 2027+ endDate: "2026-03-31"});- expect(rows[11]).toMatchObject({+ expect(rows[10]).toEqual({+ periodNumber: 11,+ startDate: "2027-01-01",+ endDate: "2027-01-31"+ });+ expect(rows[11]).toEqual({periodNumber: 12,startDate: "2027-02-01",- fiscalYear: 2027+ endDate: "2027-02-28"});});-});-// ----------------------------------------------------------------------------// The two run checks ask what new runs would hold (the preview) and which-// Draft runs are waiting. The batched readiness reads come first, then the-// Planned rows Draft revenue recognition runs hold.-// -----------------------------------------------------------------------------describe("computePeriodReadiness — run checks", () => {- const script = ({- draftDepreciationRuns = [],- heldRevenueRows = []- }: {- draftDepreciationRuns?: unknown[];- heldRevenueRows?: unknown[];- }): Scripted[] => [- { data: { timezone: "America/New_York" } },- { data: [] }, // external GL readiness: no active integrations- { count: 0 }, // draft journals- { data: [] }, // posted journals in period- { data: draftDepreciationRuns },- { count: 0 }, // unmatched intercompany- { count: 0 }, // pending receipts- { count: 0 }, // pending shipments- { count: 0 }, // pending sales invoices- { count: 0 }, // pending purchase invoices- { count: 0 }, // draft payments- { count: 0 }, // draft memos- { data: heldRevenueRows }- ];- const preview = (overrides: Partial<PeriodRunPreview>): PeriodRunPreview => ({- ...nothingDue,- ...overrides+ it("keeps a January-start fiscal year inside its own calendar year", () => {+ const rows = fiscalYearPeriodDates(2028, 1, new Set());+ expect(rows[0]?.startDate).toBe("2028-01-01");+ expect(rows[1]?.endDate).toBe("2028-02-29");+ expect(rows[11]?.endDate).toBe("2028-12-31");});- const readiness = (client: unknown, runPreview: PeriodRunPreview) =>- computePeriodReadiness(- client as any,- "C1",- "2026-10-01",- "2026-10-31",- runPreview++ it("creates only the periods that do not exist yet", () => {+ const existing = new Set(+ Array.from({ length: 12 }, (_, i) => i + 1).filter((p) => p !== 5));- const check = (result: Awaited<ReturnType<typeof readiness>>, key: string) =>- result.checks.find((c) => c.autoCheckKey === key);+ expect(fiscalYearPeriodDates(2027, 1, existing)).toEqual([+ { periodNumber: 5, startDate: "2027-05-01", endDate: "2027-05-31" }+ ]);+ });+});- it("passes both when nothing is due and no Draft run waits", async () => {- const result = await readiness(makeClient(script({})), nothingDue);+describe("periodRunChecks", () => {+ const nothingDue: PeriodRunPreview = {+ revenue: { count: 0, amount: 0, error: null },+ lease: { count: 0, amount: 0, error: null },+ depreciation: { count: 0, amount: 0, error: null }+ };- expect(check(result, "unposted-revenue-schedules")).toMatchObject({- failing: false,- count: 0,- amount: 0- });- expect(check(result, "draft-depreciation")).toMatchObject({- failing: false,- count: 0,- amount: 0- });- });+ function base(+ overrides: Partial<Parameters<typeof periodRunChecks>[0]> = {}+ ) {+ return {+ runPreview: nothingDue,+ heldRunRows: { data: [], error: null },+ draftDepreciationRuns: { data: [], error: null },+ ...overrides+ };+ }- it("fails revenue with what a new run would claim", async () => {- const result = await readiness(- makeClient(script({})),- preview({ revenue: { count: 2, amount: 150, error: null } })- );+ function check(+ args: Parameters<typeof periodRunChecks>[0],+ key: string+ ): PeriodReadinessCheck | undefined {+ return periodRunChecks(args).find((c) => c.autoCheckKey === key);+ }- expect(check(result, "unposted-revenue-schedules")).toMatchObject({- failing: true,- count: 2,- amount: 150,- due: { count: 2, amount: 150 },- draftRuns: []- });+ const revenueRun = {+ id: "R1",+ runId: "RR-000001",+ periodEnd: "2026-09-30",+ type: "Revenue Recognition" as const+ };++ it("passes every run check when nothing is due and no Draft run waits", () => {expect(- result.warnings.find((w) => w.key === "unposted-revenue-schedules")?.count- ).toBe(2);+ periodRunChecks(base()).map((c) => [c.autoCheckKey, c.failing, c.count])+ ).toEqual([+ ["draft-depreciation", false, 0],+ ["unposted-revenue-schedules", false, 0],+ ["unposted-lease-schedules", false, 0]+ ]);});- it("adds the rows a Draft run holds, and names the run", async () => {- const result = await readiness(- makeClient(- script({- heldRevenueRows: [- {- amount: 40,- run: {- id: "R1",- runId: "RR-000001",- periodEnd: "2026-09-30",- type: "Revenue Recognition"- }- },- {- amount: 10,- run: {- id: "R1",- runId: "RR-000001",- periodEnd: "2026-09-30",- type: "Revenue Recognition"- }- }- ]- })- ),- preview({ revenue: { count: 1, amount: 25, error: null } })- );-- expect(check(result, "unposted-revenue-schedules")).toMatchObject({+ it("adds what a Draft run holds to what a new run would claim, naming the run once", () => {+ // Preview 1 row / 25 + held rows 40 and 10 = 3 rows / 75.+ expect(+ check(+ base({+ runPreview: {+ ...nothingDue,+ revenue: { count: 1, amount: 25, error: null }+ },+ heldRunRows: {+ data: [+ { amount: 40, run: revenueRun },+ { amount: 10, run: revenueRun }+ ],+ error: null+ }+ }),+ "unposted-revenue-schedules"+ )+ ).toMatchObject({failing: true,count: 3,amount: 75,+ due: { count: 1, amount: 25 },draftRuns: [{ id: "R1", readableId: "RR-000001", periodEnd: "2026-09-30" }]});});- it("fails the lease check on its own preview and Draft runs, never the revenue check", async () => {- const result = await readiness(- makeClient(- script({- heldRevenueRows: [- {- amount: 30,- run: {- id: "L1",- runId: "LR-000001",- periodEnd: "2026-09-30",- type: "Lease"- }- }- ]- })- ),- preview({ lease: { count: 2, amount: 120, error: null } })- );-- expect(check(result, "unposted-lease-schedules")).toMatchObject({+ it("counts a lease run's rows on the lease check only", () => {+ const args = base({+ runPreview: {+ ...nothingDue,+ lease: { count: 2, amount: 120, error: null }+ },+ heldRunRows: {+ data: [+ {+ amount: 30,+ run: { ...revenueRun, id: "L1", runId: "LR-000001", type: "Lease" }+ }+ ],+ error: null+ }+ });+ expect(check(args, "unposted-lease-schedules")).toMatchObject({failing: true,count: 3,- amount: 150,- due: { count: 2, amount: 120 },- draftRuns: [- { id: "L1", readableId: "LR-000001", periodEnd: "2026-09-30" }- ]+ amount: 150});- expect(check(result, "unposted-revenue-schedules")).toMatchObject({+ expect(check(args, "unposted-revenue-schedules")).toMatchObject({failing: false,count: 0});});- it("fails revenue when the preview could not run", async () => {- const result = await readiness(- makeClient(script({})),- preview({- revenue: {- count: 0,- amount: 0,- error: "Set the Contract Assets account default"- }- })- );-- expect(check(result, "unposted-revenue-schedules")).toMatchObject({- failing: true,- count: 0- });+ it("fails revenue when the preview could not run", () => {+ expect(+ check(+ base({+ runPreview: {+ ...nothingDue,+ revenue: {+ count: 0,+ amount: 0,+ error: "No Contract Assets account"+ }+ }+ }),+ "unposted-revenue-schedules"+ )+ ).toMatchObject({ failing: true, count: 0 });});- it("counts the assets a new run would depreciate plus the Draft runs", async () => {- const result = await readiness(- makeClient(- script({- draftDepreciationRuns: [- {- id: "D1",- depreciationRunId: "DEP-000001",- periodEnd: "2026-10-31",- depreciationRunLine: [{ amount: 60 }, { amount: 40 }]- }- ]- })- ),- preview({ depreciation: { count: 3, amount: 900, error: null } })- );+ it("fails both schedule checks closed when the held rows cannot be read", () => {+ const args = base({ heldRunRows: { data: null, error: { message: "x" } } });+ expect(check(args, "unposted-revenue-schedules")?.failing).toBe(true);+ expect(check(args, "unposted-lease-schedules")?.failing).toBe(true);+ });- expect(check(result, "draft-depreciation")).toMatchObject({+ it("counts the assets a new run would depreciate plus each Draft depreciation run", () => {+ // 3 assets / 900 due + one Draft run of 60 + 40 = 4 / 1000.+ expect(+ check(+ base({+ runPreview: {+ ...nothingDue,+ depreciation: { count: 3, amount: 900, error: null }+ },+ draftDepreciationRuns: {+ data: [+ {+ id: "D1",+ depreciationRunId: "DEP-000001",+ periodEnd: "2026-10-31",+ depreciationRunLine: [{ amount: 60 }, { amount: 40 }]+ }+ ],+ error: null+ }+ }),+ "draft-depreciation"+ )+ ).toMatchObject({failing: true,count: 4,amount: 1000,- due: { count: 3, amount: 900 },draftRuns: [{ id: "D1", readableId: "DEP-000001", periodEnd: "2026-10-31" }]});});});--describe("requireAccountingCutover", () => {- it("refuses manual accounting work before the cutover", async () => {- const client = makeClient([{ data: { accountingCutoverDate: null } }]);- const result = await requireAccountingCutover(client, "C1");- expect(result.error?.message).toBe(ACCOUNTING_NOT_STARTED);- });-- it("allows it once the company has a cutover", async () => {- const client = makeClient([- { data: { accountingCutoverDate: "2026-01-01" } }- ]);- const result = await requireAccountingCutover(client, "C1");- expect(result.error).toBeNull();- });-- it("stops a period lock before the cutover, before any other read", async () => {- const client = makeClient([{ data: { accountingCutoverDate: null } }]);- const result = await lockAccountingPeriod(client, {- periodId: "P1",- companyId: "C1",- userId: "U1"- });- expect(result.data).toBeNull();- expect(result.error?.message).toBe(ACCOUNTING_NOT_STARTED);- });-});diff --git a/apps/erp/app/modules/accounting/accounting.post-asset-transfer.test.ts b/apps/erp/app/modules/accounting/accounting.post-asset-transfer.test.tsindex 7b51e134c3..045b70b59c 100644--- a/apps/erp/app/modules/accounting/accounting.post-asset-transfer.test.ts+++ b/apps/erp/app/modules/accounting/accounting.post-asset-transfer.test.ts@@ -2,283 +2,122 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { expect, it } from "vitest";+import { describe, expect, it } from "vitest";import {- CLOSED_JOB_STATUSES,postAssetTransferInput,- RETURNABLE_ASSET_STATUSES,resolveCapitalizationCost,resolveCapitalizationStock,statusAfterCostAdjustment} from "./accounting.service";-it("capitalize accepts the inventory payload with its optional fields absent", () => {- const parsed = postAssetTransferInput.parse({- type: "capitalize",- fixedAssetClassId: "class_fleet",- itemId: "item_1",- trackedEntityId: "te_1",- locationId: "loc_1",- transferDate: "2026-09-22"+describe("resolveCapitalizationStock", () => {+ it("nets every bin and picks the bin that holds the unit", () => {+ // A picked unit: the warehouse bin nets to 0, lineside holds it, and the+ // warehouse row comes first and must not win.+ expect(+ resolveCapitalizationStock([+ { storageUnitId: "bin_warehouse", onHand: 0 },+ { storageUnitId: "bin_lineside", onHand: 1 }+ ])+ ).toEqual({ onHand: 1, storageUnitId: "bin_lineside" });});- expect(parsed.type).toEqual("capitalize");- if (parsed.type === "capitalize") {- expect(parsed.storageUnitId).toEqual(undefined);- expect(parsed.name).toEqual(undefined);- expect(parsed.fixedAssetId).toEqual(undefined);- }-});-it("capitalize carries an existing Draft asset id and a name when given", () => {- const parsed = postAssetTransferInput.parse({- type: "capitalize",- fixedAssetClassId: "class_fleet",- itemId: "item_1",- trackedEntityId: "te_1",- locationId: "loc_1",- storageUnitId: "bin_1",- transferDate: "2026-09-22",- name: "Van VIN-001",- fixedAssetId: "fa_draft"+ it("reads NUMERIC strings and the unassigned bin", () => {+ expect(+ resolveCapitalizationStock([+ { storageUnitId: null, onHand: "1" },+ { storageUnitId: "bin_2", onHand: "0" }+ ])+ ).toEqual({ onHand: 1, storageUnitId: null });});- if (parsed.type !== "capitalize") throw new Error("wrong variant");- expect(parsed.fixedAssetId).toEqual("fa_draft");- expect(parsed.name).toEqual("Van VIN-001");- expect(parsed.storageUnitId).toEqual("bin_1");-});-it("return needs the asset, the location and the transfer date", () => {- const parsed = postAssetTransferInput.parse({- type: "return",- fixedAssetId: "fa_1",- locationId: "loc_1",- transferDate: "2027-01-15"+ it("uses the caller's bin only when nothing nets positive", () => {+ expect(resolveCapitalizationStock([], "bin_caller")).toEqual({+ onHand: 0,+ storageUnitId: "bin_caller"+ });+ expect(+ resolveCapitalizationStock(+ [{ storageUnitId: "bin_actual", onHand: 1 }],+ "bin_caller"+ )+ ).toEqual({ onHand: 1, storageUnitId: "bin_actual" });});- expect(parsed.type).toEqual("return");- expect(() =>- postAssetTransferInput.parse({- type: "return",- fixedAssetId: "fa_1",- transferDate: "2027-01-15"- })- ).toThrow();-});--it("attachJob needs only the asset and the job", () => {- const parsed = postAssetTransferInput.parse({- type: "attachJob",- fixedAssetId: "fa_cip",- jobId: "job_1"- });- expect(parsed.type).toEqual("attachJob");- expect(() =>- postAssetTransferInput.parse({- type: "attachJob",- fixedAssetId: "fa_cip"- })- ).toThrow();-});-it("capitalizeCip needs the target class and an in-service date", () => {- const parsed = postAssetTransferInput.parse({- type: "capitalizeCip",- fixedAssetId: "fa_cip",- toClassId: "class_machinery",- inServiceDate: "2026-11-01"+ it("reports a unit that is no longer on hand", () => {+ expect(+ resolveCapitalizationStock([+ { storageUnitId: "bin_1", onHand: 1 },+ { storageUnitId: "bin_1", onHand: -1 }+ ]).onHand+ ).toBe(0);});- expect(parsed.type).toEqual("capitalizeCip");- expect(() =>- postAssetTransferInput.parse({- type: "capitalizeCip",- fixedAssetId: "fa_cip",- toClassId: "class_machinery"- })- ).toThrow();-});--it("dates must be YYYY-MM-DD text, never a timestamp", () => {- expect(() =>- postAssetTransferInput.parse({- type: "return",- fixedAssetId: "fa_1",- locationId: "loc_1",- transferDate: "2027-01-15T00:00:00.000Z"- })- ).toThrow();- expect(() =>- postAssetTransferInput.parse({- type: "capitalizeCip",- fixedAssetId: "fa_cip",- toClassId: "class_machinery",- inServiceDate: "11/01/2026"- })- ).toThrow();-});--it("every variant requires its ids; unknown types are refused", () => {- expect(() =>- postAssetTransferInput.parse({- type: "attachJob",- fixedAssetId: "fa_cip",- jobId: ""- })- ).toThrow();- expect(() =>- postAssetTransferInput.parse({- type: "reclassify",- fixedAssetId: "fa_1"- })- ).toThrow();-});--it("stock resolution sums every bin and picks the bin holding the unit", () => {- // A picked unit: −1 in the warehouse bin, +1 at lineside — the warehouse- // row comes first, and must not win.- const stock = resolveCapitalizationStock([- { storageUnitId: "bin_warehouse", onHand: 0 },- { storageUnitId: "bin_lineside", onHand: 1 }- ]);- expect(stock).toEqual({ onHand: 1, storageUnitId: "bin_lineside" });-});--it("stock resolution reads NUMERIC strings and unassigned bins", () => {- const stock = resolveCapitalizationStock([- { storageUnitId: null, onHand: "1" },- { storageUnitId: "bin_2", onHand: "0" }- ]);- expect(stock.onHand).toEqual(1);- expect(stock.storageUnitId).toEqual(null);-});--it("stock resolution falls back to the caller's bin only when nothing nets positive", () => {- expect(resolveCapitalizationStock([], "bin_caller")).toEqual({- onHand: 0,- storageUnitId: "bin_caller"- });- expect(- resolveCapitalizationStock(- [{ storageUnitId: "bin_actual", onHand: 1 }],- "bin_caller"- ).storageUnitId- ).toEqual("bin_actual");-});--it("stock resolution reports a unit that is no longer on hand", () => {- const stock = resolveCapitalizationStock([- { storageUnitId: "bin_1", onHand: 1 },- { storageUnitId: "bin_1", onHand: -1 }- ]);- expect(stock.onHand).toEqual(0);-});--it("status sets match the plan", () => {- expect([...CLOSED_JOB_STATUSES]).toEqual([- "Completed",- "Cancelled",- "Closed"- ]);- expect([...RETURNABLE_ASSET_STATUSES]).toEqual([- "Active",- "Fully Depreciated"- ]);- expect(RETURNABLE_ASSET_STATUSES.has("Under Construction")).toEqual(false);- expect(CLOSED_JOB_STATUSES.has("Paused")).toEqual(false);});-it("adjustCost requires a positive amount", () => {- const base = {- type: "adjustCost",- fixedAssetId: "fa_1",- locationId: "loc_1",- transferDate: "2026-10-08"- };- expect(postAssetTransferInput.safeParse({ ...base, amount: 0 }).success).toBe(- false- );- expect(- postAssetTransferInput.safeParse({ ...base, amount: -5 }).success- ).toBe(false);- expect(- postAssetTransferInput.safeParse({- ...base,- amount: 1250,- offsetAccountId: "acc_re"- }).success- ).toBe(true);-});--it("capitalize takes the inventory cost when the unit carries one", () => {- expect(+describe("resolveCapitalizationCost", () => {+ const cost = (carried: number, entered: number | null) =>resolveCapitalizationCost({- carried: 60,- entered: null,+ carried,+ entered,serial: "SN-1",itemReadableId: "RW"- })- ).toEqual({ cost: 60, source: "inventory" });-});+ });-it("capitalize refuses an entered cost for a unit that carries one", () => {- const resolved = resolveCapitalizationCost({- carried: 60,- entered: 90,- serial: "SN-1",- itemReadableId: "RW"+ it("takes the inventory cost when the unit carries one", () => {+ expect(cost(60, null)).toEqual({ cost: 60, source: "inventory" });});- expect("error" in resolved && resolved.error).toMatch(- /SN-1 is carried in inventory at a cost/- );-});-it("capitalize takes the entered cost for a unit carried at zero", () => {- expect(- resolveCapitalizationCost({- carried: 0,- entered: 4200,- serial: "SN-2",- itemReadableId: "RW"- })- ).toEqual({ cost: 4200, source: "entered" });-});+ it("takes the entered cost for a unit carried at zero", () => {+ expect(cost(0, 4200)).toEqual({ cost: 4200, source: "entered" });+ });-it("capitalize refuses a unit carried at zero with no entered cost", () => {- const resolved = resolveCapitalizationCost({- carried: 0,- entered: null,- serial: "SN-2",- itemReadableId: "RW"+ it.each([+ ["an entered cost for a unit that carries one", 60, 90],+ ["a unit carried at zero with no entered cost", 0, null]+ ])("refuses %s, naming the serial", (_, carried, entered) => {+ expect(cost(carried, entered)).toEqual({+ error: expect.stringContaining("SN-1")+ });});- expect("error" in resolved && resolved.error).toMatch(- /SN-2 has no cost in inventory/- );});-it("a Fully Depreciated asset whose cost is raised above its residual returns to Active", () => {- // A zero-cost asset a run marked Fully Depreciated, now worth 1,000.- expect(- statusAfterCostAdjustment({- status: "Fully Depreciated",- acquisitionCost: 1000,- accumulatedDepreciation: 0,- residualValuePercent: 20- })- ).toEqual("Active");- // Raised, but still at or below its residual: nothing left to depreciate.+it.each([+ [0, false],+ [-5, false],+ [1250, true]+])("adjustCost with amount %d is accepted: %s", (amount, accepted) => {expect(- statusAfterCostAdjustment({- status: "Fully Depreciated",- acquisitionCost: 1000,- accumulatedDepreciation: 800,- residualValuePercent: 20- })- ).toEqual("Fully Depreciated");- expect(- statusAfterCostAdjustment({- status: "Active",- acquisitionCost: 1000,- accumulatedDepreciation: 0,- residualValuePercent: 0- })- ).toEqual("Active");+ postAssetTransferInput.safeParse({+ type: "adjustCost",+ fixedAssetId: "fa_1",+ locationId: "loc_1",+ transferDate: "2026-10-08",+ offsetAccountId: "acc_re",+ amount+ }).success+ ).toBe(accepted);+});++describe("statusAfterCostAdjustment", () => {+ it.each([+ // A zero-cost asset a run marked Fully Depreciated, now worth 1,000 with a+ // 200 residual: 800 left to depreciate.+ ["Fully Depreciated", 0, 20, "Active"],+ // Raised, but net book value 200 is at its residual: nothing left.+ ["Fully Depreciated", 800, 20, "Fully Depreciated"],+ ["Active", 0, 0, "Active"]+ ] as const)(+ "%s asset with 1000 cost, %d depreciated, %d%% residual becomes %s",+ (status, accumulatedDepreciation, residualValuePercent, expected) => {+ expect(+ statusAfterCostAdjustment({+ status,+ acquisitionCost: 1000,+ accumulatedDepreciation,+ residualValuePercent+ })+ ).toBe(expected);+ }+ );});diff --git a/apps/erp/app/modules/accounting/accounting.projects.test.ts b/apps/erp/app/modules/accounting/accounting.projects.test.tsdeleted file mode 100644index 086e767e3b..0000000000--- a/apps/erp/app/modules/accounting/accounting.projects.test.ts+++ /dev/null@@ -1,64 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { describe, expect, it, vi } from "vitest";--vi.mock("@carbon/content/glossary", () => ({- glossaryEntries: () => [],- terms: {}-}));--import * as accountingModels from "./accounting.models";--type ProjectValidator = {- safeParse: (- input: unknown- ) =>- | { success: true; data: { name: string; description?: string } }- | { success: false };-};--const projectValidator = Reflect.get(accountingModels, "projectValidator") as- | ProjectValidator- | undefined;--describe("projectValidator", () => {- it("trims the project name and optional description", () => {- expect(projectValidator).toBeDefined();- if (!projectValidator) return;-- const result = projectValidator.safeParse({- name: " Apollo Expansion ",- description: " Customer expansion program "- });-- expect(result.success).toBe(true);- if (result.success) {- expect(result.data).toMatchObject({- name: "Apollo Expansion",- description: "Customer expansion program"- });- }- });-- it("rejects a name that is only whitespace", () => {- expect(projectValidator).toBeDefined();- if (!projectValidator) return;-- expect(projectValidator.safeParse({ name: " " }).success).toBe(false);- });-- it("normalizes an empty description to undefined", () => {- expect(projectValidator).toBeDefined();- if (!projectValidator) return;-- const result = projectValidator.safeParse({- name: "Apollo Expansion",- description: ""- });-- expect(result.success).toBe(true);- if (result.success) expect(result.data.description).toBeUndefined();- });-});diff --git a/apps/erp/app/modules/accounting/accounting.report-cta.test.ts b/apps/erp/app/modules/accounting/accounting.report-cta.test.tsnew file mode 100644index 0000000000..b9e6d3b7b4--- /dev/null+++ b/apps/erp/app/modules/accounting/accounting.report-cta.test.ts@@ -0,0 +1,209 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { applyReportCta } from "./accounting.service";+import { selectReportCompanyIds } from "./accounting.utils";+import type { ChartPeriodSeries } from "./types";+import { NET_INCOME_ACCOUNT_ID } from "./types";++const keys = ["2026-07", "2026-08"];++function account(+ id: string,+ parentId: string | null,+ accountClass: ChartPeriodSeries["class"],+ amounts: [number, number],+ extra: Partial<ChartPeriodSeries> = {}+): ChartPeriodSeries {+ return {+ id,+ parentId,+ class: accountClass,+ name: id,+ number: null,+ active: true,+ companyGroupId: "group",+ isGroup: false,+ isSystem: false,+ incomeBalance: "Balance Sheet",+ accountType: "Equity - No Close",+ consolidatedRate: "Current",+ createdAt: "2026-01-01T00:00:00Z",+ createdBy: "user",+ updatedAt: null,+ updatedBy: null,+ customFields: {},+ tags: null,+ periods: Object.fromEntries(+ keys.map((key, index) => [+ key,+ {+ balanceAtDate: 0,+ netChange: 0,+ translatedBalance: amounts[index] ?? 0,+ translatedNetChange: amounts[index] ?? 0+ }+ ])+ ),+ ...extra+ };+}++// Translated cash 160 / 80 against translated income 120 / 60 leaves a CTA of+// 40 / 20 to close the balance sheet. `booked` is CTA already posted to the+// account, which the report adds to rather than replaces.+function chart(booked = 0): ChartPeriodSeries[] {+ return [+ account("balance-sheet", null, "Asset", [40, 20], {+ isGroup: true,+ isSystem: true+ }),+ account("assets", "balance-sheet", "Asset", [160 + booked, 80 + booked], {+ isGroup: true+ }),+ account("cash", "assets", "Asset", [160 + booked, 80 + booked]),+ account("equity", "balance-sheet", "Equity", [120, 60], { isGroup: true }),+ account("reserves", "equity", "Equity", [0, 0], { isGroup: true }),+ account("custom-cta", "reserves", "Equity", [booked, booked]),+ account("other-cta", "reserves", "Equity", [0, 0]),+ account(NET_INCOME_ACCOUNT_ID, "equity", "Equity", [120, 60]),+ account("income-statement", null, "Revenue", [120, 60], {+ incomeBalance: "Income Statement",+ isGroup: true,+ isSystem: true+ }),+ account("sales", "income-statement", "Revenue", [150, 75], {+ incomeBalance: "Income Statement"+ }),+ account("expense", "income-statement", "Expense", [30, 15], {+ incomeBalance: "Income Statement"+ })+ ];+}++function base(overrides: Partial<Parameters<typeof applyReportCta>[0]> = {}) {+ return {+ accounts: chart(),+ bucketKeys: keys,+ ctaByBucket: { "2026-07": 40, "2026-08": 20 },+ companyGroupId: "group",+ ctaAccountId: "custom-cta",+ ...overrides+ };+}++function translated(rows: ChartPeriodSeries[] | null, id: string) {+ const row = rows?.find((r) => r.id === id);+ return keys.map((key) => row?.periods[key]?.translatedBalance);+}++function withCta(change: Partial<ChartPeriodSeries>) {+ return chart().map((row) =>+ row.id === "custom-cta" ? { ...row, ...change } : row+ );+}++describe("applyReportCta", () => {+ it("posts the CTA to the configured account and rolls it up so the balance sheet closes", () => {+ const { data, error } = applyReportCta(base());+ expect(error).toBeNull();+ expect(translated(data, "custom-cta")).toEqual([40, 20]);+ expect(translated(data, "other-cta")).toEqual([0, 0]);+ expect(translated(data, "reserves")).toEqual([40, 20]);+ expect(translated(data, "equity")).toEqual([160, 80]);+ expect(translated(data, "balance-sheet")).toEqual([0, 0]);+ });++ it("adds the report CTA on top of CTA already booked to the account", () => {+ const { data } = applyReportCta(base({ accounts: chart(10) }));+ expect(translated(data, "custom-cta")).toEqual([50, 30]);+ expect(translated(data, "equity")).toEqual([170, 90]);+ expect(translated(data, "balance-sheet")).toEqual([0, 0]);+ });++ it("fills an untranslated net income from the translated income statement", () => {+ // Sales 150 − expense 30 = 120; the raw 80 stays as it was.+ const accounts = chart().map((row) =>+ row.id === NET_INCOME_ACCOUNT_ID+ ? {+ ...row,+ periods: Object.fromEntries(+ keys.map((key) => [key, { netChange: 80, balanceAtDate: 80 }])+ )+ }+ : row+ );+ const { data } = applyReportCta(base({ accounts }));+ const income = data?.find((row) => row.id === NET_INCOME_ACCOUNT_ID);+ expect(income?.periods["2026-07"]).toEqual({+ netChange: 80,+ balanceAtDate: 80,+ translatedBalance: 120,+ translatedNetChange: 120+ });+ expect(translated(data, "balance-sheet")).toEqual([0, 0]);+ });++ it("leaves the input chart untouched and gives the same answer twice", () => {+ const accounts = chart();+ const original = structuredClone(accounts);+ const first = applyReportCta(base({ accounts }));+ const second = applyReportCta(base({ accounts }));+ expect(accounts).toEqual(original);+ expect(second).toEqual(first);+ });++ it.each([+ ["missing from the chart", base({ ctaAccountId: "missing" })],+ ["inactive", base({ accounts: withCta({ active: false }) })],+ ["a group account", base({ accounts: withCta({ isGroup: true }) })],+ ["not Equity", base({ accounts: withCta({ class: "Revenue" }) })],+ [+ "on the income statement",+ base({ accounts: withCta({ incomeBalance: "Income Statement" }) })+ ],+ [+ "in another company group",+ base({ accounts: withCta({ companyGroupId: "other-group" }) })+ ],+ [+ "missing a period cell",+ base({+ accounts: withCta({+ periods: { "2026-07": chart()[5]!.periods["2026-07"]! }+ })+ })+ ],+ ["given no CTA for a period", base({ ctaByBucket: { "2026-07": 40 } })],+ [+ "given a non-finite CTA",+ base({ ctaByBucket: { "2026-07": 40, "2026-08": Number.NaN } })+ ]+ ])("refuses the whole report when the CTA account is %s", (_label, args) => {+ const result = applyReportCta(args);+ expect(result.data).toBeNull();+ expect(result.error).not.toBeNull();+ });+});++describe("selectReportCompanyIds", () => {+ const group = ["parent", "child"];++ it.each([+ ["every company for all", "all", ["parent", "child"]],+ ["the named company", "child", ["child"]],+ ["the user's own company with no selection", null, ["parent"]]+ ])("selects %s", (_label, param, expected) => {+ expect(selectReportCompanyIds(param, group, "parent")).toEqual(expected);+ });++ it("refuses a company outside the group", () => {+ expect(selectReportCompanyIds("unrelated", group, "parent")).toBeNull();+ });++ it("refuses all when the group has no companies", () => {+ expect(selectReportCompanyIds("all", [], "parent")).toBeNull();+ });+});diff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.tsindex ed2fdd57b4..7529d4b023 100644--- a/apps/erp/app/modules/accounting/accounting.service.ts+++ b/apps/erp/app/modules/accounting/accounting.service.ts@@ -295,10 +295,14 @@ import {depreciationFloor,depreciationRunLinesMatch,diffJournalLines,+ fiscalYearPeriodDates,hasAccountingCutover,+ hidesSupersededJournals,isFutureRunPeriod,LOCK_PERIOD_TASK_NAME,monthEndOf,+ periodDeletionRefusal,+ periodPostingRefusal,runPostingTargets,usageKey} from "./accounting.utils";@@ -907,6 +911,24 @@ export async function applyCtaToReportPeriodSeries(}};}+ return applyReportCta({ ...args, companyGroupId, ctaAccountId: accountId });+}++/** Add each bucket's report CTA to the configured Equity account, fill the+ * synthetic net income from the translated income statement when the+ * translation left it empty, then roll the translated values up. Returns a+ * new chart; the input is never mutated. */+export function applyReportCta(args: {+ accounts: ChartPeriodSeries[];+ bucketKeys: string[];+ ctaByBucket: Record<string, number>;+ companyGroupId: string;+ ctaAccountId: string;+}): {+ data: ChartPeriodSeries[] | null;+ error: { message: string } | null;+} {+ const { companyGroupId, ctaAccountId: accountId } = args;const ctaAccount = args.accounts.find((account) => account.id === accountId);if (!ctaAccount) {return {@@ -2710,24 +2732,8 @@ export async function getOrCreateAccountingPeriod((existing.data as unknown as AccountingPeriodCloseColumns).closeStatus ??(existing.data.closedAt ? "Closed" : "Open");- if (closeStatus === "Closed") {- return {- data: null,- error: {- message: "Accounting period is closed. Reopen it before posting."- }- };- }-- if (closeStatus === "Locked" && source === "operational") {- return {- data: null,- error: {- message:- "Accounting period is locked. Post as an accounting adjustment or unlock the period first."- }- };- }+ const refusal = periodPostingRefusal(closeStatus, source);+ if (refusal) return { data: null, error: { message: refusal } };if (existing.data.status === "Inactive" && (await isCurrentMonth())) {await client@@ -2874,14 +2880,7 @@ export async function getAccountingPeriodDeletability(const journalCount = (journals.count as number | null) ?? 0;const closeStatus = period.data.closeStatus;- const reason =- closeStatus !== "Open"- ? `Only open periods can be deleted — this period is ${closeStatus}.`- : journalCount > 0- ? `This period has ${journalCount} journal ${- journalCount === 1 ? "entry" : "entries"- } posted to it and cannot be deleted.`- : null;+ const reason = periodDeletionRefusal(closeStatus, journalCount);return {data: {@@ -3284,10 +3283,6 @@ export async function createFiscalYearPeriods(? (MONTH_NUMBER[settings.data.startMonth] ?? 1): 1;- // FY is named by its ending calendar year; a non-January start begins in the- // prior calendar year.- const firstYear = startMonth === 1 ? args.fiscalYear : args.fiscalYear - 1;-const existing = await (client.from("accountingPeriod") as any).select("periodNumber").eq("companyId", args.companyId)@@ -3299,24 +3294,20 @@ export async function createFiscalYearPeriods());- const rows = [];- for (let p = 1; p <= 12; p++) {- if (existingNumbers.has(p)) continue;- const monthIndex = (startMonth - 1 + (p - 1)) % 12; // 0-indexed- const year = firstYear + Math.floor((startMonth - 1 + (p - 1)) / 12);- const startDate = new Date(Date.UTC(year, monthIndex, 1));- const endDate = new Date(Date.UTC(year, monthIndex + 1, 0));- rows.push({- companyId: args.companyId,- startDate: startDate.toISOString().split("T")[0],- endDate: endDate.toISOString().split("T")[0],- status: "Inactive",- closeStatus: "Open",- fiscalYear: args.fiscalYear,- periodNumber: p,- createdBy: args.userId- });- }+ const rows = fiscalYearPeriodDates(+ args.fiscalYear,+ startMonth,+ existingNumbers+ ).map((period) => ({+ companyId: args.companyId,+ startDate: period.startDate,+ endDate: period.endDate,+ status: "Inactive",+ closeStatus: "Open",+ fiscalYear: args.fiscalYear,+ periodNumber: period.periodNumber,+ createdBy: args.userId+ }));if (rows.length === 0) {return { data: [], error: null };@@ -3629,6 +3620,114 @@ function runPreviewer(* revenue recognition and depreciation runs for `endDate` would hold* (`getPeriodRunPreview`).*/+/** The three run checks on the close checklist. Each counts what a new run+ * would claim for the period plus what its Draft runs already hold, and+ * fails when either is non-zero or the preview could not run. A failed read+ * of the Draft runs counts as one, so the check fails closed. */+export function periodRunChecks(args: {+ runPreview: PeriodRunPreview;+ heldRunRows: {+ data:+ | {+ amount: number;+ run: { id: string; runId: string; periodEnd: string; type: RunType };+ }[]+ | null;+ error: unknown;+ };+ draftDepreciationRuns: {+ data:+ | {+ id: string;+ depreciationRunId: string;+ periodEnd: string;+ depreciationRunLine: { amount: number }[];+ }[]+ | null;+ error: unknown;+ };+}): PeriodReadinessCheck[] {+ const { runPreview, heldRunRows, draftDepreciationRuns } = args;++ const heldByType = (type: RunType) => {+ const draftRuns = new Map<+ string,+ { id: string; readableId: string; periodEnd: string }+ >();+ let amount = 0;+ let count = 0;+ for (const line of heldRunRows.data ?? []) {+ if (line.run.type !== type) continue;+ draftRuns.set(line.run.id, {+ id: line.run.id,+ readableId: line.run.runId,+ periodEnd: line.run.periodEnd+ });+ amount += Number(line.amount);+ count += 1;+ }+ return { draftRuns, amount, count: heldRunRows.error ? 1 : count };+ };+ const heldRevenue = heldByType("Revenue Recognition");+ const revenueCount = runPreview.revenue.count + heldRevenue.count;+ const heldLease = heldByType("Lease");+ const leaseCount = runPreview.lease.count + heldLease.count;++ const depreciationDraftRuns = draftDepreciationRuns.data ?? [];+ const draftDepreciationAmount = depreciationDraftRuns.reduce(+ (sum, run) =>+ sum ++ run.depreciationRunLine.reduce(+ (lineSum, line) => lineSum + Number(line.amount),+ 0+ ),+ 0+ );+ const depreciationCount =+ runPreview.depreciation.count ++ (draftDepreciationRuns.error ? 1 : depreciationDraftRuns.length);++ return [+ {+ autoCheckKey: "draft-depreciation",+ severity: "Warning",+ label:+ "Assets a depreciation run would depreciate for this period, and Draft depreciation runs ending in it",+ failing: depreciationCount > 0 || runPreview.depreciation.error !== null,+ count: depreciationCount,+ amount: round(runPreview.depreciation.amount + draftDepreciationAmount),+ due: runPreview.depreciation,+ draftRuns: depreciationDraftRuns.map((run) => ({+ id: run.id,+ readableId: run.depreciationRunId,+ periodEnd: run.periodEnd+ }))+ },+ {+ autoCheckKey: "unposted-revenue-schedules",+ severity: "Warning",+ label:+ "Revenue a recognition run would recognize by this period end, and revenue Draft runs hold",+ failing: revenueCount > 0 || runPreview.revenue.error !== null,+ count: revenueCount,+ amount: round(runPreview.revenue.amount + heldRevenue.amount),+ due: runPreview.revenue,+ draftRuns: [...heldRevenue.draftRuns.values()]+ },+ {+ autoCheckKey: "unposted-lease-schedules",+ severity: "Warning",+ label:+ "Lease and rental entries a lease run would post by this period end, and lease Draft runs hold",+ failing: leaseCount > 0 || runPreview.lease.error !== null,+ count: leaseCount,+ amount: round(runPreview.lease.amount + heldLease.amount),+ due: runPreview.lease,+ draftRuns: [...heldLease.draftRuns.values()]+ }+ ];+}+export async function computePeriodReadiness(client: SupabaseClient<Database>,companyId: string,@@ -3780,48 +3879,11 @@ export async function computePeriodReadiness(.order("id"));- // Each run type: what a new run would claim, plus what its Draft runs hold.- const heldByType = (type: RunType) => {- const draftRuns = new Map<- string,- { id: string; readableId: string; periodEnd: string }- >();- let amount = 0;- let count = 0;- for (const line of heldRunRows.data ?? []) {- if (line.run.type !== type) continue;- draftRuns.set(line.run.id, {- id: line.run.id,- readableId: line.run.runId,- periodEnd: line.run.periodEnd- });- amount += Number(line.amount);- count += 1;- }- // A failed read fails both checks closed.- return { draftRuns, amount, count: heldRunRows.error ? 1 : count };- };- const heldRevenue = heldByType("Revenue Recognition");- const revenueDraftRuns = heldRevenue.draftRuns;- const heldRevenueAmount = heldRevenue.amount;- const revenueCount = runPreview.revenue.count + heldRevenue.count;- const heldLease = heldByType("Lease");- const leaseCount = runPreview.lease.count + heldLease.count;-- // Depreciation: the assets a new run would depreciate, plus Draft runs.- const depreciationDraftRuns = draftDepreciationRuns.data ?? [];- const draftDepreciationAmount = depreciationDraftRuns.reduce(- (sum, run) =>- sum +- run.depreciationRunLine.reduce(- (lineSum, line) => lineSum + Number(line.amount),- 0- ),- 0- );- const depreciationCount =- runPreview.depreciation.count +- (draftDepreciationRuns.error ? 1 : depreciationDraftRuns.length);+ const runChecks = periodRunChecks({+ runPreview,+ heldRunRows,+ draftDepreciationRuns+ });const unbalanced = (journalsInPeriod.data ?? []).filter((j) =>@@ -3930,43 +3992,7 @@ export async function computePeriodReadiness(failing: externalGlSync.failing,count: externalGlSync.count},- {- autoCheckKey: "draft-depreciation",- severity: "Warning",- label:- "Assets a depreciation run would depreciate for this period, and Draft depreciation runs ending in it",- failing: depreciationCount > 0 || runPreview.depreciation.error !== null,- count: depreciationCount,- amount: round(runPreview.depreciation.amount + draftDepreciationAmount),- due: runPreview.depreciation,- draftRuns: depreciationDraftRuns.map((run) => ({- id: run.id,- readableId: run.depreciationRunId,- periodEnd: run.periodEnd- }))- },- {- autoCheckKey: "unposted-revenue-schedules",- severity: "Warning",- label:- "Revenue a recognition run would recognize by this period end, and revenue Draft runs hold",- failing: revenueCount > 0 || runPreview.revenue.error !== null,- count: revenueCount,- amount: round(runPreview.revenue.amount + heldRevenueAmount),- due: runPreview.revenue,- draftRuns: [...revenueDraftRuns.values()]- },- {- autoCheckKey: "unposted-lease-schedules",- severity: "Warning",- label:- "Lease and rental entries a lease run would post by this period end, and lease Draft runs hold",- failing: leaseCount > 0 || runPreview.lease.error !== null,- count: leaseCount,- amount: round(runPreview.lease.amount + heldLease.amount),- due: runPreview.lease,- draftRuns: [...heldLease.draftRuns.values()]- },+ ...runChecks,{autoCheckKey: "unmatched-ic",severity: "Warning",@@ -5987,14 +6013,7 @@ export async function getJournalEntries();}- // A Superseded journal is a Provisional one the opening journal replaced at- // the cutover. It stays out of the list unless a status filter asks for it.- const filtersOnStatus =- Boolean(args.status) ||- (args.filters ?? []).some(- (filter) => filter.column === "status" && Boolean(filter.value)- );- if (!filtersOnStatus) {+ if (hidesSupersededJournals(args)) {query = query.neq("status", "Superseded");}diff --git a/apps/erp/app/modules/accounting/accounting.translation.test.ts b/apps/erp/app/modules/accounting/accounting.translation.test.tsindex c407cbb909..20236ce7e9 100644--- a/apps/erp/app/modules/accounting/accounting.translation.test.ts+++ b/apps/erp/app/modules/accounting/accounting.translation.test.ts@@ -7,24 +7,6 @@ import { computeReportPeriodBuckets } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { describe, expect, it, vi } from "vitest";-// The settings/glossary barrels evaluate Lingui macros that Vitest does not-// transform. The real translation service needs neither dependency here.-vi.mock("~/modules/settings/settings.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- getNextSequence: vi.fn()-}));-vi.mock("@carbon/content/glossary", () => ({- getDefinitionText: () => "",- getEntry: () => undefined,- getTermText: () => "",- glossaryEntries: () => [],- hasEntry: () => false,- listEntries: () => [],- lookupEntry: () => undefined,- termSlug: (term: string) => term,- terms: {}-}));-import {applyCtaToReportPeriodSeries,getFinancialStatementBalances,diff --git a/apps/erp/app/modules/accounting/accounting.utils.test.ts b/apps/erp/app/modules/accounting/accounting.utils.test.tsindex 824b3550e3..42a6a9f8a2 100644--- a/apps/erp/app/modules/accounting/accounting.utils.test.ts+++ b/apps/erp/app/modules/accounting/accounting.utils.test.ts@@ -32,10 +32,6 @@ import {usageKey} from "./accounting.utils";-// ----------------------------------------------------------------------------// Acquisition (registration opening entry)-// ----------------------------------------------------------------------------describe("acquisitionLines", () => {// Map each line's role to the account class its amount is stored against, so// we can assert the entry balances (display debits === display credits).@@ -105,51 +101,22 @@ describe("acquisitionLines", () => {});});-// ----------------------------------------------------------------------------// Disposal gain/loss-// ----------------------------------------------------------------------------describe("computeDisposalGainLoss", () => {- it("books a gain as a credit (negative stored amount) to the disposal account", () => {- // proceeds 1000, NBV 600 → gain 400 credited (income)- const { gainLoss, disposalStoredAmount } = computeDisposalGainLoss(- 1000,- 600- );- expect(gainLoss).toBe(400);- expect(disposalStoredAmount).toBe(-400);- });-- it("books a loss as a debit (positive stored amount) to the disposal account", () => {- // proceeds 250, NBV 600 → loss 350 debited (expense)- const { gainLoss, disposalStoredAmount } = computeDisposalGainLoss(- 250,- 600- );- expect(gainLoss).toBe(-350);- expect(disposalStoredAmount).toBe(350);- });-- it("returns a zero stored amount when proceeds equal NBV (no line needed)", () => {- const { gainLoss, disposalStoredAmount } = computeDisposalGainLoss(- 600,- 600- );- expect(gainLoss).toBe(0);- expect(disposalStoredAmount).toBe(0);- });-- it("treats a scrap (zero proceeds) as a full loss of the net book value", () => {- const { gainLoss, disposalStoredAmount } = computeDisposalGainLoss(0, 800);- expect(gainLoss).toBe(-800);- expect(disposalStoredAmount).toBe(800);+ // A gain is a credit to the disposal account (stored negative), a loss a+ // debit (stored positive).+ it.each([+ ["a gain", 1000, 600, 400, -400],+ ["a loss", 250, 600, -350, 350],+ ["nothing at NBV", 600, 600, 0, 0],+ ["a scrap as a full loss of NBV", 0, 800, -800, 800]+ ])("books %s", (_, proceeds, nbv, gainLoss, disposalStoredAmount) => {+ expect(computeDisposalGainLoss(proceeds, nbv)).toEqual({+ gainLoss,+ disposalStoredAmount+ });});});-// ----------------------------------------------------------------------------// Depreciation-run line display (NBV After)-// ----------------------------------------------------------------------------describe("depreciationRunLineDisplay", () => {it("starts a later month from the earlier months of the same run", () => {// Two months of 1,800 on a 120,000 asset with 10,000 already depreciated.@@ -210,30 +177,8 @@ describe("depreciationRunLineDisplay", () => {expect(accumulatedDepreciationBefore).toBe(20_000);expect(netBookValueAfter).toBe(76_000);});-- it("keeps the row arithmetic cost − accumulated − amount = NBV after", () => {- for (const isPosted of [false, true]) {- const accumulatedDepreciation = isPosted- ? priorAccumulated + amount- : priorAccumulated;- const { accumulatedDepreciationBefore, netBookValueAfter } =- depreciationRunLineDisplay({- acquisitionCost: cost,- accumulatedDepreciation,- amount,- isPosted- });- expect(cost - accumulatedDepreciationBefore - amount).toBe(- netBookValueAfter- );- }- });});-// ----------------------------------------------------------------------------// Date helpers-// ----------------------------------------------------------------------------describe("depreciationRunLinesMatch", () => {const P = "2026-09-30";const computed = [@@ -343,67 +288,34 @@ describe("runPostingTargets", () => {});});-describe("getMonthsBetween", () => {- it("returns 1 for same month when end day >= start day", () => {- expect(- getMonthsBetween(parseDate("2025-01-15"), parseDate("2025-01-20"))- ).toBe(1);- });-- it("returns 0 when end day < start day in same month", () => {- expect(- getMonthsBetween(parseDate("2025-01-20"), parseDate("2025-01-15"))- ).toBe(0);- });-- it("counts months across years", () => {- expect(- getMonthsBetween(parseDate("2024-11-01"), parseDate("2025-02-01"))- ).toBe(4);- });-- it("returns 0 for start after end", () => {- expect(- getMonthsBetween(parseDate("2025-06-01"), parseDate("2025-01-01"))- ).toBe(0);- });+// Months counted inclusively: a partial month at the start counts once the+// end day reaches the start day.+it.each([+ ["2025-01-15", "2025-01-20", 1],+ ["2025-01-20", "2025-01-15", 0],+ ["2024-11-01", "2025-02-01", 4],+ ["2025-06-01", "2025-01-01", 0]+])("getMonthsBetween(%s, %s) is %d", (start, end, months) => {+ expect(getMonthsBetween(parseDate(start), parseDate(end))).toBe(months);});-describe("getMonthsElapsed", () => {- it("returns 0 for same month", () => {- expect(- getMonthsElapsed(parseDate("2025-01-15"), parseDate("2025-01-20"))- ).toBe(0);- });-- it("counts elapsed months", () => {- expect(- getMonthsElapsed(parseDate("2025-01-01"), parseDate("2025-04-01"))- ).toBe(3);- });-- it("returns 0 when start after end", () => {- expect(- getMonthsElapsed(parseDate("2025-06-01"), parseDate("2025-01-01"))- ).toBe(0);- });+it.each([+ ["2025-01-15", "2025-01-20", 0],+ ["2025-01-01", "2025-04-01", 3],+ ["2025-06-01", "2025-01-01", 0]+])("getMonthsElapsed(%s, %s) is %d", (start, end, months) => {+ expect(getMonthsElapsed(parseDate(start), parseDate(end))).toBe(months);});-describe("addOneMonth", () => {- it("advances to first of next month", () => {- expect(addOneMonth("2025-01-15").toString()).toBe("2025-02-01");- });-- it("rolls over year boundary", () => {- expect(addOneMonth("2025-12-15").toString()).toBe("2026-01-01");- });-- // Aug 31 + 1 month used to overflow "Sep 31" into Oct 1, so September got- // no depreciation after an August run.- it("advances a 31st into a shorter month without skipping it", () => {- expect(addOneMonth("2026-08-31").toString()).toBe("2026-09-01");- expect(addOneMonth("2026-01-31").toString()).toBe("2026-02-01");- });+// A 31st must land on the 1st of the next month: overflowing "Sep 31" into+// Oct 1 left September with no depreciation after an August run.+it.each([+ ["2025-01-15", "2025-02-01"],+ ["2025-12-15", "2026-01-01"],+ ["2026-08-31", "2026-09-01"],+ ["2026-01-31", "2026-02-01"]+])("addOneMonth(%s) is %s", (date, next) => {+ expect(addOneMonth(date).toString()).toBe(next);});describe("month arithmetic after a posted run", () => {@@ -450,29 +362,18 @@ describe("month arithmetic after a posted run", () => {});});-describe("getLastDayOfMonth", () => {- it("returns 28 for Feb 2025", () => {- expect(getLastDayOfMonth(2025, 1)).toBe("2025-02-28");- });-- it("returns 29 for Feb 2024 (leap year)", () => {- expect(getLastDayOfMonth(2024, 1)).toBe("2024-02-29");- });-- it("returns 31 for January", () => {- expect(getLastDayOfMonth(2025, 0)).toBe("2025-01-31");- });+it.each([+ [2025, 1, "2025-02-28"],+ [2024, 1, "2024-02-29"],+ [2025, 0, "2025-01-31"]+])("getLastDayOfMonth(%d, %d) is %s", (year, monthIndex, expected) => {+ expect(getLastDayOfMonth(year, monthIndex)).toBe(expected);});describe("getNextPeriodEnd", () => {- it("returns next month's last day when given a previous period", () => {- const result = getNextPeriodEnd("2025-01-31");- expect(result).toBe("2025-02-28");- });-- it("handles year rollover", () => {- const result = getNextPeriodEnd("2025-12-31");- expect(result).toBe("2026-01-31");+ it("returns the month end after the previous period, across a year", () => {+ expect(getNextPeriodEnd("2025-01-31")).toBe("2025-02-28");+ expect(getNextPeriodEnd("2025-12-31")).toBe("2026-01-31");});it("defaults to the end of the current month of the given business date", () => {@@ -516,38 +417,23 @@ describe("getNextRevenueRecognitionPeriodEnd", () => {});});-// ----------------------------------------------------------------------------// MACRS table lookups-// ----------------------------------------------------------------------------describe("getMacrsPercentage", () => {- it("returns null for 27.5-year property", () => {- expect(getMacrsPercentage("27.5", 1, "Half-Year")).toBeNull();- });-- it("returns null for 39-year property", () => {- expect(getMacrsPercentage("39", 1, "Half-Year")).toBeNull();- });-- it("returns correct half-year 5-year year-1 percentage", () => {- expect(getMacrsPercentage("5", 1, "Half-Year")).toBe(20.0);- });-- it("returns correct half-year 7-year year-1 percentage", () => {- expect(getMacrsPercentage("7", 1, "Half-Year")).toBe(14.29);- });-- it("returns 0 when year exceeds table length", () => {- expect(getMacrsPercentage("3", 10, "Half-Year")).toBe(0);- });-- it("returns correct mid-quarter Q1 5-year year-1 percentage", () => {- expect(getMacrsPercentage("5", 1, "Mid-Quarter", 1)).toBe(35.0);- });-- it("returns correct mid-quarter Q4 7-year year-1 percentage", () => {- expect(getMacrsPercentage("7", 1, "Mid-Quarter", 4)).toBe(3.57);- });+ it.each([+ ["27.5", 1, "Half-Year", undefined, null],+ ["39", 1, "Half-Year", undefined, null],+ ["5", 1, "Half-Year", undefined, 20],+ ["7", 1, "Half-Year", undefined, 14.29],+ ["3", 10, "Half-Year", undefined, 0],+ ["5", 1, "Mid-Quarter", 1, 35],+ ["7", 1, "Mid-Quarter", 4, 3.57]+ ] as const)(+ "%s-year property, year %d, %s (quarter %s) is %s%%",+ (propertyClass, year, convention, quarter, expected) => {+ expect(getMacrsPercentage(propertyClass, year, convention, quarter)).toBe(+ expected+ );+ }+ );it("half-year 5-year table sums to ~100%", () => {let total = 0;@@ -558,29 +444,11 @@ describe("getMacrsPercentage", () => {});});-// ----------------------------------------------------------------------------// calculateMacrsDepreciation-// ----------------------------------------------------------------------------describe("calculateMacrsDepreciation", () => {- it("returns 0 for zero basis", () => {- expect(- calculateMacrsDepreciation({- adjustedBasis: 0,- propertyClass: "5",- convention: "Half-Year",- depreciationStartDate: "2025-01-15",- periodEnd: "2025-12-31",- lastPostedPeriodEnd: null,- accumulatedTaxDepreciation: 0,- bonusAmount: 0,- decimalPlaces: 2- })- ).toBe(0);- });-- it("calculates year-1 half-year 5-year depreciation on $100,000 asset", () => {- const result = calculateMacrsDepreciation({+ const macrs = (+ overrides: Partial<Parameters<typeof calculateMacrsDepreciation>[0]>+ ) =>+ calculateMacrsDepreciation({adjustedBasis: 100000,propertyClass: "5",convention: "Half-Year",@@ -589,47 +457,33 @@ describe("calculateMacrsDepreciation", () => {lastPostedPeriodEnd: null,accumulatedTaxDepreciation: 0,bonusAmount: 0,- decimalPlaces: 2+ decimalPlaces: 2,+ ...overrides});- // Year 1 at 20% of $100k = $20,000- expect(result).toBe(20000);++ it("returns 0 for zero basis", () => {+ expect(macrs({ adjustedBasis: 0 })).toBe(0);});- it("calculates 39-year property monthly depreciation", () => {- const result = calculateMacrsDepreciation({- adjustedBasis: 468000,- propertyClass: "39",- convention: "Half-Year",- depreciationStartDate: "2025-01-15",- periodEnd: "2025-12-31",- lastPostedPeriodEnd: null,- accumulatedTaxDepreciation: 0,- bonusAmount: 0,- decimalPlaces: 2- });- // $468,000 / (39*12) = $1,000/month; 11.5 months for first period- expect(result).toBeCloseTo(11500, -1);+ it("takes the 20% year-1 percentage of a 5-year half-year asset", () => {+ expect(macrs({})).toBe(20000);});- it("caps at remaining depreciable amount", () => {- const result = calculateMacrsDepreciation({- adjustedBasis: 10000,- propertyClass: "5",- convention: "Half-Year",- depreciationStartDate: "2025-01-15",- periodEnd: "2025-12-31",- lastPostedPeriodEnd: null,- accumulatedTaxDepreciation: 9500,- bonusAmount: 0,- decimalPlaces: 2- });- expect(result).toBeLessThanOrEqual(500);+ it("depreciates 39-year property straight line from mid-month", () => {+ // 468,000 / (39 × 12) = 1,000 a month; Jan 15 to Dec 31 is 11.5 months.+ expect(macrs({ adjustedBasis: 468000, propertyClass: "39" })).toBe(11500);});-});-// ----------------------------------------------------------------------------// calculateDepreciation (book)-// ---------------------------------------------------------------------------+ it("caps 39-year property at what is left of the basis", () => {+ expect(+ macrs({+ adjustedBasis: 468000,+ propertyClass: "39",+ accumulatedTaxDepreciation: 467000+ })+ ).toBe(1000);+ });+});describe("calculateDepreciation", () => {const baseAsset = {@@ -653,8 +507,9 @@ describe("calculateDepreciation", () => {it("calculates multi-month period", () => {// 6 months: 1800 * 6 = 10800- const result = calculateDepreciation(baseAsset, "2025-06-30", null, 2);- expect(result).toBeCloseTo(10800, 0);+ expect(calculateDepreciation(baseAsset, "2025-06-30", null, 2)).toBe(+ 10800+ );});it("returns 0 when fully depreciated", () => {@@ -675,7 +530,6 @@ describe("calculateDepreciation", () => {it("uses lastPostedPeriodEnd to narrow the window", () => {// After a Jan 31 run, a Mar 31 run covers February and March. This- // test used to expect one month: Jan 31 + 1 month overflowed to Mar 1.const result = calculateDepreciation(baseAsset,"2025-03-31",@@ -689,10 +543,9 @@ describe("calculateDepreciation", () => {describe("Declining Balance", () => {const dbAsset = { ...baseAsset, depreciationMethod: "Declining Balance" };- it("first month produces higher amount than straight line", () => {- const slResult = calculateDepreciation(baseAsset, "2025-01-31", null, 2);- const dbResult = calculateDepreciation(dbAsset, "2025-01-31", null, 2);- expect(dbResult).toBeGreaterThanOrEqual(slResult);+ it("takes double the straight-line rate on the opening book value", () => {+ // 60 months = 20%/yr straight line, doubled to 40%/yr: 120,000 × 40% / 12.+ expect(calculateDepreciation(dbAsset, "2025-01-31", null, 2)).toBe(4000);});it("returns 0 when fully depreciated", () => {@@ -736,10 +589,6 @@ describe("calculateDepreciation", () => {});});-// ----------------------------------------------------------------------------// calculateTaxDepreciation-// ----------------------------------------------------------------------------describe("calculateTaxDepreciation", () => {it("returns null when no tax method configured", () => {const result = calculateTaxDepreciation(@@ -787,32 +636,28 @@ describe("calculateTaxDepreciation", () => {expect(result).toBe(20000);});- it("calculates MACRS for a single-month period (how depreciation runs work)", () => {- const result = calculateTaxDepreciation(- macrsAsset,- "2025-05-31",- null,- 2+ it("spreads year 1 evenly over the months from January", () => {+ // 20,000 over Jan–Dec; through May is 5/12 of it.+ expect(calculateTaxDepreciation(macrsAsset, "2025-05-31", null, 2)).toBe(+ 8333.33);- expect(result).not.toBeNull();- expect(result!).toBeGreaterThan(0);});- it("calculates MACRS for second monthly period with lastPostedPeriodEnd", () => {- // Asset placed 2026-05-24, first run posted with periodEnd 2026-05-31- // Second run for periodEnd 2026-06-30- const result = calculateTaxDepreciation(- {- ...macrsAsset,- depreciationStartDate: "2026-05-24",- acquisitionDate: "2026-05-24"- },- "2026-06-30",- "2026-05-31",- 2- );- expect(result).not.toBeNull();- expect(result!).toBeGreaterThan(0);+ it("takes only the next month once the first month is posted", () => {+ // Placed in May: year 1's 20,000 spreads over May–Dec, 2,500 a month.+ expect(+ calculateTaxDepreciation(+ {+ ...macrsAsset,+ depreciationStartDate: "2026-05-24",+ acquisitionDate: "2026-05-24",+ accumulatedTaxDepreciation: 2500+ },+ "2026-06-30",+ "2026-05-31",+ 2+ )+ ).toBe(2500);});it("handles null bonusDepreciationPercent (DB default)", () => {@@ -848,11 +693,8 @@ describe("calculateTaxDepreciation", () => {"2025-12-31",2);- // Bonus should NOT be applied again (accumulatedTax > 0)- // Only MACRS on the $40k adjusted basis- expect(result).not.toBeNull();- expect(result!).toBeGreaterThan(0);- expect(result!).toBeLessThan(60000);+ // Year 2 MACRS only: 32% of the 40,000 basis left after the bonus.+ expect(result).toBe(12800);});it("handles 100% bonus depreciation", () => {@@ -899,7 +741,7 @@ describe("calculateTaxDepreciation", () => {null,2);- expect(result).toBeCloseTo(12000, 0);+ expect(result).toBe(12000);});it("returns 0 when fully depreciated", () => {@@ -923,15 +765,11 @@ describe("calculateTaxDepreciation", () => {bonusDepreciationPercent: null};- it("produces a positive result", () => {- const result = calculateTaxDepreciation(- dbTaxAsset,- "2025-12-31",- null,- 2+ it("compounds the doubled rate month by month", () => {+ // 40%/yr monthly is 1/30: 100,000 × (1 − (29/30)^12).+ expect(calculateTaxDepreciation(dbTaxAsset, "2025-12-31", null, 2)).toBe(+ 33423.51);- expect(result).not.toBeNull();- expect(result!).toBeGreaterThan(0);});it("returns 0 when fully depreciated", () => {@@ -942,10 +780,6 @@ describe("calculateTaxDepreciation", () => {});});-// ----------------------------------------------------------------------------// buildDepreciationLines-// ----------------------------------------------------------------------------describe("buildDepreciationLines", () => {const baseAsset = {id: "asset-1",@@ -966,16 +800,7 @@ describe("buildDepreciationLines", () => {bonusDepreciationPercent: 0};- const total = (lines: { amount: number; taxAmount: number | null }[]) =>- lines.reduce<{ amount: number; taxAmount: number }>(- (sum, line) => ({- amount: sum.amount + line.amount,- taxAmount: sum.taxAmount + (line.taxAmount ?? 0)- }),- { amount: 0, taxAmount: 0 }- );-- it("returns one line per month, each with book and tax amounts when tax is enabled", () => {+ it("returns one line per month with book and tax amounts when tax is enabled", () => {const lines = buildDepreciationLines([baseAsset],"2025-12-31",@@ -999,10 +824,10 @@ describe("buildDepreciationLines", () => {"2025-11-30","2025-12-31"]);- for (const line of lines) {- expect(line.amount).toBeGreaterThan(0);- expect(line.taxAmount!).toBeGreaterThan(0);- }+ // Book 108,000 / 60 = 1,800 a month; tax MACRS 20% of 120,000 over 12.+ expect(+ lines.every((line) => line.amount === 1800 && line.taxAmount === 2000)+ ).toBe(true);});it("returns null taxAmount when tax is disabled", () => {@@ -1049,9 +874,10 @@ describe("buildDepreciationLines", () => {new Map(),2);- expect(lines.length).toBeGreaterThan(0);- expect(lines.every((line) => line.amount === 0)).toBe(true);- expect(total(lines).taxAmount).toBeGreaterThan(0);+ expect(lines).toHaveLength(12);+ expect(+ lines.every((line) => line.amount === 0 && line.taxAmount === 2000)+ ).toBe(true);});it("handles multiple assets", () => {@@ -1070,20 +896,6 @@ describe("buildDepreciationLines", () => {);});- it("book vs tax difference: MACRS produces more year-1 depreciation than SL", () => {- const lines = buildDepreciationLines(- [baseAsset],- "2025-12-31",- null,- true,- new Map(),- 2- );- // Book SL: 108k/60mo * 12mo = $21,600- // Tax MACRS 5-yr HY: 120k * 20% = $24,000- expect(total(lines)).toEqual({ amount: 21600, taxAmount: 24000 });- });-it("splits a 3-month straight-line catch-up into 3 equal months", () => {const lines = buildDepreciationLines([baseAsset],@@ -1111,9 +923,8 @@ describe("buildDepreciationLines", () => {new Map(),2);- expect(lines).toHaveLength(3);- expect(lines[1].amount).toBeLessThan(lines[0].amount);- expect(lines[2].amount).toBeLessThan(lines[1].amount);+ // 1/30 of the opening value each month: 120,000, 116,000, 112,133.33.+ expect(lines.map((line) => line.amount)).toEqual([4000, 3866.67, 3737.78]);});it("charges units of production only in the months with logged usage", () => {@@ -1179,8 +990,12 @@ describe("buildDepreciationLines", () => {"2025-05-31","2025-06-30"]);- expect(lines[0].taxAmount).toBeGreaterThanOrEqual(60000);- expect(lines.slice(1).every((line) => line.taxAmount! < 60000)).toBe(true);+ // 20% of the 60,000 basis spread over April–December, 1,333.33 a month;+ // each month takes cumulative-to-date less what is taken, so the cent+ // lands in May.+ expect(lines.map((line) => line.taxAmount)).toEqual([+ 61333.33, 1333.34, 1333.33+ ]);});});diff --git a/apps/erp/app/modules/accounting/accounting.utils.ts b/apps/erp/app/modules/accounting/accounting.utils.tsindex 39c0f88b6f..a66d61c7ce 100644--- a/apps/erp/app/modules/accounting/accounting.utils.ts+++ b/apps/erp/app/modules/accounting/accounting.utils.ts@@ -3,9 +3,16 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { dayBeforeCutover } from "@carbon/database/accounting-cutover";-import { credit, debit, equals, round, toStoredAmount } from "@carbon/utils";import {- type CalendarDate,+ credit,+ debit,+ equals,+ type PeriodPostingSource,+ round,+ toStoredAmount+} from "@carbon/utils";+import {+ CalendarDate,endOfMonth,parseDate,startOfMonth,@@ -1130,3 +1137,96 @@ function isCalendarDateString(value: string): boolean {// lock/unlock instead of a generic "Mark Done". Identified by name (a stable,// non-deletable system definition).export const LOCK_PERIOD_TASK_NAME = "Lock the period";++/** The companies a financial report covers: every company for "all", the one+ * named, else the user's own. Null when the selection is empty or names a+ * company outside the group, so a report never reads another group's ledger. */+export function selectReportCompanyIds(+ companiesParam: string | null,+ groupCompanyIds: string[],+ companyId: string+): string[] | null {+ const selected =+ companiesParam === "all"+ ? groupCompanyIds+ : companiesParam+ ? [companiesParam]+ : [companyId];+ if (+ selected.length === 0 ||+ selected.some((id) => !groupCompanyIds.includes(id))+ ) {+ return null;+ }+ return selected;+}++/** A Superseded journal is a Provisional one the opening journal replaced at+ * the cutover. The journal list hides it unless a status filter asks for it. */+export function hidesSupersededJournals(args: {+ status: string | null;+ filters?: { column: string; value?: unknown }[];+}): boolean {+ return !(+ Boolean(args.status) ||+ (args.filters ?? []).some(+ (filter) => filter.column === "status" && Boolean(filter.value)+ )+ );+}++/** Why a posting dated in a period is refused, or null when it may post. A+ * Closed period takes nothing; a Locked one takes accounting adjustments but+ * not operational postings. */+export function periodPostingRefusal(+ closeStatus: string,+ source: PeriodPostingSource+): string | null {+ if (closeStatus === "Closed") {+ return "Accounting period is closed. Reopen it before posting.";+ }+ if (closeStatus === "Locked" && source === "operational") {+ return "Accounting period is locked. Post as an accounting adjustment or unlock the period first.";+ }+ return null;+}++/** Why a period cannot be deleted, or null: only an Open period with no+ * journals posted to it can go. */+export function periodDeletionRefusal(+ closeStatus: string,+ journalCount: number+): string | null {+ if (closeStatus !== "Open") {+ return `Only open periods can be deleted — this period is ${closeStatus}.`;+ }+ if (journalCount > 0) {+ return `This period has ${journalCount} journal ${+ journalCount === 1 ? "entry" : "entries"+ } posted to it and cannot be deleted.`;+ }+ return null;+}++/** The months of a fiscal year not yet created. A fiscal year is named by+ * its ending calendar year, so a non-January start begins the year before. */+export function fiscalYearPeriodDates(+ fiscalYear: number,+ startMonth: number,+ existingPeriodNumbers: Set<number | null>+): { periodNumber: number; startDate: string; endDate: string }[] {+ const firstYear = startMonth === 1 ? fiscalYear : fiscalYear - 1;+ const rows = [];+ for (let p = 1; p <= 12; p++) {+ if (existingPeriodNumbers.has(p)) continue;+ const start = new CalendarDate(firstYear, startMonth, 1).add({+ months: p - 1+ });+ rows.push({+ periodNumber: p,+ startDate: start.toString(),+ endDate: endOfMonth(start).toString()+ });+ }+ return rows;+}diff --git a/apps/erp/app/modules/accounting/ui/Reports/pivotData.test.ts b/apps/erp/app/modules/accounting/ui/Reports/pivotData.test.tsindex 09aaef9108..6b0ee40417 100644--- a/apps/erp/app/modules/accounting/ui/Reports/pivotData.test.ts+++ b/apps/erp/app/modules/accounting/ui/Reports/pivotData.test.ts@@ -25,428 +25,239 @@ function group(return { rowValue1Id, rowValue2Id, columnKey, amount, quantity, lineCount };}-const VALUE_NAMES: Record<string, string> = {- a: "Alpha",- b: "Beta",- x: "X-Ray",- y: "Yankee"-};+type BuildArgs = Parameters<typeof buildPivotTree>[0];++function build(groups: PivotGroupRow[], overrides: Partial<BuildArgs> = {}) {+ return buildPivotTree({+ groups,+ valueNames: { a: "Alpha", b: "Beta", x: "X-Ray", y: "Yankee", z: "Zulu" },+ columnKeys: ["c1", "c2"],+ rowCount: 1,+ measure: "amount",+ ...overrides+ });+}++const cell = (amount: number, quantity: number, lineCount: number) => ({+ amount,+ quantity,+ lineCount+});describe("buildPivotTree", () => {- it("1-dim rows: sorts by ABS(measure) desc, Unassigned last, totals correct", () => {- const groups = [+ it("sorts one-dimension rows by ABS(measure) desc with Unassigned last", () => {+ const result = build([group("a", null, "c1", 100, 5, 2),group("a", null, "c2", 50, 1, 1),group("b", null, "c1", -400, 2, 3),group("b", null, "c2", 100, 0, 1),- // Unassigned row has the biggest ABS total but must still sort last.+ // The biggest ABS total, but Unassigned still sorts last.group(null, null, "c1", 900, 9, 4)- ];-- const result = buildPivotTree({- groups,- valueNames: VALUE_NAMES,- columnKeys: ["c1", "c2"],- rowCount: 1,- measure: "amount"- });+ ]);- expect(result.flatTree).toHaveLength(3);+ expect(result.columnsTruncated).toBe(false);+ expect(result.columnKeys).toEqual(["c1", "c2"]);+ // Beta |−300| before Alpha |150|.expect(result.flatTree.map((n) => n.data.label)).toEqual([- "Beta", // ABS(-300) > ABS(150)+ "Beta","Alpha","Unassigned"]);- expect(result.columnsTruncated).toBe(false);- expect(result.columnKeys).toEqual(["c1", "c2"]);-- const beta = result.flatTree[0];- expect(beta?.id).toBe("b");- expect(beta?.parentId).toBeUndefined();- expect(beta?.level).toBe(0);- expect(beta?.hasChildren).toBe(false);- expect(beta?.children).toEqual([]);- expect(beta?.data.rowValue1Id).toBe("b");- expect(beta?.data.rowValue2Id).toBeNull();- expect(beta?.data.isUnassigned).toBe(false);- expect(beta?.data.total).toEqual({- amount: -300,- quantity: 2,- lineCount: 4+ expect(result.flatTree[0]).toMatchObject({+ id: "b",+ parentId: undefined,+ level: 0,+ hasChildren: false,+ children: [],+ data: {+ rowValue1Id: "b",+ rowValue2Id: null,+ isUnassigned: false,+ total: cell(-300, 2, 4),+ cells: { c1: cell(-400, 2, 3), c2: cell(100, 0, 1) }+ }});- expect(beta?.data.cells["c1"]).toEqual({- amount: -400,- quantity: 2,- lineCount: 3+ expect(result.flatTree[2]?.data).toMatchObject({+ isUnassigned: true,+ rowValue1Id: null,+ total: { amount: 900 }});- expect(beta?.data.cells["c2"]).toEqual({- amount: 100,- quantity: 0,- lineCount: 1- });-- const unassigned = result.flatTree[2];- expect(unassigned?.data.isUnassigned).toBe(true);- expect(unassigned?.data.rowValue1Id).toBeNull();- expect(unassigned?.data.total.amount).toBe(900);});- it("falls back to the raw id when a valueNames entry is missing", () => {- const result = buildPivotTree({- groups: [group("mystery", null, "c1", 10)],- valueNames: {},- columnKeys: ["c1"],- rowCount: 1,- measure: "amount"- });- expect(result.flatTree[0]?.data.label).toBe("mystery");+ it("labels a row by its raw id when valueNames has no entry", () => {+ expect(+ build([group("mystery", null, "c1", 10)]).flatTree[0]?.data.label+ ).toBe("mystery");});- it("2-dim nesting: parent subtotals equal sum of children; levels and parentId wired", () => {- const groups = [- group("a", "x", "c1", 100, 2, 1),- group("a", "x", "c2", 50, 1, 1),- group("a", "y", "c1", 300, 3, 2),- group("a", null, "c1", 25, 0, 1), // Unassigned child under Alpha- group("b", "x", "c1", 10, 1, 1)- ];-- const result = buildPivotTree({- groups,- valueNames: VALUE_NAMES,- columnKeys: ["c1", "c2"],- rowCount: 2,- measure: "amount"- });+ it("nests two dimensions with parent subtotals over their children", () => {+ const result = build(+ [+ group("a", "x", "c1", 100, 2, 1),+ group("a", "x", "c2", 50, 1, 1),+ group("a", "y", "c1", 300, 3, 2),+ group("a", null, "c1", 25, 0, 1),+ group("b", "x", "c1", 10, 1, 1)+ ],+ { rowCount: 2 }+ );- // Alpha (475) before Beta (10); Alpha's children: Yankee (300), X-Ray (150),- // Unassigned (25, last regardless of size).- expect(result.flatTree.map((n) => n.id)).toEqual([- "a",- "a|y",- "a|x",- "a|__unassigned__",- "b",- "b|x"+ // Alpha 475 before Beta 10; Alpha's children Yankee 300, X-Ray 150, then+ // Unassigned 25 last regardless of size.+ expect(result.flatTree.map((n) => [n.id, n.parentId, n.level])).toEqual([+ ["a", undefined, 0],+ ["a|y", "a", 1],+ ["a|x", "a", 1],+ ["a|__unassigned__", "a", 1],+ ["b", undefined, 0],+ ["b|x", "b", 1]]);-- const alpha = result.flatTree[0];- expect(alpha?.level).toBe(0);- expect(alpha?.parentId).toBeUndefined();- expect(alpha?.hasChildren).toBe(true);- expect(alpha?.children).toEqual(["a|y", "a|x", "a|__unassigned__"]);- expect(alpha?.data.rowValue1Id).toBe("a");- expect(alpha?.data.rowValue2Id).toBeNull();-- const alphaChildren = result.flatTree.filter((n) => n.parentId === "a");- expect(alphaChildren).toHaveLength(3);- for (const child of alphaChildren) {- expect(child.level).toBe(1);- expect(child.hasChildren).toBe(false);- expect(child.data.rowValue1Id).toBe("a");- }-- // Parent totals aggregate children.- const childTotalSum = alphaChildren.reduce(- (sum, child) => sum + child.data.total.amount,- 0- );- expect(alpha?.data.total.amount).toBe(childTotalSum);- expect(alpha?.data.total).toEqual({- amount: 475,- quantity: 6,- lineCount: 5+ expect(result.flatTree[0]).toMatchObject({+ hasChildren: true,+ children: ["a|y", "a|x", "a|__unassigned__"],+ data: {+ rowValue1Id: "a",+ rowValue2Id: null,+ total: cell(475, 6, 5),+ cells: { c1: { amount: 425 }, c2: { amount: 50 } }+ }+ });+ expect(result.flatTree[3]?.data).toMatchObject({+ rowValue1Id: "a",+ rowValue2Id: null,+ isUnassigned: true});-- // Parent cells aggregate children's cells per column.- const childC1Sum = alphaChildren.reduce(- (sum, child) => sum + (child.data.cells["c1"]?.amount ?? 0),- 0- );- expect(alpha?.data.cells["c1"]?.amount).toBe(childC1Sum);- expect(alpha?.data.cells["c1"]?.amount).toBe(425);- expect(alpha?.data.cells["c2"]?.amount).toBe(50);-- // Unassigned leaf: rowValue2Id null, flagged.- const unassignedLeaf = result.flatTree.find(- (n) => n.id === "a|__unassigned__"- );- expect(unassignedLeaf?.data.rowValue2Id).toBeNull();- expect(unassignedLeaf?.data.isUnassigned).toBe(true);});- it("column totals and grand total are consistent with the input", () => {- const groups = [- group("a", null, "c1", 100, 2, 1),- group("b", null, "c1", -40, 1, 2),- group("a", null, "c2", 60, 3, 1),- group(null, null, null, 5, 1, 1) // null columnKey → UNASSIGNED_COLUMN_KEY- ];-- const result = buildPivotTree({- groups,- valueNames: VALUE_NAMES,- columnKeys: ["c1", "c2", UNASSIGNED_COLUMN_KEY],- rowCount: 1,- measure: "amount"- });+ it("totals each column, including the Unassigned column, and the grand total", () => {+ const result = build(+ [+ group("a", null, "c1", 100, 2, 1),+ group("b", null, "c1", -40, 1, 2),+ group("a", null, "c2", 60, 3, 1),+ group(null, null, null, 5, 1, 1)+ ],+ { columnKeys: ["c1", "c2", UNASSIGNED_COLUMN_KEY] }+ );- expect(result.columnTotals["c1"]).toEqual({- amount: 60,- quantity: 3,- lineCount: 3+ expect(result.columnTotals).toEqual({+ c1: cell(60, 3, 3),+ c2: cell(60, 3, 1),+ [UNASSIGNED_COLUMN_KEY]: cell(5, 1, 1)});- expect(result.columnTotals["c2"]).toEqual({- amount: 60,- quantity: 3,- lineCount: 1- });- expect(result.columnTotals[UNASSIGNED_COLUMN_KEY]).toEqual({- amount: 5,- quantity: 1,- lineCount: 1- });- expect(result.grandTotal).toEqual({- amount: 125,- quantity: 7,- lineCount: 5- });-- // Grand total equals the sum of all column totals (nothing hidden here).- const columnSum = Object.values(result.columnTotals).reduce(- (sum, cell) => sum + cell.amount,- 0- );- expect(columnSum).toBe(result.grandTotal.amount);+ expect(result.grandTotal).toEqual(cell(125, 7, 5));});- it("rowCount 0: a single total row spanning all data", () => {+ it("collapses to a single labelled total row when no row dimension is chosen", () => {const groups = [group("a", null, "c1", 100, 2, 1),group("b", null, "c2", 50, 1, 1)];-- const result = buildPivotTree({- groups,- valueNames: VALUE_NAMES,- columnKeys: ["c1", "c2"],- rowCount: 0,- measure: "amount"- });+ const result = build(groups, { rowCount: 0 });expect(result.flatTree).toHaveLength(1);- const totalNode = result.flatTree[0];- expect(totalNode?.id).toBe("total");- expect(totalNode?.data.key).toBe("total");- expect(totalNode?.data.label).toBe("Total");- expect(totalNode?.level).toBe(0);- expect(totalNode?.parentId).toBeUndefined();- expect(totalNode?.hasChildren).toBe(false);- expect(totalNode?.data.isUnassigned).toBe(false);- expect(totalNode?.data.total).toEqual({- amount: 150,- quantity: 3,- lineCount: 2- });- expect(totalNode?.data.cells["c1"]?.amount).toBe(100);- expect(totalNode?.data.cells["c2"]?.amount).toBe(50);-- // Localized total label is honored.- const localized = buildPivotTree({- groups,- valueNames: VALUE_NAMES,- columnKeys: ["c1", "c2"],- rowCount: 0,- measure: "amount",- totalLabel: "Gesamt"+ expect(result.flatTree[0]).toMatchObject({+ id: "total",+ level: 0,+ parentId: undefined,+ hasChildren: false,+ data: {+ key: "total",+ label: "Total",+ isUnassigned: false,+ total: cell(150, 3, 2),+ cells: { c1: { amount: 100 }, c2: { amount: 50 } }+ }});- expect(localized.flatTree[0]?.data.label).toBe("Gesamt");+ expect(+ build(groups, { rowCount: 0, totalLabel: "Gesamt" }).flatTree[0]?.data+ .label+ ).toBe("Gesamt");});- it("honors a localized unassignedLabel", () => {- const result = buildPivotTree({- groups: [group(null, null, "c1", 10)],- valueNames: {},- columnKeys: ["c1"],- rowCount: 1,- measure: "amount",- unassignedLabel: "Nicht zugewiesen"- });- expect(result.flatTree[0]?.data.label).toBe("Nicht zugewiesen");- expect(result.flatTree[0]?.data.isUnassigned).toBe(true);+ it("uses the caller's localized Unassigned label", () => {+ expect(+ build([group(null, null, "c1", 10)], {+ unassignedLabel: "Nicht zugewiesen"+ }).flatTree[0]?.data.label+ ).toBe("Nicht zugewiesen");});- it("truncates columns to top-N by ABS(measure), always keeping Unassigned; totals stay truthful", () => {- const groups = [- group("a", null, "c1", 1000, 1, 1),- group("a", null, "c2", 10, 1, 1),- group("a", null, "c3", -500, 1, 1),- group("a", null, null, 1, 1, 1) // Unassigned column, tiny total- ];-- const result = buildPivotTree({- groups,- valueNames: VALUE_NAMES,- columnKeys: ["c1", "c2", "c3", UNASSIGNED_COLUMN_KEY],- rowCount: 1,- measure: "amount",- maxColumns: 2- });+ it("keeps the top columns by ABS(measure) plus Unassigned, with totals over all data", () => {+ const result = build(+ [+ group("a", null, "c1", 1000, 1, 1),+ group("a", null, "c2", 10, 1, 1),+ group("a", null, "c3", -500, 1, 1),+ group("a", null, null, 1, 1, 1)+ ],+ { columnKeys: ["c1", "c2", "c3", UNASSIGNED_COLUMN_KEY], maxColumns: 2 }+ );expect(result.columnsTruncated).toBe(true);- // Top non-unassigned column by ABS is c1 (1000 > 500 > 10); Unassigned is- // always kept even though its total is the smallest.+ // c1 is the top column by ABS; Unassigned stays though it is the smallest.expect(result.columnKeys).toEqual(["c1", UNASSIGNED_COLUMN_KEY]);-- const alpha = result.flatTree[0];- // Hidden columns are excluded from visible cells...- expect(alpha?.data.cells["c2"]).toBeUndefined();- expect(alpha?.data.cells["c3"]).toBeUndefined();- expect(alpha?.data.cells["c1"]?.amount).toBe(1000);- expect(alpha?.data.cells[UNASSIGNED_COLUMN_KEY]?.amount).toBe(1);- // ...but row totals, column totals, and the grand total include ALL data.- expect(alpha?.data.total.amount).toBe(511);+ expect(Object.keys(result.flatTree[0]?.data.cells ?? {})).toEqual([+ "c1",+ UNASSIGNED_COLUMN_KEY+ ]);+ // Hidden columns still count: 1000 + 10 − 500 + 1.+ expect(result.flatTree[0]?.data.total.amount).toBe(511);expect(result.grandTotal.amount).toBe(511);- expect(result.columnTotals["c2"]?.amount).toBe(10);- expect(result.columnTotals["c3"]?.amount).toBe(-500);+ expect(result.columnTotals.c3?.amount).toBe(-500);});- it("truncates by the chosen measure, not always amount", () => {- const groups = [- group("a", null, "c1", 1000, 1, 1), // big amount, small quantity- group("a", null, "c2", 10, 900, 1) // small amount, big quantity- ];-- const result = buildPivotTree({- groups,- valueNames: VALUE_NAMES,- columnKeys: ["c1", "c2"],- rowCount: 1,- measure: "quantity",- maxColumns: 1- });-- expect(result.columnsTruncated).toBe(true);+ it("ranks columns for truncation by the chosen measure", () => {+ const result = build(+ [group("a", null, "c1", 1000, 1, 1), group("a", null, "c2", 10, 900, 1)],+ { measure: "quantity", maxColumns: 1 }+ );expect(result.columnKeys).toEqual(["c2"]);});it("does not cap columns when maxColumns is omitted", () => {const columnKeys = Array.from({ length: 120 }, (_, i) => `c${i}`);- const groups = columnKeys.map((key, i) => group("a", null, key, i + 1));-- const result = buildPivotTree({- groups,- valueNames: VALUE_NAMES,- columnKeys,- rowCount: 1,- measure: "amount"- });-+ const result = build(+ columnKeys.map((key, i) => group("a", null, key, i + 1)),+ { columnKeys }+ );expect(result.columnsTruncated).toBe(false);expect(result.columnKeys).toEqual(columnKeys);});- it("sorts rows by a specific column, ascending and descending (signed)", () => {- const groups = [- group("a", null, "c1", 100),- group("b", null, "c1", -300),- group("c", null, "c1", 200)- ];-- const desc = buildPivotTree({- groups,- valueNames: VALUE_NAMES,- columnKeys: ["c1"],- rowCount: 1,- measure: "amount",- sort: { key: "c1", direction: "desc" }- });- // Signed, not ABS: 200 > 100 > -300.- expect(desc.flatTree.map((n) => n.data.rowValue1Id)).toEqual([- "c",- "a",- "b"- ]);-- const asc = buildPivotTree({- groups,- valueNames: VALUE_NAMES,- columnKeys: ["c1"],- rowCount: 1,- measure: "amount",- sort: { key: "c1", direction: "asc" }- });- expect(asc.flatTree.map((n) => n.data.rowValue1Id)).toEqual([- "b",- "a",- "c"- ]);- });-- it("sorts by total and keeps Unassigned last even under an explicit sort", () => {- const groups = [- group("a", null, "c1", 100),- group("b", null, "c1", 300),- group(null, null, "c1", 999) // Unassigned biggest, must still sort last- ];-- const result = buildPivotTree({- groups,- valueNames: VALUE_NAMES,- columnKeys: ["c1"],- rowCount: 1,- measure: "amount",- sort: { key: TOTAL_SORT_KEY, direction: "asc" }- });-+ it.each([+ // A column sort is signed, not ABS.+ ["c1", "desc", ["Zulu", "Alpha", "Beta"]],+ ["c1", "asc", ["Beta", "Alpha", "Zulu"]],+ [LABEL_SORT_KEY, "asc", ["Alpha", "Beta", "Zulu"]],+ [LABEL_SORT_KEY, "desc", ["Zulu", "Beta", "Alpha"]],+ [TOTAL_SORT_KEY, "asc", ["Beta", "Alpha", "Zulu"]]+ ] as const)("sorts rows by %s %s", (key, direction, labels) => {+ const result = build(+ [+ group("a", null, "c1", 100),+ group("b", null, "c1", -300),+ group("z", null, "c1", 200),+ group(null, null, "c1", 999)+ ],+ { columnKeys: ["c1"], sort: { key, direction } }+ );+ // Unassigned stays last under every explicit sort.expect(result.flatTree.map((n) => n.data.label)).toEqual([- "Alpha",- "Beta",+ ...labels,"Unassigned"]);});- it("sorts by row label alphabetically", () => {- const groups = [group("b", null, "c1", 100), group("a", null, "c1", 100)];-- const asc = buildPivotTree({- groups,- valueNames: VALUE_NAMES,- columnKeys: ["c1"],- rowCount: 1,- measure: "amount",- sort: { key: LABEL_SORT_KEY, direction: "asc" }- });- expect(asc.flatTree.map((n) => n.data.label)).toEqual(["Alpha", "Beta"]);-- const desc = buildPivotTree({- groups,- valueNames: VALUE_NAMES,- columnKeys: ["c1"],- rowCount: 1,- measure: "amount",- sort: { key: LABEL_SORT_KEY, direction: "desc" }- });- expect(desc.flatTree.map((n) => n.data.label)).toEqual(["Beta", "Alpha"]);- });-- it("applies the column sort within a nested level too", () => {- const groups = [- group("a", "x", "c1", 100),- group("a", "y", "c1", 300),- group("a", "z", "c1", 200)- ];-- const result = buildPivotTree({- groups,- valueNames: { ...VALUE_NAMES, z: "Zulu" },- columnKeys: ["c1"],- rowCount: 2,- measure: "amount",- sort: { key: "c1", direction: "asc" }- });-- // Children of Alpha ordered by c1 ascending: x(100), z(200), y(300).+ it("applies the sort within a nested level", () => {+ const result = build(+ [+ group("a", "x", "c1", 100),+ group("a", "y", "c1", 300),+ group("a", "z", "c1", 200)+ ],+ { columnKeys: ["c1"], rowCount: 2, sort: { key: "c1", direction: "asc" } }+ );expect(result.flatTree.filter((n) => n.parentId === "a")@@ -456,82 +267,71 @@ describe("buildPivotTree", () => {});describe("applyPercentOfTotal", () => {- it("sums to ~100 per column and yields 0s for a zero-total column", () => {- const groups = [- group("a", null, "c1", 25, 0, 1),- group("b", null, "c1", 75, 0, 1),- // c0 nets to zero: both rows must read 0%.- group("a", null, "c0", 100, 0, 1),- group("b", null, "c0", -100, 0, 1)- ];-- const result = buildPivotTree({- groups,- valueNames: VALUE_NAMES,- columnKeys: ["c1", "c0"],- rowCount: 1,- measure: "amount"- });-- let c1Sum = 0;- for (const node of result.flatTree) {- const percents = applyPercentOfTotal(- node.data.cells,- result.columnTotals,- "amount"- );- c1Sum += percents["c1"] ?? 0;- expect(percents["c0"]).toBe(0);- }- expect(Math.abs(c1Sum - 100)).toBeLessThan(1e-6);+ it("splits a column 25/75 and reads 0% in a column that nets to zero", () => {+ const result = build(+ [+ group("a", null, "c1", 25),+ group("b", null, "c1", 75),+ group("a", null, "c0", 100),+ group("b", null, "c0", -100)+ ],+ { columnKeys: ["c1", "c0"] }+ );+ expect(+ result.flatTree.map((node) =>+ applyPercentOfTotal(node.data.cells, result.columnTotals, "amount")+ )+ ).toEqual([+ { c1: 25, c0: 0 },+ { c1: 75, c0: 0 }+ ]);});- it("uses the chosen measure (count maps to lineCount)", () => {- const cells = { c1: { amount: 0, quantity: 0, lineCount: 3 } };- const columnTotals = { c1: { amount: 0, quantity: 0, lineCount: 12 } };- const percents = applyPercentOfTotal(cells, columnTotals, "count");- expect(percents["c1"]).toBe(25);+ it("measures count as lineCount", () => {+ expect(+ applyPercentOfTotal(+ { c1: cell(0, 0, 3) },+ { c1: cell(0, 0, 12) },+ "count"+ )+ ).toEqual({ c1: 25 });});});-describe("getPivotMeasureValue", () => {- it("maps each measure and treats a missing cell as 0", () => {- const cell = { amount: 1, quantity: 2, lineCount: 3 };- expect(getPivotMeasureValue(cell, "amount")).toBe(1);- expect(getPivotMeasureValue(cell, "quantity")).toBe(2);- expect(getPivotMeasureValue(cell, "count")).toBe(3);- expect(getPivotMeasureValue(undefined, "amount")).toBe(0);- });+it.each([+ ["amount", 1],+ ["quantity", 2],+ ["count", 3]+] as const)("getPivotMeasureValue reads %s", (measure, expected) => {+ expect(getPivotMeasureValue(cell(1, 2, 3), measure)).toBe(expected);+ expect(getPivotMeasureValue(undefined, measure)).toBe(0);});describe("pivotToCsvRows", () => {- it("matches the rendered tree: header, indentation, and totals row", () => {- const groups = [- group("a", "x", "c1", 100, 0, 1),- group("a", "y", "c1", 300, 0, 1),- group("a", "x", "c2", 50, 0, 1),- group(null, null, "c1", 5, 0, 1)- ];-- const built = buildPivotTree({- groups,- valueNames: VALUE_NAMES,- columnKeys: ["c1", "c2"],- rowCount: 2,- measure: "amount"- });-- const csv = pivotToCsvRows({+ const csv = (+ built: ReturnType<typeof build>,+ columnLabels: Record<string, string>+ ) =>+ pivotToCsvRows({flatTree: built.flatTree,columnKeys: built.columnKeys,columnTotals: built.columnTotals,grandTotal: built.grandTotal,measure: "amount",- columnLabels: { c1: "Jan 2026", c2: "Feb 2026" }+ columnLabels});- // header + 5 tree nodes (Alpha, 2 children, Unassigned parent + child) + totals- expect(csv).toEqual([+ it("writes the rendered tree with a header, indented children and a totals row", () => {+ const built = build(+ [+ group("a", "x", "c1", 100),+ group("a", "y", "c1", 300),+ group("a", "x", "c2", 50),+ group(null, null, "c1", 5)+ ],+ { rowCount: 2 }+ );+ expect(csv(built, { c1: "Jan 2026", c2: "Feb 2026" })).toEqual([["", "Jan 2026", "Feb 2026", "Total"],["Alpha", "400", "50", "450"],[" Yankee", "300", "0", "300"],@@ -542,25 +342,12 @@ describe("pivotToCsvRows", () => {]);});- it("falls back to the raw column key when a label is missing", () => {- const built = buildPivotTree({- groups: [group("a", null, "c1", 10, 0, 1)],- valueNames: VALUE_NAMES,- columnKeys: ["c1"],- rowCount: 1,- measure: "amount"- });-- const csv = pivotToCsvRows({- flatTree: built.flatTree,- columnKeys: built.columnKeys,- columnTotals: built.columnTotals,- grandTotal: built.grandTotal,- measure: "amount",- columnLabels: {}- });-- expect(csv[0]).toEqual(["", "c1", "Total"]);- expect(csv[csv.length - 1]).toEqual(["Total", "10", "10"]);+ it("heads a column by its raw key when it has no label", () => {+ const built = build([group("a", null, "c1", 10)], { columnKeys: ["c1"] });+ expect(csv(built, {})).toEqual([+ ["", "c1", "Total"],+ ["Alpha", "10", "10"],+ ["Total", "10", "10"]+ ]);});});diff --git a/apps/erp/app/modules/agent/agent.prompt.test.ts b/apps/erp/app/modules/agent/agent.prompt.test.tsindex f53d40f5d1..9ed72ccc73 100644--- a/apps/erp/app/modules/agent/agent.prompt.test.ts+++ b/apps/erp/app/modules/agent/agent.prompt.test.ts@@ -2,47 +2,11 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { describe, expect, it } from "vitest";+import { expect, it } from "vitest";import { buildSystemPrompt } from "./agent.prompt";-const prompt = buildSystemPrompt({ today: "2026-09-30" });--describe("agent system prompt", () => {- it("gives the model the company's date, not the server's", () => {- expect(prompt).toContain("Today's date is 2026-09-30.");- });-- // The agent is a Carbon assistant, not a general chatbot. Without an explicit- // scope section the model answers arithmetic, writes Python, etc. — it has the- // capability, and nothing else in the prompt tells it not to.- it("declares Carbon-only scope", () => {- expect(prompt).toContain("SCOPE — CARBON ONLY");- expect(prompt).toContain("NOT a general-purpose");- });-- it("names the out-of-scope categories that regressed", () => {- // The two the user actually hit: a math question and "write me a Python program".- expect(prompt).toMatch(/math, arithmetic, calculations/);- expect(prompt).toMatch(/writing, explaining, reviewing or debugging code/);- });-- it("tells the model how to decline instead of only that it must", () => {- expect(prompt).toContain("HOW TO DECLINE");- // A refusal with no alternative reads as a dead end.- expect(prompt).toContain(- "offer\na concrete Carbon-related thing you CAN do"- );- });-- it("holds the scope against insistence and Carbon-framed smuggling", () => {- expect(prompt).toContain("the scope does\nnot change");- expect(prompt).toContain("write a Python script to call Carbon's API");- });-- it("keeps Carbon-adjacent questions answerable", () => {- // Over-refusing is the failure mode on the other side: ERP/manufacturing- // concept questions are the agent's whole job.- expect(prompt).toContain("manufacturing/ERP/MES/QMS domain concepts");- expect(prompt).toContain("answer the Carbon half and decline the rest");- });+it("gives the model the company's date, not the server's", () => {+ expect(buildSystemPrompt({ today: "2026-09-30" })).toContain(+ "Today's date is 2026-09-30."+ );});diff --git a/apps/erp/app/modules/inventory/inventory.models.test.ts b/apps/erp/app/modules/inventory/inventory.models.test.tsindex 4ceb2f3cdb..fe3ea692ae 100644--- a/apps/erp/app/modules/inventory/inventory.models.test.ts+++ b/apps/erp/app/modules/inventory/inventory.models.test.ts@@ -10,43 +10,9 @@ import {receiptFixedAssetLineUpdateValidator,reconcileReceiptLineSerials,resolveStockTransferPickForward,- shipmentFixedAssetLineUpdateValidator,- storageTypeValidator,- storageUnitValidator+ shipmentFixedAssetLineUpdateValidator} from "./inventory.models";-describe("storageTypeValidator", () => {- it("trims surrounding whitespace from the name", () => {- const r = storageTypeValidator.safeParse({ name: " Pallet " });- expect(r.success).toBe(true);- if (r.success) expect(r.data.name).toBe("Pallet");- });-- it("rejects a name that is only whitespace", () => {- const r = storageTypeValidator.safeParse({ name: " " });- expect(r.success).toBe(false);- });-});--describe("storageUnitValidator", () => {- it("trims surrounding whitespace from the name", () => {- const r = storageUnitValidator.safeParse({- name: "Rack A1 ",- locationId: "loc1"- });- expect(r.success).toBe(true);- if (r.success) expect(r.data.name).toBe("Rack A1");- });-- it("rejects a name that is only whitespace", () => {- const r = storageUnitValidator.safeParse({- name: " ",- locationId: "loc1"- });- expect(r.success).toBe(false);- });-});-describe("resolveStockTransferPickForward", () => {const base = {lineQuantity: 10,@@ -119,65 +85,25 @@ describe("resolveStockTransferPickForward", () => {});});-describe("shipmentFixedAssetLineUpdateValidator", () => {- it("rejects a negative meter reading", () => {- const r = shipmentFixedAssetLineUpdateValidator.safeParse({- id: "sfal1",- field: "meter",- value: "-1"- });- expect(r.success).toBe(false);- });-- it("accepts an empty or a positive meter reading", () => {- for (const value of ["", "120"]) {- const r = shipmentFixedAssetLineUpdateValidator.safeParse({- id: "sfal1",- field: "meter",- value- });- expect(r.success).toBe(true);- }- });-- it("rejects an unknown field", () => {- const r = shipmentFixedAssetLineUpdateValidator.safeParse({- id: "sfal1",- field: "notes",- value: "scratched"- });- expect(r.success).toBe(false);- });-});--describe("receiptFixedAssetLineUpdateValidator", () => {- it("rejects a negative meter reading", () => {- const r = receiptFixedAssetLineUpdateValidator.safeParse({- id: "rfal1",- field: "meter",- value: "-1"- });- expect(r.success).toBe(false);- });-- it("accepts an empty or a positive meter reading", () => {- for (const value of ["", "120"]) {- const r = receiptFixedAssetLineUpdateValidator.safeParse({- id: "rfal1",- field: "meter",- value- });- expect(r.success).toBe(true);- }+describe.each([+ ["shipment", shipmentFixedAssetLineUpdateValidator, "received"],+ ["receipt", receiptFixedAssetLineUpdateValidator, "shipped"]+])("%s fixed-asset line update", (_, validator, foreignField) => {+ it.each([+ ["", true],+ ["120", true],+ ["-1", false]+ ])("meter reading %j accepted: %s", (value, accepted) => {+ expect(+ validator.safeParse({ id: "fal1", field: "meter", value }).success+ ).toBe(accepted);});- it("rejects an unknown field", () => {- const r = receiptFixedAssetLineUpdateValidator.safeParse({- id: "rfal1",- field: "shipped",- value: "true"- });- expect(r.success).toBe(false);+ it("rejects a field the line does not have", () => {+ expect(+ validator.safeParse({ id: "fal1", field: foreignField, value: "true" })+ .success+ ).toBe(false);});});@@ -246,37 +172,39 @@ describe("planSerialBoxWrite", () => {"Receipt Line Index": index,Receipt: "rec1"});+ type Input = Parameters<typeof planSerialBoxWrite>[0];+ const plan = (overrides: Partial<Input>) =>+ planSerialBoxWrite({+ receiptLineId: "line1",+ index: 0,+ serialNumber: "SN-A",+ box: [],+ withSerial: [],+ ...overrides+ });it("clears the box when the serial is emptied", () => {expect(- planSerialBoxWrite({- receiptLineId: "line1",- index: 0,+ plan({serialNumber: " ",- box: [{ id: "e1", hasHistory: false }],- withSerial: []+ box: [{ id: "e1", hasHistory: false }]})).toEqual({ kind: "clear", releaseIds: ["e1"] });});it("renames the box's own entity when the serial is edited", () => {expect(- planSerialBoxWrite({- receiptLineId: "line1",- index: 0,+ plan({serialNumber: "NEW",- box: [{ id: "e1", hasHistory: false }],- withSerial: []+ box: [{ id: "e1", hasHistory: false }]})).toEqual({ kind: "write", targetId: "e1", releaseIds: [] });});it("refuses a serial held by another box and empties this one", () => {expect(- planSerialBoxWrite({- receiptLineId: "line1",+ plan({index: 1,- serialNumber: "SN-A",box: [{ id: "e2", hasHistory: false }],withSerial: [{ id: "e1", hasHistory: false, attributes: box("line1", 0) }@@ -287,24 +215,17 @@ describe("planSerialBoxWrite", () => {it("refuses a serial held by a box on another receipt line", () => {expect(- planSerialBoxWrite({- receiptLineId: "line1",- index: 0,- serialNumber: "SN-A",- box: [],+ plan({withSerial: [{ id: "e9", hasHistory: false, attributes: box("line2", 0) }]- }).kind- ).toBe("taken");+ })+ ).toEqual({ kind: "taken", reason: "box", releaseIds: [] });});it("keeps one copy when a racing save left two in the box", () => {expect(- planSerialBoxWrite({- receiptLineId: "line1",- index: 0,- serialNumber: "SN-A",+ plan({box: [{ id: "e1", hasHistory: false },{ id: "e2", hasHistory: false }@@ -319,21 +240,16 @@ describe("planSerialBoxWrite", () => {it("never renames a box entity that has stock history", () => {expect(- planSerialBoxWrite({- receiptLineId: "line1",- index: 0,+ plan({serialNumber: "NEW",- box: [{ id: "unit", hasHistory: true }],- withSerial: []+ box: [{ id: "unit", hasHistory: true }]})).toEqual({ kind: "write", targetId: undefined, releaseIds: ["unit"] });});it("refuses the serial of a unit with stock history", () => {expect(- planSerialBoxWrite({- receiptLineId: "line1",- index: 0,+ plan({serialNumber: "SN-B",box: [{ id: "e1", hasHistory: false }],withSerial: [@@ -345,9 +261,7 @@ describe("planSerialBoxWrite", () => {it("refuses a unit with stock history even when it already sits in the box", () => {expect(- planSerialBoxWrite({- receiptLineId: "line1",- index: 0,+ plan({serialNumber: "SN-B",box: [{ id: "shipped", hasHistory: true }],withSerial: [@@ -359,11 +273,7 @@ describe("planSerialBoxWrite", () => {it("takes back the serial of a voided receipt as the same unit", () => {expect(- planSerialBoxWrite({- receiptLineId: "line1",- index: 0,- serialNumber: "SN-A",- box: [],+ plan({withSerial: [{id: "voided",@@ -378,10 +288,7 @@ describe("planSerialBoxWrite", () => {it("refuses the serial of a record no receipt box holds (a job's reserved serial)", () => {expect(- planSerialBoxWrite({- receiptLineId: "line1",- index: 0,- serialNumber: "SN-A",+ plan({box: [{ id: "e1", hasHistory: false }],withSerial: [{ id: "reserved", hasHistory: false, attributes: { Job: "job1" } }@@ -392,11 +299,8 @@ describe("planSerialBoxWrite", () => {it("names a received unit in another box as an existing unit", () => {expect(- planSerialBoxWrite({- receiptLineId: "line1",- index: 0,+ plan({serialNumber: "SN-B",- box: [],withSerial: [{ id: "received", hasHistory: true, attributes: box("line2", 0) }]diff --git a/apps/erp/app/modules/inventory/inventory.plan-post.test.ts b/apps/erp/app/modules/inventory/inventory.plan-post.test.tsindex 5ea72fd5b0..bc018a6d9a 100644--- a/apps/erp/app/modules/inventory/inventory.plan-post.test.ts+++ b/apps/erp/app/modules/inventory/inventory.plan-post.test.ts@@ -8,10 +8,6 @@ import {planInventoryCountPost} from "./inventory.service";-// Unit tests for the pure planning core: the reconciliation delta math-// (`counted - systemQuantity`). The FOR UPDATE lock, status flip, and serial 0/1-// validation are DB-level and exercised in the browser/integration verification.-type Line = PlannableLine & { postedItemLedgerId: string | null };const line = (overrides: Partial<Line>): Line => ({@@ -23,60 +19,29 @@ const line = (overrides: Partial<Line>): Line => ({...overrides});-it("delta = counted - snapshot (positive)", () => {- const { planned } = planInventoryCountPost([- line({ systemQuantity: 8, countedQuantity: 10 })- ]);- expect(planned[0]!.delta).toEqual(2);-});--it("delta is negative when counted is below snapshot", () => {- const { planned } = planInventoryCountPost([- line({ systemQuantity: 5, countedQuantity: 3 })- ]);- expect(planned[0]!.delta).toEqual(-2);-});--it("delta is 0 when counted matches the snapshot", () => {- const { planned } = planInventoryCountPost([- line({ systemQuantity: 7, countedQuantity: 7 })- ]);- expect(planned[0]!.delta).toEqual(0);-});--it("reconciliation posts the reviewed variance, not counted - live", () => {- // Snapshot 10, counter found 8 (−2). A +5 receipt landed since the snapshot;- // the delta must still be −2 (applied on top of the receipt), NOT 8 − 15.- const { planned } = planInventoryCountPost([- line({ systemQuantity: 10, countedQuantity: 8 })- ]);- expect(planned[0]!.delta).toEqual(-2);-});--it("string NUMERIC quantities are coerced", () => {- const { planned } = planInventoryCountPost([- line({ systemQuantity: "8", countedQuantity: "10.5" })- ]);- expect(planned[0]!.delta).toEqual(2.5);-});--it("the full line is preserved on the plan (e.g. postedItemLedgerId)", () => {- const { planned } = planInventoryCountPost([+// The delta is counted − snapshot, never counted − live on-hand: a receipt that+// landed after the snapshot must not be reversed by the count.+it("plans each line's delta as counted minus the snapshot, keeping the line", () => {+ const lines = [+ line({ id: "a", systemQuantity: 5, countedQuantity: 5 }),+ line({ id: "b", systemQuantity: 8, countedQuantity: 10 }),line({+ id: "c",systemQuantity: 12,countedQuantity: 8,postedItemLedgerId: "il_orig"})+ ];+ expect(planInventoryCountPost(lines).planned).toEqual([+ { line: lines[0], delta: 0 },+ { line: lines[1], delta: 2 },+ { line: lines[2], delta: -4 }]);- expect(planned[0]!.delta).toEqual(-4);- expect(planned[0]!.line.postedItemLedgerId).toEqual("il_orig");});-it("plans every line", () => {+it("coerces NUMERIC quantities that arrive as strings", () => {const { planned } = planInventoryCountPost([- line({ id: "a", systemQuantity: 5, countedQuantity: 5 }),- line({ id: "b", systemQuantity: 5, countedQuantity: 9 }),- line({ id: "c", systemQuantity: 5, countedQuantity: 1 })+ line({ systemQuantity: "8", countedQuantity: "10.5" })]);- expect(planned.map((p) => p.delta)).toEqual([0, 4, -4]);+ expect(planned[0]?.delta).toBe(2.5);});diff --git a/apps/erp/app/modules/inventory/inventory.server.ts b/apps/erp/app/modules/inventory/inventory.server.tsindex bc77898af3..6e48e316aa 100644--- a/apps/erp/app/modules/inventory/inventory.server.ts+++ b/apps/erp/app/modules/inventory/inventory.server.ts@@ -2954,16 +2954,7 @@ export const postInventoryCount = defineServiceFn({service.postInventoryCount);if (posted.error) {- const message = getErrorMessage(- posted.error,- "Failed to post inventory count"- );- // The rows to highlight: the count stays Pending.- const invalidLineIds = posted.error.body.invalidLineIds;- if (Array.isArray(invalidLineIds)) {- return { invalidLineIds: invalidLineIds as string[], message };- }- return service.serverFnFailure(ctx, posted.error, message);+ return service.inventoryCountPostingFailure(ctx, posted.error);}return { inventoryCountId };}@@ -3033,16 +3024,12 @@ export const adjustInventory = defineServiceFn({locationId: adjustment.locationId ?? null}];- // The bin surface comes from the type alone: `quantity` is a positive- // magnitude, so its sign cannot say which way stock moves.- const removes =- adjustment.adjustmentType === "Negative Adjmt." ||- adjustment.adjustmentType === "Scrap";const rules = await service.storageRuleViolations(ctx,- adjustment.storageUnitId- ? ["inventoryAdjustment", removes ? "pick" : "place"]- : ["inventoryAdjustment"],+ service.adjustmentRuleSurfaces(+ adjustment.adjustmentType,+ adjustment.storageUnitId+ ),line);const violations = dedupeViolations(rules.violations);@@ -3057,14 +3044,11 @@ export const adjustInventory = defineServiceFn({service.postInventoryAdjustment);if (posted.error) {- // Below 500 the posting refused the adjustment, in words for the person.- return posted.error.status < 500- ? service.serverFnFailure(ctx, posted.error, posted.error.message)- : ctx.error(- "internal",- "Failed to create manual inventory adjustment",- posted.error- );+ return service.postingFailure(+ ctx,+ posted.error,+ "Failed to create manual inventory adjustment"+ );}return { itemLedgerId: posted.data.itemLedger?.id ?? null };}diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex 4b7dff17c2..858bcde03e 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -213,6 +213,7 @@ import type {warehouseTransferValidator} from "./inventory.models";import {+ type inventoryAdjustmentTypes,isPickingListLocked,isStockTransferLocked,isWarehouseTransferLocked,@@ -4933,6 +4934,51 @@ export function serverFnFailure();}+/**+ * A posting's refusal below 500 is written for the person and keeps its+ * message; anything else is ours, behind `message`.+ */+export function postingFailure(+ ctx: ServiceContext,+ error: ServerFnError,+ message: string+): CarbonError {+ return error.status < 500+ ? serverFnFailure(ctx, error, error.message)+ : ctx.error("internal", message, error);+}++/**+ * A count that cannot post names the lines to fix, so the page can mark them;+ * the count stays Pending. Any other failure is an error.+ */+export function inventoryCountPostingFailure(+ ctx: ServiceContext,+ error: ServerFnError+): { invalidLineIds: string[]; message: string } | CarbonError {+ const message = getErrorMessage(error, "Failed to post inventory count");+ const invalidLineIds = error.body.invalidLineIds;+ if (Array.isArray(invalidLineIds)) {+ return { invalidLineIds: invalidLineIds as string[], message };+ }+ return serverFnFailure(ctx, error, message);+}++/**+ * The storage-rule surfaces an adjustment is checked on. `quantity` is a+ * positive magnitude, so the type alone says which way stock moves: a+ * decrease or scrap takes from the bin (`pick`), anything else adds (`place`).+ */+export function adjustmentRuleSurfaces(+ adjustmentType: (typeof inventoryAdjustmentTypes)[number],+ storageUnitId: string | undefined+): RuleSurface[] {+ if (!storageUnitId) return ["inventoryAdjustment"];+ const removes =+ adjustmentType === "Negative Adjmt." || adjustmentType === "Scrap";+ return ["inventoryAdjustment", removes ? "pick" : "place"];+}+/** The caller's default location, from their user defaults. */export async function defaultLocationOf(ctx: ServiceContext) {const defaults = await ctx.asCaller.supabasediff --git a/apps/erp/app/modules/invoicing/invoicing.application-history.test.ts b/apps/erp/app/modules/invoicing/invoicing.application-history.test.tsindex 649d21d5e9..d4c0a8d1b1 100644--- a/apps/erp/app/modules/invoicing/invoicing.application-history.test.ts+++ b/apps/erp/app/modules/invoicing/invoicing.application-history.test.ts@@ -4,20 +4,7 @@import type { Database } from "@carbon/database";import { createClient } from "@supabase/supabase-js";-import { describe, expect, it, vi } from "vitest";--vi.mock("@carbon/content/glossary", () => ({- terms: {},- getEntry: () => null,- lookupEntry: () => null,- hasEntry: () => false,- termSlug: (s: string) => s,- glossaryEntries: () => []-}));--vi.mock("../people/people.service", () => ({}));-vi.mock("../sales/sales.service", () => ({}));-vi.mock("../accounting/accounting.service", () => ({}));+import { describe, expect, it } from "vitest";import {getInvoiceSettlements,diff --git a/apps/erp/app/modules/invoicing/invoicing.models.test.ts b/apps/erp/app/modules/invoicing/invoicing.models.test.tsindex 0c73f5ffc7..f302d081c7 100644--- a/apps/erp/app/modules/invoicing/invoicing.models.test.ts+++ b/apps/erp/app/modules/invoicing/invoicing.models.test.ts@@ -13,302 +13,109 @@ import {} from "./invoicing.models";describe("paymentValidator", () => {- const validReceipt = {- paymentType: "Receipt" as const,- customerId: "cust1",- paymentDate: "2026-05-19",- currencyCode: "USD",- exchangeRate: 1,- totalAmount: 100,- bankAccount: "acc1"- };-- it("accepts a Receipt with a customer", () => {- const r = paymentValidator.safeParse(validReceipt);- expect(r.success).toBe(true);- });-- it("accepts a Disbursement with a supplier", () => {- const r = paymentValidator.safeParse({- ...validReceipt,- paymentType: "Disbursement",- customerId: undefined,- supplierId: "supp1"- });- expect(r.success).toBe(true);- });-- it("accepts a customer refund disbursement", () => {- expect(- paymentValidator.safeParse({- ...validReceipt,- paymentType: "Disbursement"- }).success- ).toBe(true);- });-- it("accepts a supplier refund receipt", () => {- expect(- paymentValidator.safeParse({- ...validReceipt,- customerId: undefined,- supplierId: "supp1"- }).success- ).toBe(true);- });-- it.each(["Receipt", "Disbursement"])(- "rejects ambiguous %s counterparty",- (paymentType) => {- expect(- paymentValidator.safeParse({- ...validReceipt,- paymentType,- supplierId: "supp1"- }).success- ).toBe(false);- }- );-- it("rejects a Receipt missing customer", () => {- const r = paymentValidator.safeParse({- ...validReceipt,- customerId: undefined- });- expect(r.success).toBe(false);- });-- it("rejects a Disbursement missing supplier", () => {- const r = paymentValidator.safeParse({- ...validReceipt,- paymentType: "Disbursement",- customerId: undefined- });- expect(r.success).toBe(false);- });-- it("accepts a zero totalAmount (pure credit-application, no cash)", () => {- const r = paymentValidator.safeParse({- ...validReceipt,- totalAmount: 0- });- expect(r.success).toBe(true);- });-- it("rejects a negative totalAmount", () => {- const r = paymentValidator.safeParse({- ...validReceipt,- totalAmount: -10- });- expect(r.success).toBe(false);- });-- it("rejects a zero exchange rate", () => {- const r = paymentValidator.safeParse({- ...validReceipt,- exchangeRate: 0- });- expect(r.success).toBe(false);- });-- it("accepts a Disbursement with an employee (reimbursement payout)", () => {- const r = paymentValidator.safeParse({- ...validReceipt,- paymentType: "Disbursement",- customerId: undefined,- employeeId: "emp1"- });- expect(r.success).toBe(true);- });-+ const base = (overrides: Record<string, unknown>) =>+ paymentValidator.safeParse({+ paymentType: "Receipt",+ paymentDate: "2026-05-19",+ currencyCode: "USD",+ exchangeRate: 1,+ totalAmount: 100,+ bankAccount: "acc1",+ ...overrides+ });++ // Exactly one party; either direction is legal for a customer or a supplier+ // (refunds), an employee only receives a reimbursement payout.it.each([- ["customer", { customerId: "cust1" }],- ["supplier", { supplierId: "supp1" }]- ])("rejects an employee payee alongside a %s", (_label, other) => {- expect(- paymentValidator.safeParse({- ...validReceipt,- paymentType: "Disbursement",- customerId: undefined,- employeeId: "emp1",- ...other- }).success- ).toBe(false);- });-- it("rejects a payment with no party at all", () => {- expect(- paymentValidator.safeParse({- ...validReceipt,- customerId: undefined- }).success- ).toBe(false);+ ["Receipt", { customerId: "cust1" }, true],+ ["Disbursement", { supplierId: "supp1" }, true],+ ["Disbursement", { customerId: "cust1" }, true],+ ["Receipt", { supplierId: "supp1" }, true],+ ["Disbursement", { employeeId: "emp1" }, true],+ ["Receipt", {}, false],+ ["Disbursement", {}, false],+ ["Receipt", { customerId: "cust1", supplierId: "supp1" }, false],+ ["Disbursement", { customerId: "cust1", supplierId: "supp1" }, false],+ ["Disbursement", { employeeId: "emp1", customerId: "cust1" }, false],+ ["Disbursement", { employeeId: "emp1", supplierId: "supp1" }, false]+ ])("%s with %o parses: %s", (paymentType, parties, success) => {+ expect(base({ paymentType, ...parties }).success).toBe(success);+ });++ it("accepts a zero total (credit application, no cash) and refuses a negative one", () => {+ expect(base({ customerId: "cust1", totalAmount: 0 }).success).toBe(true);+ expect(base({ customerId: "cust1", totalAmount: -10 }).success).toBe(false);});});describe("invoiceSettlementValidator", () => {- const validApp = {- paymentId: "p1",- targetSalesInvoiceId: "si1",- appliedAmount: 50,- discountAmount: 0,- writeOffAmount: 0,- targetExchangeRate: 1,- sourceExchangeRate: 1,- appliedDate: "2026-05-19"- };-- it("accepts an application against a sales invoice", () => {- const r = invoiceSettlementValidator.safeParse(validApp);- expect(r.success).toBe(true);- });-- it("accepts an application against a purchase invoice", () => {- const r = invoiceSettlementValidator.safeParse({- ...validApp,- targetSalesInvoiceId: undefined,- targetPurchaseInvoiceId: "pi1"- });- expect(r.success).toBe(true);- });-- it("rejects when both sales and purchase ids set", () => {- const r = invoiceSettlementValidator.safeParse({- ...validApp,- targetPurchaseInvoiceId: "pi1"- });- expect(r.success).toBe(false);- });-- it("rejects when neither sales nor purchase id set", () => {- const r = invoiceSettlementValidator.safeParse({- ...validApp,- targetSalesInvoiceId: undefined- });- expect(r.success).toBe(false);- });-- it("accepts an application against a reimbursement", () => {- const r = invoiceSettlementValidator.safeParse({- ...validApp,- targetSalesInvoiceId: undefined,- targetReimbursementId: "reimb1"- });- expect(r.success).toBe(true);- });-- it("rejects a reimbursement target alongside an invoice target", () => {- const r = invoiceSettlementValidator.safeParse({- ...validApp,- targetReimbursementId: "reimb1"- });- expect(r.success).toBe(false);- });-- it("rejects when all three components are zero", () => {- const r = invoiceSettlementValidator.safeParse({- ...validApp,- appliedAmount: 0,+ const base = (overrides: Record<string, unknown>) =>+ invoiceSettlementValidator.safeParse({+ paymentId: "p1",+ appliedAmount: 50,discountAmount: 0,- writeOffAmount: 0+ writeOffAmount: 0,+ targetExchangeRate: 1,+ sourceExchangeRate: 1,+ appliedDate: "2026-05-19",+ ...overrides});- expect(r.success).toBe(false);- });- it("accepts a discount-only application (no cash applied)", () => {- const r = invoiceSettlementValidator.safeParse({- ...validApp,- appliedAmount: 0,- discountAmount: 5- });- expect(r.success).toBe(true);+ it.each([+ [{ targetSalesInvoiceId: "si1" }, true],+ [{ targetPurchaseInvoiceId: "pi1" }, true],+ [{ targetReimbursementId: "reimb1" }, true],+ [{}, false],+ [{ targetSalesInvoiceId: "si1", targetPurchaseInvoiceId: "pi1" }, false],+ [{ targetSalesInvoiceId: "si1", targetReimbursementId: "reimb1" }, false]+ ])("needs exactly one target: %o parses %s", (targets, success) => {+ expect(base(targets).success).toBe(success);});- it("accepts a write-off-only application", () => {- const r = invoiceSettlementValidator.safeParse({- ...validApp,+ it.each([+ [{ appliedAmount: 0 }, false],+ [{ appliedAmount: 0, discountAmount: 5 }, true],+ [{ appliedAmount: 0, writeOffAmount: 5 }, true]+ ])("needs a non-zero component: %o parses %s", (amounts, success) => {+ expect(base({ targetSalesInvoiceId: "si1", ...amounts }).success).toBe(+ success+ );+ });++ it("keeps the exact document principal when its rounded base is zero", () => {+ const result = base({+ targetSalesInvoiceId: "si1",appliedAmount: 0,- writeOffAmount: 5- });- expect(r.success).toBe(true);- });-- it("rejects a zero invoice exchange rate", () => {- const r = invoiceSettlementValidator.safeParse({- ...validApp,- targetExchangeRate: 0- });- expect(r.success).toBe(false);- });-- it("rejects a negative payment exchange rate", () => {- const r = invoiceSettlementValidator.safeParse({- ...validApp,- sourceExchangeRate: -1+ sourceAmount: 0.01,+ sourceExchangeRate: 100000,+ targetExchangeRate: 100000});- expect(r.success).toBe(false);+ expect(result.data?.sourceAmount).toBe(0.01);});});describe("isInvoicePayable", () => {- it("is payable when posted with a real outstanding balance", () => {- expect(isInvoicePayable("Partially Paid", 25)).toBe(true);- expect(isInvoicePayable("Submitted", 0.01)).toBe(true);- expect(isInvoicePayable("Overdue", 100)).toBe(true);- });-- it("keeps positive foreign document remainders payable below a base cent", () => {- expect(isInvoicePayable("Partially Paid", 0.003)).toBe(true);- expect(isInvoicePayable("Partially Paid", 0.009)).toBe(true);- });-- it("is not payable when fully paid or zero balance", () => {- expect(isInvoicePayable("Paid", 0)).toBe(false);- expect(isInvoicePayable("Submitted", 0)).toBe(false);- });-- it("is not payable in non-payable statuses regardless of balance", () => {- expect(isInvoicePayable("Voided", 100)).toBe(false);- expect(isInvoicePayable("Draft", 100)).toBe(false);- expect(isInvoicePayable("Pending", 100)).toBe(false);- });-- it("treats nullish balance/status as not payable", () => {- expect(isInvoicePayable(null, null)).toBe(false);- expect(isInvoicePayable(undefined, undefined)).toBe(false);- });-});--it("retains exact document principal when its rounded base is zero", () => {- const result = invoiceSettlementValidator.safeParse({- paymentId: "pay",- targetSalesInvoiceId: "inv",- appliedAmount: 0,- discountAmount: 0,- writeOffAmount: 0,- sourceAmount: 0.01,- sourceExchangeRate: 100000,- targetExchangeRate: 100000,- appliedDate: "2026-09-07"+ it.each([+ ["Partially Paid", 25, true],+ ["Submitted", 0.01, true],+ ["Overdue", 100, true],+ // A foreign document remainder below one base cent is still owed.+ ["Partially Paid", 0.003, true],+ ["Paid", 0, false],+ ["Submitted", 0, false],+ ["Voided", 100, false],+ ["Draft", 100, false],+ ["Pending", 100, false],+ [null, null, false],+ [undefined, undefined, false]+ ])("%s with balance %s → %s", (status, balance, payable) => {+ expect(isInvoicePayable(status, balance)).toBe(payable);});- expect(result.success).toBe(true);- if (result.success) expect(result.data).toHaveProperty("sourceAmount", 0.01);});+// Every party × direction is legal: deriving direction from the party once+// made a customer Debit / supplier Credit memo unauthorable.describe("memoValidator", () => {- /**- * All four party × direction combinations are legal and must stay authorable.- * `memoDirection` carries both values, `memo`'s only party constraint is- * customer-XOR-supplier (verified against the live schema — nothing pairs the- * two), both memo list routes filter on the PARTY and offer direction as a- * separate filter, and `packages/database/src/datasets/validate.ts` requires- * coverage of both directions.- *- * `MemoForm` briefly derived `direction` from the party and force-submitted it- * with `<Hidden value>`, which both overwrote a stored direction on save and- * made a customer Debit / supplier Credit memo unauthorable. This pins the- * contract that change violated.- */const base = {memoDate: "2026-09-28",currencyCode: "USD",@@ -317,41 +124,37 @@ describe("memoValidator", () => {};it.each([- ["customer", "Credit"],- ["customer", "Debit"],- ["supplier", "Credit"],- ["supplier", "Debit"]- ] as const)("accepts a %s memo in the %s direction", (party, direction) => {- const result = memoValidator.safeParse({- ...base,- direction,- ...(party === "customer"- ? { customerId: "cust_1" }- : { supplierId: "sup_1" })- });- expect(result.success).toBe(true);- if (result.success) expect(result.data.direction).toBe(direction);+ [{ customerId: "cust_1" }, "Credit"],+ [{ customerId: "cust_1" }, "Debit"],+ [{ supplierId: "sup_1" }, "Credit"],+ [{ supplierId: "sup_1" }, "Debit"]+ ] as const)("accepts %o in the %s direction", (party, direction) => {+ expect(+ memoValidator.safeParse({ ...base, direction, ...party }).data?.direction+ ).toBe(direction);});- it("still requires exactly one party", () => {- for (const parties of [{}, { customerId: "cust_1", supplierId: "sup_1" }]) {+ it.each([{}, { customerId: "cust_1", supplierId: "sup_1" }])(+ "requires exactly one party, refusing %o",+ (parties) => {expect(memoValidator.safeParse({ ...base, direction: "Credit", ...parties }).success).toBe(false);}- });+ );it("requires a direction rather than defaulting one", () => {- // A defaulted direction is how a wrong one reaches the journal unnoticed.expect(memoValidator.safeParse({ ...base, customerId: "cust_1" }).success).toBe(false);});});-describe("salesInvoiceCustomerChange", () => {- it("sets the invoice customer and clears its contact and location", () => {+describe("invoice party change", () => {+ const eur = { currencyCode: "EUR", exchangeRate: 0.92 };++ it("sets the invoice customer, clears its contact and location, and keeps the currency when the customer has none", () => {expect(salesInvoiceCustomerChange("cust_billing", null)).toEqual({invoiceCustomerId: "cust_billing",invoiceCustomerContactId: null,@@ -359,59 +162,26 @@ describe("salesInvoiceCustomerChange", () => {});});- it("never writes the sold-to customer", () => {- for (const currency of [- null,- { currencyCode: "EUR", exchangeRate: 0.92 }- ]) {- expect(- salesInvoiceCustomerChange("cust_billing", currency)- ).not.toHaveProperty("customerId");- }- });-- it("keeps the invoice currency when the customer has none", () => {- const change = salesInvoiceCustomerChange("cust_billing", null);- expect(change).not.toHaveProperty("currencyCode");- expect(change).not.toHaveProperty("exchangeRate");- });-- it("takes the customer's currency and rate when it has one", () => {- expect(- salesInvoiceCustomerChange("cust_billing", {- currencyCode: "EUR",- exchangeRate: 0.92- })- ).toMatchObject({ currencyCode: "EUR", exchangeRate: 0.92 });+ it("takes the invoice customer's currency, never the sold-to customer", () => {+ expect(salesInvoiceCustomerChange("cust_billing", eur)).toEqual({+ invoiceCustomerId: "cust_billing",+ invoiceCustomerContactId: null,+ invoiceCustomerLocationId: null,+ ...eur+ });});-});-describe("purchaseInvoiceSupplierChange", () => {- it("sets the invoice supplier and clears its contact and location", () => {+ it("sets the invoice supplier and takes its currency, never the supplier", () => {expect(purchaseInvoiceSupplierChange("supp_billing", null)).toEqual({invoiceSupplierId: "supp_billing",invoiceSupplierContactId: null,invoiceSupplierLocationId: null});- });-- it("never writes the supplier", () => {- for (const currency of [- null,- { currencyCode: "EUR", exchangeRate: 0.92 }- ]) {- expect(- purchaseInvoiceSupplierChange("supp_billing", currency)- ).not.toHaveProperty("supplierId");- }- });-- it("takes the supplier's currency and rate when it has one", () => {- expect(- purchaseInvoiceSupplierChange("supp_billing", {- currencyCode: "EUR",- exchangeRate: 0.92- })- ).toMatchObject({ currencyCode: "EUR", exchangeRate: 0.92 });+ expect(purchaseInvoiceSupplierChange("supp_billing", eur)).toEqual({+ invoiceSupplierId: "supp_billing",+ invoiceSupplierContactId: null,+ invoiceSupplierLocationId: null,+ ...eur+ });});});diff --git a/apps/erp/app/modules/invoicing/invoicing.service.charge.test.ts b/apps/erp/app/modules/invoicing/invoicing.service.charge.test.tsdeleted file mode 100644index 74b5c776cc..0000000000--- a/apps/erp/app/modules/invoicing/invoicing.service.charge.test.ts+++ /dev/null@@ -1,47 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import type { Database } from "@carbon/database";-import { createClient } from "@supabase/supabase-js";-import { describe, expect, it, vi } from "vitest";--vi.mock("@carbon/content/glossary", () => ({- terms: {},- getEntry: () => null,- lookupEntry: () => null,- hasEntry: () => false,- termSlug: (value: string) => value,- glossaryEntries: () => []-}));--vi.mock("../people/people.service", () => ({}));-vi.mock("../sales/sales.service", () => ({}));-vi.mock("../accounting/accounting.service", () => ({}));--import { getCharge } from "./invoicing.service";--describe("getCharge", () => {- it("scopes the charge and embedded lines by company and id", async () => {- const requests: URL[] = [];- const client = createClient<Database>("http://charge.test", "key", {- auth: { persistSession: false, autoRefreshToken: false },- global: {- fetch: async (input) => {- requests.push(new URL(String(input)));- return Response.json({- id: "shared-id",- companyId: "company-a",- chargeLine: []- });- }- }- });-- await getCharge(client, "company-a", "shared-id");-- expect(requests).toHaveLength(1);- expect(requests[0]?.searchParams.get("id")).toBe("eq.shared-id");- expect(requests[0]?.searchParams.get("companyId")).toBe("eq.company-a");- });-});diff --git a/apps/erp/app/modules/invoicing/invoicing.settlements.test.ts b/apps/erp/app/modules/invoicing/invoicing.settlements.test.tsindex a671c83b16..f68b9c8a67 100644--- a/apps/erp/app/modules/invoicing/invoicing.settlements.test.ts+++ b/apps/erp/app/modules/invoicing/invoicing.settlements.test.ts@@ -4,24 +4,14 @@import type { Database } from "@carbon/database";import type { SupabaseClient } from "@supabase/supabase-js";-import { describe, expect, it, vi } from "vitest";--vi.mock("@carbon/content/glossary", () => ({- terms: {},- getEntry: () => null,- lookupEntry: () => null,- hasEntry: () => false,- termSlug: (s: string) => s,- glossaryEntries: () => []-}));--vi.mock("../people/people.service", () => ({}));-vi.mock("../sales/sales.service", () => ({}));-vi.mock("../accounting/accounting.service", () => ({}));-+import { describe, expect, it } from "vitest";import * as service from "./invoicing.service";type Row = Record<string, any>;++// In-memory PostgREST fake. Rows omit columns a test does not care about, and a+// filter on an absent column (including embedded `payment.status` filters)+// passes, so these tests cover the arithmetic, not which rows a query selects.function clientFor(tables: Record<string, Row[]>,failedPages: Record<string, number> = {}@@ -87,6 +77,58 @@ function clientFor(} as unknown as SupabaseClient<Database>};}++// Kysely fake with the same leniency; records inserts and which tables were+// deleted from, so a refusal can be shown to write nothing.+function databaseFor(tables: Record<string, Row[]>) {+ const inserts: Row[] = [];+ const deletes: string[] = [];+ const db: any = {+ transaction: () => ({ execute: (fn: any) => fn(db) }),+ selectFrom: (table: string) => query(table),+ deleteFrom: (table: string) => query(table, "delete"),+ insertInto: (table: string) => query(table, "insert")+ };+ function query(table: string, mode = "select") {+ let rows = tables[table] ?? [];+ const q: any = {+ select: () => q,+ selectAll: () => q,+ forUpdate: () => q,+ orderBy: () => q,+ leftJoin: () => q,+ innerJoin: () => q,+ where: (column: unknown, op: string, value: unknown) => {+ if (typeof column === "string") {+ const key = column.split(".").at(-1)!;+ rows = rows.filter(+ (r) =>+ r[key] === undefined ||+ (op === "in"+ ? (value as unknown[]).includes(r[key])+ : op === "!="+ ? r[key] !== value+ : r[key] === value)+ );+ }+ return q;+ },+ values: (values: Row[]) => {+ inserts.push(...values);+ return q;+ },+ execute: async () => {+ if (mode === "delete") deletes.push(table);+ return rows;+ },+ executeTakeFirst: async () => rows[0]+ };+ return q;+ }+ return { db, inserts, deletes };+}++// 110 EUR received at 1.1 EUR per USD = 100 USD base.const payment = {id: "prior",companyId: "co",@@ -103,9 +145,140 @@ const config = {company: [{ id: "co", companyGroupId: "group", baseCurrencyCode: "USD" }],currency: [{ code: "EUR", companyGroupId: "group", decimalPlaces: 2 }]};+const current = {+ ...payment,+ id: "current",+ status: "Draft",+ totalAmount: 110,+ exchangeRate: 1.2+};+const invoice = {+ partyId: "cust",+ id: "invoice",+ companyId: "co",+ customerId: "cust",+ status: "Submitted",+ currencyCode: "EUR",+ exchangeRate: 1.1,+ totalAmount: 100,+ balance: 100,+ invoiceId: "INV1"+};+const draft = {+ targetSalesInvoiceId: "invoice",+ appliedAmount: 100,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1.1,+ sourceExchangeRate: 1.2,+ sourceAmount: 110,+ appliedDate: "2026-09-07"+};+const memo = (overrides: Row = {}) => ({+ id: "memo",+ memoId: "CM1",+ companyId: "co",+ status: "Posted",+ direction: "Credit",+ customerId: "cust",+ supplierId: null,+ currencyCode: "EUR",+ exchangeRate: 1.1,+ amount: 55,+ ...overrides+});+// A settlement row as the open-invoice readers select it.+const settlement = (overrides: Row = {}) => ({+ paymentId: "posted",+ memoId: null,+ targetSalesInvoiceId: "invoice",+ sourceAmount: 1,+ appliedAmount: 1,+ discountAmount: 0,+ writeOffAmount: 0,+ payment: { status: "Posted" },+ memo: null,+ appliedViaPayment: null,+ ...overrides+});++function draftDb(overrides: Record<string, Row[]> = {}) {+ return databaseFor({+ ...config,+ payment: [current],+ salesInvoice: [invoice],+ salesInvoices: [invoice],+ ...overrides+ });+}+const replace = (+ db: unknown,+ applications: Parameters<+ typeof service.replaceInvoiceSettlements+ >[1]["applications"]+) =>+ service.replaceInvoiceSettlements(db as any, {+ paymentId: "current",+ companyId: "co",+ createdBy: "user",+ applications+ });+const applyCredits = (+ db: unknown,+ applications: Parameters<+ typeof service.applyCreditsToInvoices+ >[1]["applications"]+) =>+ service.applyCreditsToInvoices(db as any, {+ paymentId: "current",+ companyId: "co",+ createdBy: "user",+ side: "sales",+ appliedDate: "2026-09-07",+ applications+ });+const onAccountSources = (+ client: SupabaseClient<Database>,+ party: Parameters<typeof service.getAvailableOnAccountCreditSources>[2] = {+ paymentType: "Receipt",+ customerId: "cust"+ }+) => service.getAvailableOnAccountCreditSources(client, "co", party, "EUR");+const memoCredits = (+ client: SupabaseClient<Database>,+ excludePaymentId?: string+) =>+ service.getAvailableCreditsForParty(+ client,+ "co",+ { side: "sales", customerId: "cust" },+ excludePaymentId,+ "EUR"+ );+const openInvoices = (+ client: SupabaseClient<Database>,+ side: "sales" | "purchase" = "sales"+) =>+ side === "sales"+ ? service.getOpenSalesInvoicesForCustomer(client, "co", "cust", "EUR")+ : service.getOpenPurchaseInvoicesForSupplier(+ client,+ "co",+ "supplier",+ "EUR"+ );+const invoicesTable = (side: "sales" | "purchase") =>+ side === "sales" ? "salesInvoices" : "purchaseInvoices";+const companyScoped = (+ calls: ReturnType<typeof clientFor>["calls"],+ table: string+) =>+ calls+ .filter((c) => c.table === table)+ .every((c) => c.filters.some(([k, v]) => k === "companyId" && v === "co"));-describe("authoritative on-account sources", () => {- it("keeps the existing base-total reader contract, dividing document cash by its snapshot", async () => {+describe("on-account credit sources", () => {+ it("reports the base total by dividing document cash by its rate", async () => {const { client } = clientFor({ ...config, payment: [payment] });expect(await service.getAvailableOnAccountCredit(client, "co", {@@ -114,7 +287,9 @@ describe("authoritative on-account sources", () => {})).toBe(100);});- it("spends original document credit and its recorded base release only after applying payment posts", async () => {++ it("spends document credit and its recorded base release only once the applying payment posts", async () => {+ // Posted: 55 EUR consumed, base release 40 + 10 FX = 50. Draft reserves nothing.const { client, calls } = clientFor({...config,payment: [@@ -140,35 +315,27 @@ describe("authoritative on-account sources", () => {}]});- const result = await service.getAvailableOnAccountCreditSources(- client,- "co",- { paymentType: "Receipt", customerId: "cust" },- "EUR"- );- expect(result.error).toBeNull();- expect(result.data).toEqual({- sources: [- {- paymentId: "prior",- postingDate: "2026-01-01",- exchangeRate: 1.1,- remainingDocument: 55,- remainingBase: 50- }- ],- availableDocumentAmount: 55,- availableBaseAmount: 50+ expect(await onAccountSources(client)).toEqual({+ data: {+ sources: [+ {+ paymentId: "prior",+ postingDate: "2026-01-01",+ exchangeRate: 1.1,+ remainingDocument: 55,+ remainingBase: 50+ }+ ],+ availableDocumentAmount: 55,+ availableBaseAmount: 50+ },+ error: null});- expect(- calls- .filter((c) => c.table === "payment")- .every((c) =>- c.filters.some(([k, v]) => k === "companyId" && v === "co")- )- ).toBe(true);+ expect(companyScoped(calls, "payment")).toBe(true);});- it("uses AP applied minus FX for carrying release", async () => {++ it("releases AP carrying base as applied minus FX", async () => {+ // 100 − (40 − (−10)) = 50.const { client } = clientFor({...config,payment: [@@ -190,210 +357,159 @@ describe("authoritative on-account sources", () => {}]});- const result = await service.getAvailableOnAccountCreditSources(- client,- "co",- { paymentType: "Disbursement", supplierId: "sup" },- "EUR"- );+ const result = await onAccountSources(client, {+ paymentType: "Disbursement",+ supplierId: "sup"+ });expect(result.data?.availableBaseAmount).toBe(50);});- it("retains a positive minor unit with zero carrying base and rejects missing precision", async () => {++ it("keeps a positive minor unit whose carrying base rounds to zero", async () => {const { client } = clientFor({...config,payment: [{ ...payment, totalAmount: 0.01, exchangeRate: 100000 }]});- expect(- (- await service.getAvailableOnAccountCreditSources(- client,- "co",- { paymentType: "Receipt", customerId: "cust" },- "EUR"- )- ).data?.sources[0]- ).toMatchObject({ remainingDocument: 0.01, remainingBase: 0 });- const missing = clientFor({ ...config, currency: [], payment: [payment] });- expect(- (- await service.getAvailableOnAccountCreditSources(- missing.client,- "co",- { paymentType: "Receipt", customerId: "cust" },- "EUR"- )- ).error?.message- ).toMatch(/currency/i);+ expect((await onAccountSources(client)).data?.sources[0]).toMatchObject({+ remainingDocument: 0.01,+ remainingBase: 0+ });+ });++ it("refuses when the currency has no configured precision", async () => {+ const { client } = clientFor({+ ...config,+ currency: [],+ payment: [payment]+ });+ expect((await onAccountSources(client)).error?.message).toMatch(+ /currency/i+ );+ });++ it("includes every posted source beyond the 1000-row response cap", async () => {+ const { client } = clientFor({+ ...config,+ payment: Array.from({ length: 1001 }, (_, i) => ({+ ...payment,+ id: `prior-${i}`+ }))+ });+ const result = await onAccountSources(client);+ expect(result.data?.sources).toHaveLength(1001);+ expect(result.data?.availableBaseAmount).toBe(100100);+ expect(result.data?.availableDocumentAmount).toBe(110110);+ });++ it("deducts consumption rows across pages", async () => {+ const { client } = clientFor({+ ...config,+ payment: [{ ...payment, totalAmount: 1002, exchangeRate: 1 }],+ invoiceSettlement: Array.from({ length: 1001 }, (_, i) => ({+ id: `s-${i}`,+ paymentId: "prior",+ sourcePaymentId: null,+ sourceAmount: 1,+ appliedAmount: 1,+ fxGainLossAmount: 0,+ payment: { status: "Posted" }+ }))+ });+ const result = await onAccountSources(client);+ expect(result.data?.availableDocumentAmount).toBe(1);+ expect(result.data?.availableBaseAmount).toBe(1);});});-describe("memo credit readers", () => {- it("reports 55 EUR at 1.1 as 50 base; Draft reserves, Voided releases, own staged rows remain visible", async () => {+describe("memo credit availability", () => {+ it("reports 55 EUR at 1.1 as 50 base; a Draft reserves, a Voided releases, the caller's own staged rows stay available", async () => {+ const staged = (+ paymentId: string,+ status: string,+ sourceAmount: number,+ appliedAmount: number+ ) => ({+ memoId: "memo",+ sourceAmount,+ appliedAmount,+ appliedViaPaymentId: paymentId,+ appliedViaPayment: { status }+ });const { client } = clientFor({...config,- memo: [- {- id: "memo",- memoId: "CM1",- direction: "Credit",- companyId: "co",- customerId: "cust",- status: "Posted",- currencyCode: "EUR",- exchangeRate: 1.1,- amount: 55- }- ],+ memo: [memo()],+ invoiceSettlement: [+ staged("draft", "Draft", 11, 10),+ staged("void", "Voided", 22, 20),+ staged("own", "Draft", 11, 10)+ ]+ });+ expect((await memoCredits(client, "own")).data?.[0]).toMatchObject({+ amount: 50,+ remaining: 40,+ remainingDocument: 44+ });+ });++ it("deducts posted consumption across pages", async () => {+ const { client } = clientFor({+ ...config,+ memo: [memo({ exchangeRate: 1, amount: 1002 })],+ invoiceSettlement: Array.from({ length: 1001 }, (_, i) => ({+ id: `s-${i}`,+ memoId: "memo",+ sourceAmount: 1,+ appliedAmount: 1,+ fxGainLossAmount: 0,+ appliedViaPaymentId: null+ }))+ });+ expect((await memoCredits(client)).data?.[0]).toMatchObject({+ remaining: 1,+ remainingDocument: 1+ });+ });++ it("reserves a refund's document principal without taking its FX from the memo's carrying base", async () => {+ // 55 − 22 = 33 EUR left; base 50 − 20 = 30, the 2.4 refund FX not deducted.+ const { client } = clientFor({+ ...config,+ memo: [memo()],invoiceSettlement: [{- memoId: "memo",- sourceAmount: 11,- appliedAmount: 10,- appliedViaPaymentId: "draft",- appliedViaPayment: { status: "Draft" }- },- {- memoId: "memo",+ memoId: null,+ targetMemoId: "memo",+ paymentId: "refund",sourceAmount: 22,appliedAmount: 20,- appliedViaPaymentId: "void",- appliedViaPayment: { status: "Voided" }- },- {- memoId: "memo",- sourceAmount: 11,- appliedAmount: 10,- appliedViaPaymentId: "own",- appliedViaPayment: { status: "Draft" }+ fxGainLossAmount: 2.4,+ payment: { status: "Posted" },+ appliedViaPaymentId: null}]});- const result = await service.getAvailableCreditsForParty(- client,- "co",- { side: "sales", customerId: "cust" },- "own",- "EUR"- );- expect(result.data?.[0]).toMatchObject({- amount: 50,- remaining: 40,- remainingDocument: 44+ expect((await memoCredits(client)).data?.[0]).toMatchObject({+ remainingDocument: 33,+ remaining: 30});});});-function databaseFor(tables: Record<string, Row[]>) {- const inserts: Row[] = [];- const deletes: string[] = [];- const db: any = {- transaction: () => ({ execute: (fn: any) => fn(db) }),- selectFrom: (table: string) => query(table),- deleteFrom: (table: string) => query(table, "delete"),- insertInto: (table: string) => query(table, "insert")- };- function query(table: string, mode = "select") {- let rows = tables[table] ?? [];- const q: any = {- select: () => q,- selectAll: () => q,- forUpdate: () => q,- orderBy: () => q,- leftJoin: () => q,- innerJoin: () => q,- where: (column: unknown, op: string, value: unknown) => {- if (typeof column === "string") {- const key = column.split(".").at(-1)!;- rows = rows.filter(- (r) =>- r[key] === undefined ||- (op === "in"- ? (value as unknown[]).includes(r[key])- : op === "!="- ? r[key] !== value- : r[key] === value)- );- }- return q;- },- values: (values: Row[]) => {- inserts.push(...values);- return q;- },- execute: async () => {- if (mode === "delete") deletes.push(table);- return rows;- },- executeTakeFirst: async () => rows[0]- };- return q;- }- return { db, inserts, deletes };-}-const current = {- ...payment,- id: "current",- status: "Draft",- totalAmount: 110,- exchangeRate: 1.2-};-const invoice = {- partyId: "cust",- id: "invoice",- companyId: "co",- customerId: "cust",- status: "Submitted",- currencyCode: "EUR",- exchangeRate: 1.1,- totalAmount: 100,- balance: 100,- invoiceId: "INV1"-};-const draft = {- targetSalesInvoiceId: "invoice",- appliedAmount: 100,- discountAmount: 0,- writeOffAmount: 0,- targetExchangeRate: 1.1,- sourceExchangeRate: 1.2,- sourceAmount: 110,- appliedDate: "2026-09-07"-};-function draftDb(overrides: Record<string, Row[]> = {}) {- return databaseFor({- ...config,- payment: [current],- salesInvoice: [invoice],- salesInvoices: [invoice],- ...overrides- });-}-describe("replaceInvoiceSettlements transaction", () => {+describe("replaceInvoiceSettlements", () => {it.each([["target rate", { ...draft, targetExchangeRate: 2 }],["source rate", { ...draft, sourceExchangeRate: 2 }],["funding source", { ...draft, sourcePaymentId: "forged" }]- ])("rejects a forged %s before replacing drafts", async (_label, app) => {+ ])("rejects a forged %s before replacing drafts", async (_, app) => {const { db, deletes, inserts } = draftDb();- await expect(- service.replaceInvoiceSettlements(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- applications: [app]- })- ).rejects.toThrow(/rate|source/i);+ await expect(replace(db, [app])).rejects.toThrow(/rate|source/i);expect(deletes).toEqual([]);expect(inserts).toEqual([]);});- it("recomputes base principal and realized FX from authoritative invoice/payment snapshots", async () => {++ it("recomputes base principal and realized FX from the invoice and payment snapshots", async () => {+ // 110 EUR at 1.2 = 91.66667 base paid against 100 base billed: FX −8.33333.const { db, inserts } = draftDb();- await service.replaceInvoiceSettlements(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- applications: [draft]- });+ await replace(db, [draft]);expect(inserts).toEqual([expect.objectContaining({paymentId: "current",@@ -406,33 +522,32 @@ describe("replaceInvoiceSettlements transaction", () => {})]);});- it("rejects another currency and missing configured precision", async () => {- for (const overrides of [- { salesInvoice: [{ ...invoice, currencyCode: "GBP" }] },- { currency: [] }- ] as Record<string, Row[]>[]) {- const { db, inserts } = draftDb(overrides);- await expect(- service.replaceInvoiceSettlements(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- applications: [draft]- })- ).rejects.toThrow(/currency|decimal/i);- expect(inserts).toEqual([]);- }++ it.each([+ [+ "another currency",+ { salesInvoice: [{ ...invoice, currencyCode: "GBP" }] }+ ],+ ["no configured precision", { currency: [] }]+ ])("rejects an invoice in %s", async (_, overrides) => {+ const { db, inserts } = draftDb(overrides);+ await expect(replace(db, [draft])).rejects.toThrow(/currency|decimal/i);+ expect(inserts).toEqual([]);});- it("allocates a zero-cash draft from the prior payment without repricing it", async () => {++ it("refuses a principal finer than the currency's precision", async () => {+ const { db, deletes } = draftDb();+ await expect(+ replace(db, [{ ...draft, sourceAmount: 0.015, appliedAmount: 0.01364 }])+ ).rejects.toThrow(/precision/i);+ expect(deletes).toEqual([]);+ });++ it("funds a zero-cash draft from the prior payment at that payment's rate", async () => {const { db, inserts } = draftDb({payment: [{ ...current, totalAmount: 0 }, payment]});- await service.replaceInvoiceSettlements(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- applications: [draft]- });+ await replace(db, [draft]);expect(inserts[0]).toMatchObject({paymentId: "current",sourcePaymentId: "prior",@@ -442,7 +557,8 @@ describe("replaceInvoiceSettlements transaction", () => {fxGainLossAmount: 0});});- it("retains full document principal after base precision rounds to zero", async () => {++ it("keeps the full document principal when its base rounds to zero", async () => {const tiny = {...invoice,exchangeRate: 100000,@@ -454,26 +570,295 @@ describe("replaceInvoiceSettlements transaction", () => {salesInvoice: [tiny],salesInvoices: [tiny]});- await service.replaceInvoiceSettlements(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- applications: [+ await replace(db, [+ {+ ...draft,+ sourceAmount: 0.01,+ appliedAmount: 0,+ sourceExchangeRate: 100000,+ targetExchangeRate: 100000+ }+ ]);+ expect(inserts[0]).toMatchObject({ sourceAmount: 0.01, appliedAmount: 0 });+ });++ it("refuses to keep a staged credit whose memo was voided", async () => {+ const { db, deletes } = draftDb({+ invoiceSettlement: [{- ...draft,- sourceAmount: 0.01,- appliedAmount: 0,- sourceExchangeRate: 100000,- targetExchangeRate: 100000+ companyId: "co",+ memoId: "memo",+ paymentId: null,+ appliedViaPaymentId: "current",+ targetSalesInvoiceId: "invoice",+ sourceAmount: 11,+ appliedAmount: 10,+ discountAmount: 0,+ writeOffAmount: 0+ }+ ],+ memo: [memo({ status: "Voided" })]+ });+ await expect(+ replace(db, [{ ...draft, sourceAmount: 55, appliedAmount: 50 }])+ ).rejects.toThrow(/posted credit/i);+ expect(deletes).toEqual([]);+ });++ it("gives AP the opposite FX sign and applies the recorded control carrying amount", async () => {+ const payable = {+ ...invoice,+ customerId: undefined,+ supplierId: "sup",+ partyId: "sup",+ status: "Open"+ };+ const { db, inserts } = draftDb({+ payment: [+ {+ ...current,+ paymentType: "Disbursement",+ customerId: null,+ supplierId: "sup"+ }+ ],+ purchaseInvoice: [payable],+ purchaseInvoices: [payable],+ journalLine: [{ documentId: "invoice", amount: 100.00001 }]+ });+ await replace(db, [+ {+ ...draft,+ targetSalesInvoiceId: undefined,+ targetPurchaseInvoiceId: "invoice"+ }+ ]);+ expect(inserts[0]).toMatchObject({+ targetPurchaseInvoiceId: "invoice",+ appliedAmount: 100.00001,+ sourceAmount: 110,+ fxGainLossAmount: 8.33334+ });+ });+});++describe("memo refunds", () => {+ const refundMemo = (isAR: boolean, overrides: Row = {}) =>+ memo({+ customerId: isAR ? "cust" : null,+ supplierId: isAR ? null : "supplier",+ direction: isAR ? "Credit" : "Debit",+ ...overrides+ });+ const refund = {+ ...draft,+ targetSalesInvoiceId: undefined,+ targetMemoId: "memo",+ sourceAmount: 55,+ sourceExchangeRate: 1.25,+ appliedAmount: 50+ };++ it.each([true, false])(+ "stages a refund (customer: %s) against the exact memo principal with cash-direction FX",+ async (isAR) => {+ // 55 EUR at 1.25 = 44 base against 50 carrying: 6 in the cash direction.+ const { db, inserts } = draftDb({+ payment: [+ {+ ...current,+ paymentType: isAR ? "Disbursement" : "Receipt",+ customerId: isAR ? "cust" : null,+ supplierId: isAR ? null : "supplier",+ totalAmount: 55,+ exchangeRate: 1.25+ }+ ],+ memo: [refundMemo(isAR)],+ journalLine: [{ documentId: "memo", amount: -50 }]+ });+ await replace(db, [refund]);+ expect(inserts).toEqual([+ expect.objectContaining({+ targetMemoId: "memo",+ targetSalesInvoiceId: null,+ targetPurchaseInvoiceId: null,+ sourcePaymentId: null,+ sourceAmount: 55,+ appliedAmount: 50,+ fxGainLossAmount: isAR ? 6 : -6,+ createdBy: "user"+ })+ ]);+ }+ );++ it.each([+ ["party", { supplierId: "other" }, {}],+ ["currency", { currencyCode: "USD" }, {}],+ ["direction", { direction: "Credit" }, {}],+ ["memo status", { status: "Draft" }, {}],+ ["adjustments", {}, { discountAmount: 1 }],+ ["over-refund", {}, { sourceAmount: 56 }],+ [+ "invoice target",+ {},+ { targetMemoId: undefined, targetPurchaseInvoiceId: "invoice" }+ ]+ ])(+ "rejects a supplier refund with a bad %s without replacing applications",+ async (_, memoOverride, appOverride) => {+ const { db, inserts, deletes } = draftDb({+ payment: [+ {+ ...current,+ paymentType: "Receipt",+ customerId: null,+ supplierId: "supplier",+ totalAmount: 100,+ exchangeRate: 1.25+ }+ ],+ memo: [refundMemo(false, memoOverride)]+ });+ await expect(+ replace(db, [{ ...refund, ...appOverride }])+ ).rejects.toThrow();+ expect(inserts).toEqual([]);+ expect(deletes).toEqual([]);+ }+ );++ it("a fully refunded memo cannot also fund an invoice", async () => {+ const { db, inserts } = draftDb({+ payment: [{ ...current, totalAmount: 0, exchangeRate: 1.1 }],+ memo: [memo()],+ invoiceSettlement: [+ {+ memoId: null,+ targetMemoId: "memo",+ paymentId: "refund",+ sourceAmount: 55,+ appliedAmount: 50,+ fxGainLossAmount: 6}]});- expect(inserts[0]).toMatchObject({ sourceAmount: 0.01, appliedAmount: 0 });+ await expect(+ applyCredits(db, [+ { memoId: "memo", invoiceId: "invoice", amount: 50, sourceAmount: 55 }+ ])+ ).rejects.toThrow(/remaining funding balance/);+ expect(inserts).toEqual([]);+ });+});++describe("applyCreditsToInvoices", () => {+ it("stores the exact memo document principal while applying the base amount", async () => {+ const { db, inserts } = draftDb({ memo: [memo()] });+ await applyCredits(db, [+ { memoId: "memo", invoiceId: "invoice", amount: 50 }+ ]);+ expect(inserts[0]).toMatchObject({+ memoId: "memo",+ appliedViaPaymentId: "current",+ appliedAmount: 50,+ sourceAmount: 55,+ sourceExchangeRate: 1.1,+ targetExchangeRate: 1.1+ });+ });++ it.each([+ ["a Draft", { status: "Draft" }],+ ["a Debit", { direction: "Debit" }],+ ["another currency's", { currencyCode: "GBP" }],+ ["another customer's", { customerId: "other" }]+ ])("rejects %s memo before replacing staged credits", async (_, invalid) => {+ const { db, deletes } = draftDb({ memo: [memo(invalid)] });+ await expect(+ applyCredits(db, [{ memoId: "memo", invoiceId: "invoice", amount: 50 }])+ ).rejects.toThrow();+ expect(deletes).toEqual([]);+ });++ it("rejects an amount over the memo's base balance", async () => {+ // 54 base is under 55 EUR but over the memo's 50 base.+ const { db } = draftDb({ memo: [memo()] });+ await expect(+ applyCredits(db, [{ memoId: "memo", invoiceId: "invoice", amount: 54 }])+ ).rejects.toThrow(/funding|balance/i);+ });++ it("keeps same-rate memo FX zero when the target releases its posted rounding residual", async () => {+ const { db, inserts } = draftDb({+ memo: [memo({ amount: 110 })],+ journalLine: [{ documentId: "invoice", amount: 100.00001 }]+ });+ await applyCredits(db, [+ { memoId: "memo", invoiceId: "invoice", amount: 100, sourceAmount: 110 }+ ]);+ expect(inserts[0]).toMatchObject({+ sourceAmount: 110,+ appliedAmount: 100.00001,+ fxGainLossAmount: 0+ });+ });++ it("saves a partial and then the final document cent with zero carrying base", async () => {+ const highRateInvoice = {+ ...invoice,+ totalAmount: 160.01 / 16000,+ exchangeRate: 16000+ };+ const tables = {+ payment: [{ ...current, totalAmount: 0, exchangeRate: 16000 }],+ salesInvoice: [highRateInvoice],+ salesInvoices: [highRateInvoice],+ memo: [+ memo({+ exchangeRate: 16000,+ amount: 160.01,+ memoDate: "2026-09-07",+ postingDate: "2026-09-07"+ })+ ],+ journalLine: [{ documentId: "invoice", amount: 0.01 }]+ };+ const partial = draftDb(tables);+ await applyCredits(partial.db, [+ { memoId: "memo", invoiceId: "invoice", amount: 0.01, sourceAmount: 160 }+ ]);+ expect(partial.inserts[0]).toMatchObject({+ appliedAmount: 0.01,+ sourceAmount: 160+ });+ const final = draftDb({+ ...tables,+ invoiceSettlement: [+ {+ ...partial.inserts[0],+ paymentId: null,+ appliedViaPaymentId: "posted",+ targetPurchaseInvoiceId: null,+ discountAmount: 0,+ writeOffAmount: 0+ }+ ]+ });+ await applyCredits(final.db, [+ { memoId: "memo", invoiceId: "invoice", amount: 0, sourceAmount: 0.01 }+ ]);+ expect(final.inserts[0]).toMatchObject({+ appliedAmount: 0,+ sourceAmount: 0.01,+ fxGainLossAmount: 0+ });});});-describe("composer invoice balances", () => {- it("seeds two invoice snapshots from each original document total, independent of an old dust-forgiven view balance", async () => {+describe("open invoices for the composer", () => {+ it("seeds each invoice from its original document total, ignoring a stale view balance", async () => {const { client } = clientFor({...config,salesInvoices: [@@ -494,12 +879,7 @@ describe("composer invoice balances", () => {}]});- const result = await service.getOpenSalesInvoicesForCustomer(- client,- "co",- "cust",- "EUR"- );+ const result = await openInvoices(client);expect(result.data?.map((i) => [i.id, i.balance, i.remainingDocument])).toEqual([@@ -508,7 +888,8 @@ describe("composer invoice balances", () => {["tiny", 0, 0.01]]);});- it("uses recorded per-line control rounding and effective settlements for remaining base", async () => {++ it("takes remaining base from the recorded control line, less effective settlements", async () => {const { client } = clientFor({...config,salesInvoices: [@@ -522,403 +903,109 @@ describe("composer invoice balances", () => {}],invoiceSettlement: [- {- targetSalesInvoiceId: "invoice",- paymentId: "posted",- memoId: null,- sourceAmount: 0.01,- appliedAmount: 0.00001,- discountAmount: 0,- writeOffAmount: 0,- payment: { status: "Posted" },- memo: null,- appliedViaPayment: null- }+ settlement({ sourceAmount: 0.01, appliedAmount: 0.00001 })]});- const result = await service.getOpenSalesInvoicesForCustomer(- client,- "co",- "cust",- "EUR"- );- expect(result.data?.[0]).toMatchObject({+ expect((await openInvoices(client)).data?.[0]).toMatchObject({balance: 0.00003,remainingDocument: 0.02});});-});--describe("memo application save", () => {- const memo = {- id: "memo",- companyId: "co",- status: "Posted",- direction: "Credit",- customerId: "cust",- supplierId: null,- currencyCode: "EUR",- exchangeRate: 1.1,- amount: 55- };- it("stores exact memo document principal while applying base amount", async () => {- const { db, inserts } = draftDb({ memo: [memo] });- await service.applyCreditsToInvoices(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- side: "sales",- appliedDate: "2026-09-07",- applications: [{ memoId: "memo", invoiceId: "invoice", amount: 50 }]- });- expect(inserts[0]).toMatchObject({- memoId: "memo",- appliedViaPaymentId: "current",- appliedAmount: 50,- sourceAmount: 55,- sourceExchangeRate: 1.1,- targetExchangeRate: 1.1- });- });- it.each([- { ...memo, status: "Draft" },- { ...memo, direction: "Debit" },- { ...memo, currencyCode: "GBP" },- { ...memo, customerId: "other" }- ])(- "rejects an ineligible memo before replacing staged credits",- async (invalid) => {- const { db, deletes } = draftDb({ memo: [invalid] });- await expect(- service.applyCreditsToInvoices(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- side: "sales",- appliedDate: "2026-09-07",- applications: [{ memoId: "memo", invoiceId: "invoice", amount: 50 }]- })- ).rejects.toThrow();- expect(deletes).toEqual([]);- }- );- it("rejects base overdraw that the former document-number cap accepted", async () => {- const { db } = draftDb({ memo: [memo] });- await expect(- service.applyCreditsToInvoices(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- side: "sales",- appliedDate: "2026-09-07",- applications: [{ memoId: "memo", invoiceId: "invoice", amount: 54 }]- })- ).rejects.toThrow(/funding|balance/i);- });-});-describe("invoice history", () => {- it("aggregates funding splits under the applying payment, excludes draft/voided activity, and scopes parents", async () => {- const app = {- id: "a",- companyId: "co",- paymentId: "posted",- payment: { ...payment, id: "posted", paymentId: "PAY1" },- memoId: null,- targetSalesInvoiceId: "invoice",- sourceAmount: 44,- appliedAmount: 40,- discountAmount: 0,- writeOffAmount: 0,- fxGainLossAmount: -3.33333,- targetExchangeRate: 1.1,- sourceExchangeRate: 1.2,- appliedDate: "2026-09-07",- appliedViaPaymentId: null- };- const { client, calls } = clientFor({- invoiceSettlement: [- app,- {- ...app,- id: "b",- sourceAmount: 66,- appliedAmount: 60,- fxGainLossAmount: 0,- sourceExchangeRate: 1.1- },- {- ...app,- id: "c",- paymentId: "draft",- payment: { ...payment, status: "Draft" }- },- {- ...app,- id: "d",- paymentId: null,- payment: null,- memo: { id: "memo", companyId: "co", status: "Posted" },- appliedViaPayment: { status: "Draft" },- memoId: "memo",- appliedViaPaymentId: "draft"- }- ],- payment: [- { ...payment, id: "posted", paymentId: "PAY1" },- { ...payment, id: "draft", status: "Draft" }- ],- memo: [{ id: "memo", companyId: "co", status: "Posted" }]+ it("reads a legacy settlement with no document principal from its applied base", async () => {+ const { client } = clientFor({+ ...config,+ salesInvoices: [{ ...invoice, totalAmount: 90, exchangeRate: 1 }],+ invoiceSettlement: [settlement({ sourceAmount: null })]});- const result = await service.getInvoiceSettlementsForInvoice(- client,- "co",- "sales",- "invoice"- );- expect(result.data).toHaveLength(1);+ const result = await openInvoices(client);+ expect(result.error).toBeNull();expect(result.data?.[0]).toMatchObject({- appliedAmount: 100,- sourceAmount: 110,- fxGainLossAmount: -3.33333+ balance: 89,+ remainingDocument: 89});- expect(- calls- .filter((c) => c.table === "invoiceSettlement")- .every((c) =>- c.filters.some(- ([key, value]) => key === "companyId" && value === "co"- )- )- ).toBe(true);- });-});--it("refuses a draft principal finer than configured document precision", async () => {- const { db, deletes } = draftDb();- await expect(- service.replaceInvoiceSettlements(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- applications: [{ ...draft, sourceAmount: 0.015, appliedAmount: 0.01364 }]- })- ).rejects.toThrow(/precision/i);- expect(deletes).toEqual([]);-});--it("does not retain a staged credit whose memo has been voided", async () => {- const staged = {- companyId: "co",- memoId: "memo",- paymentId: null,- appliedViaPaymentId: "current",- targetSalesInvoiceId: "invoice",- sourceAmount: 11,- appliedAmount: 10,- discountAmount: 0,- writeOffAmount: 0- };- const { db, deletes } = draftDb({- invoiceSettlement: [staged],- memo: [- {- id: "memo",- status: "Voided",- currencyCode: "EUR",- exchangeRate: 1.1,- customerId: "cust",- direction: "Credit"- }- ]});- await expect(- service.replaceInvoiceSettlements(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- applications: [{ ...draft, sourceAmount: 55, appliedAmount: 50 }]- })- ).rejects.toThrow(/posted credit/i);- expect(deletes).toEqual([]);-});-it("normalizes AP with the opposite FX sign and recorded control carrying amount", async () => {- const payable = {- ...invoice,- customerId: undefined,- supplierId: "sup",- partyId: "sup",- status: "Open"- };- const { db, inserts } = draftDb({- payment: [- {- ...current,- paymentType: "Disbursement",- customerId: null,- supplierId: "sup"- }- ],- purchaseInvoice: [payable],- purchaseInvoices: [payable],- journalLine: [{ documentId: "invoice", amount: 100.00001 }]- });- await service.replaceInvoiceSettlements(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- applications: [- {- ...draft,- targetSalesInvoiceId: undefined,- targetPurchaseInvoiceId: "invoice"- }+ it.each([+ ["an invalid principal of -1", { sourceAmount: -1 }, /principal/i],+ ["an invalid principal of NaN", { sourceAmount: Number.NaN }, /principal/i],+ [+ "settlements over the total instead of clamping",+ { sourceAmount: 91, appliedAmount: 91 },+ /excessive settlements/i]- });- expect(inserts[0]).toMatchObject({- targetPurchaseInvoiceId: "invoice",- appliedAmount: 100.00001,- sourceAmount: 110,- fxGainLossAmount: 8.33334- });-});--describe("financial reader pagination", () => {- it("includes every posted source beyond the default 1000 row response", async () => {+ ])("refuses %s", async (_, overrides, message) => {const { client } = clientFor({...config,- payment: Array.from({ length: 1001 }, (_, i) => ({- ...payment,- id: `prior-${i}`- }))- });- const result = await service.getAvailableOnAccountCreditSources(- client,- "co",- { paymentType: "Receipt", customerId: "cust" },- "EUR"- );- expect(result.data?.sources).toHaveLength(1001);- expect(result.data?.availableBaseAmount).toBe(100100);- expect(result.data?.availableDocumentAmount).toBe(110110);- });- it("deducts all effective consumption rows across pages", async () => {- const { client } = clientFor({- ...config,- payment: [{ ...payment, totalAmount: 1002, exchangeRate: 1 }],- invoiceSettlement: Array.from({ length: 1001 }, (_, i) => ({- id: `s-${i}`,- paymentId: "prior",- sourcePaymentId: null,- sourceAmount: 1,- appliedAmount: 1,- fxGainLossAmount: 0,- payment: { status: "Posted" }- }))- });- const result = await service.getAvailableOnAccountCreditSources(- client,- "co",- { paymentType: "Receipt", customerId: "cust" },- "EUR"- );- expect(result.data?.availableDocumentAmount).toBe(1);- expect(result.data?.availableBaseAmount).toBe(1);- });- it("includes all posted memo credit consumption when determining availability", async () => {- const { client } = clientFor({- ...config,- memo: [- {- id: "memo",- memoId: "CM1",- direction: "Credit",- companyId: "co",- customerId: "cust",- status: "Posted",- currencyCode: "EUR",- exchangeRate: 1,- amount: 1002- }- ],- invoiceSettlement: Array.from({ length: 1001 }, (_, i) => ({- id: `s-${i}`,- memoId: "memo",- sourceAmount: 1,- appliedAmount: 1,- fxGainLossAmount: 0,- appliedViaPaymentId: null- }))- });- const result = await service.getAvailableCreditsForParty(- client,- "co",- { side: "sales", customerId: "cust" },- undefined,- "EUR"- );- expect(result.data?.[0]).toMatchObject({- remaining: 1,- remainingDocument: 1+ salesInvoices: [{ ...invoice, totalAmount: 90, exchangeRate: 1 }],+ invoiceSettlement: [settlement(overrides)]});+ const result = await openInvoices(client);+ expect(result.data).toBeNull();+ expect(result.error?.message).toMatch(message);});-});-it("keeps same-rate memo FX zero when the target releases its posted rounding residual", async () => {- const { db, inserts } = draftDb({- memo: [- {- id: "memo",- companyId: "co",- status: "Posted",- direction: "Credit",- customerId: "cust",- supplierId: null,- currencyCode: "EUR",- exchangeRate: 1.1,- amount: 110- }- ],- journalLine: [{ documentId: "invoice", amount: 100.00001 }]- });- await service.applyCreditsToInvoices(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- side: "sales",- appliedDate: "2026-09-07",- applications: [- { memoId: "memo", invoiceId: "invoice", amount: 100, sourceAmount: 110 }- ]- });- expect(inserts[0]).toMatchObject({- sourceAmount: 110,- appliedAmount: 100.00001,- fxGainLossAmount: 0- });-});+ it.each(["sales", "purchase"] as const)(+ "keeps signed %s control lines",+ async (side) => {+ const { client } = clientFor({+ ...config,+ [invoicesTable(side)]: [+ {+ ...invoice,+ status: side === "sales" ? "Submitted" : "Open",+ totalAmount: 90,+ exchangeRate: 1+ }+ ],+ journalLine: [+ { documentId: "invoice", amount: 100 },+ { documentId: "invoice", amount: -10 }+ ]+ });+ expect((await openInvoices(client, side)).data?.[0]).toMatchObject({+ balance: 90,+ remainingDocument: 90+ });+ }+ );++ it.each(["sales", "purchase"] as const)(+ "uses original intercompany %s controls and excludes VOID rows",+ async (side) => {+ const description = side === "sales" ? "IC Receivables" : "IC Payables";+ const { client } = clientFor({+ ...config,+ [invoicesTable(side)]: [+ {+ ...invoice,+ status: side === "sales" ? "Submitted" : "Open",+ totalAmount: 99,+ exchangeRate: 1+ }+ ],+ journalLine: [+ { documentId: "invoice", amount: 100, description },+ {+ documentId: "invoice",+ amount: -100,+ description: `VOID: ${description}`+ }+ ]+ });+ expect((await openInvoices(client, side)).data?.[0]).toMatchObject({+ balance: 100,+ remainingDocument: 99+ });+ }+ );-describe("complete composer source reads", () => {- const application = {- paymentId: "posted",- memoId: null,- targetSalesInvoiceId: "invoice",- targetPurchaseInvoiceId: "invoice",- sourceAmount: 1,- appliedAmount: 1,- discountAmount: 0,- writeOffAmount: 0,- payment: { status: "Posted" },- memo: null,- appliedViaPayment: null- };it.each(["sales", "purchase"] as const)("reads all %s settlements beyond the response cap",async (side) => {const { client } = clientFor({...config,- [side === "sales" ? "salesInvoices" : "purchaseInvoices"]: [+ [invoicesTable(side)]: [{...invoice,totalAmount: 1002,@@ -928,25 +1015,11 @@ describe("complete composer source reads", () => {}],journalLine: [{ documentId: "invoice", amount: 1002 }],- invoiceSettlement: Array.from({ length: 1001 }, (_, index) => ({- ...application,- id: `s${index}`- }))+ invoiceSettlement: Array.from({ length: 1001 }, (_, index) =>+ settlement({ id: `s${index}`, targetPurchaseInvoiceId: "invoice" })+ )});- const result =- side === "sales"- ? await service.getOpenSalesInvoicesForCustomer(- client,- "co",- "cust",- "EUR"- )- : await service.getOpenPurchaseInvoicesForSupplier(- client,- "co",- "supplier",- "EUR"- );+ const result = await openInvoices(client, side);expect(result.error).toBeNull();expect(result.data?.[0]).toMatchObject({balance: 1,@@ -954,7 +1027,8 @@ describe("complete composer source reads", () => {});});- it("reads every original control line beyond the response cap", async () => {++ it("reads every control line beyond the response cap", async () => {const { client } = clientFor({...config,salesInvoices: [{ ...invoice, totalAmount: 1001, exchangeRate: 1 }],@@ -964,18 +1038,14 @@ describe("complete composer source reads", () => {amount: 1}))});- const result = await service.getOpenSalesInvoicesForCustomer(- client,- "co",- "cust",- "EUR"- );- expect(result.data?.[0]).toMatchObject({+ expect((await openInvoices(client)).data?.[0]).toMatchObject({balance: 1001,remainingDocument: 1001});});- it("reads every invoice and bounds contributing ID filters across an ordinary invoice batch", async () => {++ // The gateway refuses long request lines, so id filters go in batches.+ it("reads every invoice with company-scoped id filters of at most 100", async () => {const invoices = Array.from({ length: 1001 }, (_, index) => ({...invoice,id: `invoice${index}`,@@ -987,430 +1057,124 @@ describe("complete composer source reads", () => {salesInvoices: invoices,journalLine: invoices.map((i) => ({ documentId: i.id, amount: 3 })),invoiceSettlement: invoices.flatMap((i, index) =>- [0, 1].map((n) => ({- ...application,- id: `s${index}-${n}`,- targetSalesInvoiceId: i.id- }))+ [0, 1].map((n) =>+ settlement({ id: `s${index}-${n}`, targetSalesInvoiceId: i.id })+ ))});- const result = await service.getOpenSalesInvoicesForCustomer(- client,- "co",- "cust",- "EUR"- );+ const result = await openInvoices(client);expect(result.data).toHaveLength(1001);expect(result.data?.every((i) => i.balance === 1 && i.remainingDocument === 1)).toBe(true);- const contributing = calls.filter(- (c) => c.table === "invoiceSettlement" || c.table === "journalLine"- );- expect(- contributing.every((c) => c.idFilters.every((ids) => ids.length <= 100))- ).toBe(true);- expect(- contributing.every((c) =>- c.filters.some(([key, value]) => key === "companyId" && value === "co")- )- ).toBe(true);+ for (const table of ["invoiceSettlement", "journalLine"]) {+ expect(companyScoped(calls, table)).toBe(true);+ expect(+ calls+ .filter((c) => c.table === table)+ .every((c) => c.idFilters.every((ids) => ids.length <= 100))+ ).toBe(true);+ }});- it("refuses a partial balance if a later contributing page fails", async () => {++ it("refuses a partial balance when a later page fails", async () => {const { client } = clientFor({...config,salesInvoices: [{ ...invoice, totalAmount: 1002, exchangeRate: 1 }],- invoiceSettlement: Array.from({ length: 1001 }, (_, index) => ({- ...application,- id: `s${index}`- }))+ invoiceSettlement: Array.from({ length: 1001 }, (_, index) =>+ settlement({ id: `s${index}` })+ )},{ invoiceSettlement: 1000 });- const result = await service.getOpenSalesInvoicesForCustomer(- client,- "co",- "cust",- "EUR"- );- expect(result.data).toBeNull();- expect(result.error?.message).toBe("Later page failed");- });-});--it("rounds merged fractional document principal in invoice history", async () => {- const { client } = clientFor({- invoiceSettlement: [0.1, 0.2].map((amount, index) => ({- id: `s${index}`,- companyId: "co",- paymentId: "posted",- payment: { ...payment, id: "posted", paymentId: "PAY1" },- memoId: null,- targetSalesInvoiceId: "invoice",- sourceAmount: amount,- appliedAmount: amount,- discountAmount: 0,- writeOffAmount: 0,- fxGainLossAmount: 0,- targetExchangeRate: 1,- sourceExchangeRate: 1,- appliedDate: "2026-09-07",- appliedViaPaymentId: null- })),- payment: [{ ...payment, id: "posted", paymentId: "PAY1" }]+ expect(await openInvoices(client)).toEqual({+ data: null,+ error: { message: "Later page failed" }+ });});- const result = await service.getInvoiceSettlementsForInvoice(- client,- "co",- "sales",- "invoice"- );- expect(result.data?.[0]?.sourceAmount).toBe(0.3);});-it("saves a manual memo partial and then its final document cent with zero carrying base", async () => {- const highRateInvoice = {- ...invoice,- totalAmount: 160.01 / 16000,- exchangeRate: 16000- };- const memo = {- id: "memo",- companyId: "co",- status: "Posted",- direction: "Credit",- customerId: "cust",- supplierId: null,- currencyCode: "EUR",- exchangeRate: 16000,- amount: 160.01,- memoDate: "2026-09-07",- postingDate: "2026-09-07"- };- const tables = {- payment: [{ ...current, totalAmount: 0, exchangeRate: 16000 }],- salesInvoice: [highRateInvoice],- salesInvoices: [highRateInvoice],- memo: [memo],- journalLine: [{ documentId: "invoice", amount: 0.01 }]- };- const args = {- paymentId: "current",+describe("invoice settlement history", () => {+ const historyRow = (overrides: Row = {}) => ({+ id: "a",companyId: "co",- createdBy: "user",- side: "sales" as const,- appliedDate: "2026-09-07"- };- const partial = draftDb(tables);- await service.applyCreditsToInvoices(partial.db, {- ...args,- applications: [- { memoId: "memo", invoiceId: "invoice", amount: 0.01, sourceAmount: 160 }- ]- });- expect(partial.inserts[0]).toMatchObject({- appliedAmount: 0.01,- sourceAmount: 160- });- const final = draftDb({- ...tables,- invoiceSettlement: [- {- ...partial.inserts[0],- paymentId: null,- appliedViaPaymentId: "posted",- targetPurchaseInvoiceId: null,- discountAmount: 0,- writeOffAmount: 0- }- ]- });- await service.applyCreditsToInvoices(final.db, {- ...args,- applications: [- { memoId: "memo", invoiceId: "invoice", amount: 0, sourceAmount: 0.01 }- ]- });- expect(final.inserts[0]).toMatchObject({- appliedAmount: 0,- sourceAmount: 0.01,- fxGainLossAmount: 0+ paymentId: "posted",+ payment: { ...payment, id: "posted", paymentId: "PAY1" },+ memoId: null,+ targetSalesInvoiceId: "invoice",+ sourceAmount: 44,+ appliedAmount: 40,+ discountAmount: 0,+ writeOffAmount: 0,+ fxGainLossAmount: -3.33333,+ targetExchangeRate: 1.1,+ sourceExchangeRate: 1.2,+ appliedDate: "2026-09-07",+ appliedViaPaymentId: null,+ ...overrides});-});+ const history = (client: SupabaseClient<Database>) =>+ service.getInvoiceSettlementsForInvoice(client, "co", "sales", "invoice");-it.each(["sales", "purchase"] as const)(- "preserves signed original %s controls",- async (side) => {- const { client } = clientFor({- ...config,- [side === "sales" ? "salesInvoices" : "purchaseInvoices"]: [- {- ...invoice,- status: side === "sales" ? "Submitted" : "Open",- totalAmount: 90,- exchangeRate: 1- }+ it("sums funding splits under the applying payment and leaves out draft activity", async () => {+ const { client, calls } = clientFor({+ invoiceSettlement: [+ historyRow(),+ historyRow({+ id: "b",+ sourceAmount: 66,+ appliedAmount: 60,+ fxGainLossAmount: 0,+ sourceExchangeRate: 1.1+ }),+ historyRow({+ id: "c",+ paymentId: "draft",+ payment: { ...payment, status: "Draft" }+ }),+ historyRow({+ id: "d",+ paymentId: null,+ payment: null,+ memo: { id: "memo", companyId: "co", status: "Posted" },+ appliedViaPayment: { status: "Draft" },+ memoId: "memo",+ appliedViaPaymentId: "draft"+ })],- journalLine: [- { documentId: "invoice", amount: 100 },- { documentId: "invoice", amount: -10 }- ]+ payment: [+ { ...payment, id: "posted", paymentId: "PAY1" },+ { ...payment, id: "draft", status: "Draft" }+ ],+ memo: [{ id: "memo", companyId: "co", status: "Posted" }]});- const result =- side === "sales"- ? await service.getOpenSalesInvoicesForCustomer(- client,- "co",- "cust",- "EUR"- )- : await service.getOpenPurchaseInvoicesForSupplier(- client,- "co",- "supplier",- "EUR"- );+ const result = await history(client);+ expect(result.data).toHaveLength(1);expect(result.data?.[0]).toMatchObject({- balance: 90,- remainingDocument: 90- });- }-);--it("reads a legacy settlement with no document principal from its applied base", async () => {- const { client } = clientFor({- ...config,- salesInvoices: [{ ...invoice, totalAmount: 90, exchangeRate: 1 }],- invoiceSettlement: [- {- paymentId: "posted",- memoId: null,- targetSalesInvoiceId: "invoice",- sourceAmount: null,- appliedAmount: 1,- discountAmount: 0,- writeOffAmount: 0,- payment: { status: "Posted" },- memo: null,- appliedViaPayment: null- }- ]- });- const result = await service.getOpenSalesInvoicesForCustomer(- client,- "co",- "cust",- "EUR"- );- expect(result.error).toBeNull();- expect(result.data?.[0]).toMatchObject({- balance: 89,- remainingDocument: 89- });-});-it.each([-1, Number.NaN])(- "refuses invalid effective invoice principal %s",- async (sourceAmount) => {- const { client } = clientFor({- ...config,- salesInvoices: [{ ...invoice, totalAmount: 90, exchangeRate: 1 }],- invoiceSettlement: [- {- paymentId: "posted",- memoId: null,- targetSalesInvoiceId: "invoice",- sourceAmount,- appliedAmount: 1,- discountAmount: 0,- writeOffAmount: 0,- payment: { status: "Posted" },- memo: null,- appliedViaPayment: null- }- ]+ appliedAmount: 100,+ sourceAmount: 110,+ fxGainLossAmount: -3.33333});- const result = await service.getOpenSalesInvoicesForCustomer(- client,- "co",- "cust",- "EUR"- );- expect(result.data).toBeNull();- expect(result.error?.message).toMatch(/principal/i);- }-);-it("refuses excess invoice settlements instead of silently clamping the balance", async () => {- const { client } = clientFor({- ...config,- salesInvoices: [{ ...invoice, totalAmount: 90, exchangeRate: 1 }],- invoiceSettlement: [- {- paymentId: "posted",- memoId: null,- targetSalesInvoiceId: "invoice",- sourceAmount: 91,- appliedAmount: 91,- discountAmount: 0,- writeOffAmount: 0,- payment: { status: "Posted" },- memo: null,- appliedViaPayment: null- }- ]+ expect(companyScoped(calls, "invoiceSettlement")).toBe(true);});- const result = await service.getOpenSalesInvoicesForCustomer(- client,- "co",- "cust",- "EUR"- );- expect(result.data).toBeNull();- expect(result.error?.message).toMatch(/excessive settlements/i);-});-it.each(["sales", "purchase"] as const)(- "uses original IC %s controls and excludes VOID rows",- async (side) => {- const description = side === "sales" ? "IC Receivables" : "IC Payables";+ it("rounds merged fractional document principal", async () => {+ // 0.1 + 0.2 is 0.30000000000000004 in floating point.const { client } = clientFor({- ...config,- [side === "sales" ? "salesInvoices" : "purchaseInvoices"]: [- {- ...invoice,- status: side === "sales" ? "Submitted" : "Open",- totalAmount: 99,- exchangeRate: 1- }- ],- journalLine: [- { documentId: "invoice", amount: 100, description },- {- documentId: "invoice",- amount: -100,- description: `VOID: ${description}`- }- ]- });- const result =- side === "sales"- ? await service.getOpenSalesInvoicesForCustomer(- client,- "co",- "cust",- "EUR"- )- : await service.getOpenPurchaseInvoicesForSupplier(- client,- "co",- "supplier",- "EUR"- );- expect(result.data?.[0]).toMatchObject({- balance: 100,- remainingDocument: 99- });- }-);--it.each([true, false])(- "stages %s customer-ledger refund against exact memo principal with cash-direction FX",- async (isAR) => {- const { db, inserts } = draftDb({- payment: [- {- ...current,- paymentType: isAR ? "Disbursement" : "Receipt",- customerId: isAR ? "cust" : null,- supplierId: isAR ? null : "supplier",- totalAmount: 55,- exchangeRate: 1.25- }- ],- memo: [- {- id: "memo",- companyId: "co",- status: "Posted",- customerId: isAR ? "cust" : null,- supplierId: isAR ? null : "supplier",- direction: isAR ? "Credit" : "Debit",- currencyCode: "EUR",- exchangeRate: 1.1,- amount: 55- }- ],- journalLine: [{ documentId: "memo", amount: -50 }]- });- await service.replaceInvoiceSettlements(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- applications: [- {- ...draft,- targetSalesInvoiceId: undefined,- targetMemoId: "memo",- sourceAmount: 55,- sourceExchangeRate: 1.25,- appliedAmount: 50- }- ]+ invoiceSettlement: [0.1, 0.2].map((amount, index) =>+ historyRow({+ id: `s${index}`,+ sourceAmount: amount,+ appliedAmount: amount,+ fxGainLossAmount: 0,+ targetExchangeRate: 1,+ sourceExchangeRate: 1+ })+ ),+ payment: [{ ...payment, id: "posted", paymentId: "PAY1" }]});- expect(inserts).toEqual([- expect.objectContaining({- targetMemoId: "memo",- targetSalesInvoiceId: null,- targetPurchaseInvoiceId: null,- sourcePaymentId: null,- sourceAmount: 55,- appliedAmount: 50,- fxGainLossAmount: isAR ? 6 : -6,- createdBy: "user"- })- ]);- }-);--it("memo availability reserves refund document principal without subtracting refund FX from memo carrying", async () => {- const { client } = clientFor({- ...config,- memo: [- {- id: "memo",- memoId: "CR1",- companyId: "co",- status: "Posted",- direction: "Credit",- currencyCode: "EUR",- exchangeRate: 1.1,- amount: 55,- memoDate: "2026-09-07"- }- ],- invoiceSettlement: [- {- memoId: null,- targetMemoId: "memo",- paymentId: "refund",- sourceAmount: 22,- appliedAmount: 20,- fxGainLossAmount: 2.4,- payment: { status: "Posted" },- appliedViaPaymentId: null- }- ]- });- const result = await service.getAvailableCreditsForParty(- client,- "co",- { side: "sales", customerId: "cust" },- undefined,- "EUR"- );- expect(result.data?.[0]).toMatchObject({- remainingDocument: 33,- remaining: 30+ expect((await history(client)).data?.[0]?.sourceAmount).toBe(0.3);});});@@ -1439,118 +1203,8 @@ it("changing a draft payment to a supplier clears its former customer", async ()expect(saved).toMatchObject({ customerId: null, supplierId: "supplier" });});-it.each([- ["party", { supplierId: "other" }, {}],- ["currency", { currencyCode: "USD" }, {}],- ["direction", { direction: "Credit" }, {}],- ["memo status", { status: "Draft" }, {}],- ["adjustments", {}, { discountAmount: 1 }],- ["over-refund", {}, { sourceAmount: 56 }],- [- "invoice target",- {},- { targetMemoId: undefined, targetPurchaseInvoiceId: "invoice" }- ]-])(- "rejects invalid supplier refund %s without replacing applications",- async (_label, memoOverride, appOverride) => {- const { db, inserts, deletes } = draftDb({- payment: [- {- ...current,- paymentType: "Receipt",- customerId: null,- supplierId: "supplier",- totalAmount: 100,- exchangeRate: 1.25- }- ],- memo: [- {- id: "memo",- companyId: "co",- status: "Posted",- supplierId: "supplier",- customerId: null,- direction: "Debit",- currencyCode: "EUR",- exchangeRate: 1.1,- amount: 55,- ...memoOverride- }- ]- });- await expect(- service.replaceInvoiceSettlements(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- applications: [- {- ...draft,- targetSalesInvoiceId: undefined,- targetMemoId: "memo",- sourceAmount: 55,- sourceExchangeRate: 1.25,- appliedAmount: 50,- ...appOverride- }- ]- })- ).rejects.toThrow();- expect(inserts).toEqual([]);- expect(deletes).toEqual([]);- }-);--it("a fully refunded memo cannot also fund an invoice", async () => {- const { db, inserts } = draftDb({- payment: [{ ...current, totalAmount: 0, exchangeRate: 1.1 }],- memo: [- {- id: "memo",- companyId: "co",- status: "Posted",- customerId: "cust",- direction: "Credit",- currencyCode: "EUR",- exchangeRate: 1.1,- amount: 55- }- ],- invoiceSettlement: [- {- memoId: null,- targetMemoId: "memo",- paymentId: "refund",- sourceAmount: 55,- appliedAmount: 50,- fxGainLossAmount: 6- }- ]- });- await expect(- service.applyCreditsToInvoices(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- side: "sales",- appliedDate: "2026-09-07",- applications: [- { memoId: "memo", invoiceId: "invoice", amount: 50, sourceAmount: 55 }- ]- })- ).rejects.toThrow(/remaining funding balance/);- expect(inserts).toEqual([]);-});-describe("customer deposits fund only their own document", () => {const deposit = { ...payment, id: "deposit", rentalAgreementId: "ra-1" };- const agreement = {- id: "ra-1",- companyId: "co",- rentalAgreementId: "RA000001"- };const billsAgreement = (rentalAgreementId: string) => ({salesInvoiceLine: [{@@ -1567,14 +1221,9 @@ describe("customer deposits fund only their own document", () => {payment: [{ ...current, totalAmount: 0 }, deposit],...billsAgreement("ra-3")});- await expect(- service.replaceInvoiceSettlements(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- applications: [draft]- })- ).rejects.toThrow("Insufficient payment funding for target: invoice");+ await expect(replace(db, [draft])).rejects.toThrow(+ "Insufficient payment funding for target: invoice"+ );expect(deletes).toEqual([]);expect(inserts).toEqual([]);});@@ -1584,12 +1233,7 @@ describe("customer deposits fund only their own document", () => {payment: [{ ...current, totalAmount: 0 }, deposit],...billsAgreement("ra-1")});- await service.replaceInvoiceSettlements(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- applications: [draft]- });+ await replace(db, [draft]);expect(inserts).toEqual([expect.objectContaining({sourcePaymentId: "deposit",@@ -1599,26 +1243,19 @@ describe("customer deposits fund only their own document", () => {]);});- it("refuses a deposit payment applied to another agreement's invoice, naming it", async () => {+ it("refuses a deposit payment applied to another agreement's invoice", async () => {const { db, inserts } = draftDb({payment: [{ ...current, rentalAgreementId: "ra-1" }],- rentalAgreement: [agreement],+ rentalAgreement: [+ { id: "ra-1", companyId: "co", rentalAgreementId: "RA000001" }+ ],...billsAgreement("ra-3")});- await expect(- service.replaceInvoiceSettlements(db, {- paymentId: "current",- companyId: "co",- createdBy: "user",- applications: [draft]- })- ).rejects.toThrow(- "A deposit for RA000001 can only be applied to that agreement's invoices"- );+ await expect(replace(db, [draft])).rejects.toThrow(/RA000001/);expect(inserts).toEqual([]);});- it("keeps deposits out of on-account credit totals but returns them scoped", async () => {+ it("keeps deposits out of on-account totals but lists them with their scope", async () => {const { client } = clientFor({...config,payment: [@@ -1631,14 +1268,10 @@ describe("customer deposits fund only their own document", () => {}]});- const result = await service.getAvailableOnAccountCreditSources(- client,- "co",- { paymentType: "Receipt", customerId: "cust" },- "EUR"- );+ const result = await onAccountSources(client);expect(result.data?.availableDocumentAmount).toBe(110);expect(result.data?.availableBaseAmount).toBe(100);+ expect(result.data?.sources[0]).not.toHaveProperty("scope");expect(result.data?.sources).toEqual([expect.objectContaining({ paymentId: "prior" }),expect.objectContaining({@@ -1647,7 +1280,6 @@ describe("customer deposits fund only their own document", () => {scope: { type: "rentalAgreement", id: "ra-1", readableId: "RA000001" }})]);- expect(result.data?.sources[0]).not.toHaveProperty("scope");expect(await service.getAvailableOnAccountCredit(client, "co", {paymentType: "Receipt",@@ -1669,13 +1301,7 @@ describe("customer deposits fund only their own document", () => {}]});- const result = await service.getOpenSalesInvoicesForCustomer(- client,- "co",- "cust",- "EUR"- );- expect(result.data?.[0]).toMatchObject({+ expect((await openInvoices(client)).data?.[0]).toMatchObject({rentalAgreementIds: ["ra-1"],salesOrderIds: ["so-1"]});diff --git a/apps/erp/app/modules/invoicing/ui/Payment/AvailableCreditsTable.tsx b/apps/erp/app/modules/invoicing/ui/Payment/AvailableCreditsTable.tsxindex 0ded0a7c86..ef370c7f72 100644--- a/apps/erp/app/modules/invoicing/ui/Payment/AvailableCreditsTable.tsx+++ b/apps/erp/app/modules/invoicing/ui/Payment/AvailableCreditsTable.tsx@@ -20,12 +20,7 @@ import {SelectTrigger,SelectValue} from "@carbon/react";-import {- INPUT_FORMAT,- round,- toBaseAmount,- toDocumentAmount-} from "@carbon/utils";+import { INPUT_FORMAT } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { useCallback, useMemo, useState } from "react";import { LuSave } from "react-icons/lu";@@ -37,26 +32,17 @@ import {usePermissions} from "~/hooks";import { path } from "~/utils/path";--// An available credit (a posted, balance-reducing memo) the party can apply to an-// open invoice alongside the cash payment.-type AvailableCredit = {- id: string;- memoId: string;- direction: string;- currencyCode: string;- exchangeRate: number;- remaining: number;- remainingDocument: number;-};--type OpenInvoiceOption = {- id: string;- invoiceId: string;- exchangeRate: number;- balance: number;- remainingDocument: number;-};+import {+ type AvailableCredit,+ buildCreditApplications,+ type CreditRow,+ changeCreditInvoice,+ type OpenInvoiceOption,+ type StagedCredit,+ seedCreditRows,+ toggleCreditRow,+ updateCreditAmount+} from "./payment-logic";type AvailableCreditsTableProps = {paymentId: string;@@ -69,25 +55,7 @@ type AvailableCreditsTableProps = {openInvoices: OpenInvoiceOption[];// Credit applications already staged on this (Draft) payment — pre-fills the// table so a staged credit shows as selected instead of vanishing.- staged?: {- memoId: string;- invoiceId: string;- amount: number;- sourceAmount?: number | null;- }[];-};--type CreditRow = {- id: string;- memoId: string;- direction: string;- remaining: number;- remainingDocument: number;- checked: boolean;- invoiceId: string; // target invoice id- amount: number;- sourceAmount: number;- exchangeRate: number;+ staged?: StagedCredit[];};const GRID =@@ -118,101 +86,28 @@ const AvailableCreditsTable = ({[openInvoices]);- // staged is keyed by the memo's row id (== credit.id).- const stagedByMemo = useMemo(- () => new Map(staged.map((s) => [s.memoId, s])),- [staged]- );const seed = useMemo<CreditRow[]>(- () =>- credits.map((c) => {- const s = stagedByMemo.get(c.id);- return {- id: c.id,- memoId: c.memoId,- direction: c.direction,- remaining: c.remaining,- remainingDocument: c.remainingDocument,- exchangeRate: c.exchangeRate,- checked: Boolean(s),- invoiceId:- s?.invoiceId ??- openInvoices.find((i) => i.exchangeRate === c.exchangeRate)?.id ??- "",- amount: s?.amount ?? 0,- sourceAmount:- s?.sourceAmount ??- (s- ? toDocumentAmount(s.amount, c.exchangeRate, documentDecimals)- : 0)- };- }),- [credits, openInvoices, stagedByMemo, documentDecimals]+ () => seedCreditRows(credits, openInvoices, staged, documentDecimals),+ [credits, openInvoices, staged, documentDecimals]);const [rows, setRows] = useState<CreditRow[]>(seed);- const capFor = useCallback(- (row: CreditRow, invoiceId: string) => {- const invoice = balanceByInvoice.get(invoiceId);- if (!invoice || invoice.exchangeRate !== row.exchangeRate)- return { amount: 0, sourceAmount: 0 };- const sourceAmount = Math.min(- row.remainingDocument,- invoice.remainingDocument- );- const amount =- sourceAmount === invoice.remainingDocument- ? invoice.balance- : sourceAmount === row.remainingDocument- ? row.remaining- : toBaseAmount(sourceAmount, row.exchangeRate);- return { amount, sourceAmount };- },- [balanceByInvoice]- );const toggleRow = useCallback((id: string, checked: boolean) =>- setRows((prev) =>- prev.map((r) =>- r.id !== id- ? r- : {- ...r,- checked,- ...(checked- ? capFor(r, r.invoiceId)- : { amount: 0, sourceAmount: 0 })- }- )- ),- [capFor]+ setRows((prev) => toggleCreditRow(prev, id, checked, balanceByInvoice)),+ [balanceByInvoice]);const updateInvoice = useCallback((id: string, invoiceId: string) =>setRows((prev) =>- prev.map((r) =>- r.id !== id- ? r- : { ...r, invoiceId, ...(r.checked ? capFor(r, invoiceId) : {}) }- )+ changeCreditInvoice(prev, id, invoiceId, balanceByInvoice)),- [capFor]+ [balanceByInvoice]);const updateAmount = useCallback((id: string, value: number) =>- setRows((prev) =>- prev.map((r) => {- if (r.id !== id) return r;- const amount = round(Math.max(0, value));- const sourceAmount = toDocumentAmount(- amount,- r.exchangeRate,- documentDecimals- );- return { ...r, amount, sourceAmount, checked: sourceAmount > 0 };- })- ),+ setRows((prev) => updateCreditAmount(prev, id, value, documentDecimals)),[documentDecimals]);@@ -222,14 +117,7 @@ const AvailableCreditsTable = ({);const onSave = () => {- const applications = rows- .filter((r) => r.checked && r.sourceAmount > 0 && r.invoiceId)- .map((r) => ({- memoId: r.id,- invoiceId: r.invoiceId,- amount: r.amount,- sourceAmount: r.sourceAmount- }));+ const applications = buildCreditApplications(rows);const formData = new FormData();formData.set("applications", JSON.stringify(applications));diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplications.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplications.tsxindex 1644b8b451..aaec0f4d74 100644--- a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplications.tsx+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplications.tsx@@ -20,12 +20,12 @@ import { Trans } from "@lingui/react/macro";import { useNumberFormatter } from "@react-aria/i18n";import { DateTime, Hyperlink } from "~/components";import { useCurrencyFormatter } from "~/hooks";-import type { getInvoiceSettlements } from "~/modules/invoicing/invoicing.service";import { path } from "~/utils/path";--type PaymentApplication = NonNullable<- Awaited<ReturnType<typeof getInvoiceSettlements>>["data"]->[number];+import {+ aggregateApplications,+ type PaymentApplication,+ unappliedPaymentCash+} from "./payment-logic";type PaymentApplicationsProps = {isRefund?: boolean;@@ -92,52 +92,13 @@ const PaymentApplications = ({}: PaymentApplicationsProps) => {const currencyFormatter = useCurrencyFormatter({ currency: baseCurrency });const documentFormatter = useCurrencyFormatter({ currency: paymentCurrency });- const byInvoice = new Map<- string,- PaymentApplication & { sourceRates: number[] }- >();- for (const a of splits) {- const id =- a.targetSalesInvoiceId ??- a.targetPurchaseInvoiceId ??- a.targetMemoId ??- a.targetReimbursementId ??- a.id;- const existing = byInvoice.get(id);- if (!existing) {- byInvoice.set(id, { ...a, sourceRates: [Number(a.sourceExchangeRate)] });- continue;- }- existing.appliedAmount = round(- existing.appliedAmount + Number(a.appliedAmount)- );- existing.discountAmount = round(- existing.discountAmount + Number(a.discountAmount)- );- existing.writeOffAmount = round(- existing.writeOffAmount + Number(a.writeOffAmount)- );- existing.sourceAmount =- (existing.sourceAmount ?? 0) + Number(a.sourceAmount ?? 0);- existing.fxGainLossAmount = round(- Number(existing.fxGainLossAmount ?? 0) + Number(a.fxGainLossAmount ?? 0)- );- existing.sourceRates = [- ...new Set([...existing.sourceRates, Number(a.sourceExchangeRate)])- ];- }- const applications = [...byInvoice.values()];+ const applications = aggregateApplications(splits);const rateFormatter = useNumberFormatter(SCALE_FORMAT);const total = (field: "appliedAmount" | "discountAmount" | "writeOffAmount") => round(applications.reduce((sum, a) => sum + Number(a[field]), 0));- const unapplied =- paymentTotal -- splits.reduce(- (s, a) => s + (a.sourcePaymentId ? 0 : Number(a.sourceAmount ?? 0)),- 0- );+ const unapplied = unappliedPaymentCash(paymentTotal, splits);// Discount and write-off only exist on a trade invoice settlement.const hasAdjustments = !isRefund && !isReimbursement;diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.test.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.test.tsxdeleted file mode 100644index 7634634ff3..0000000000--- a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.test.tsx+++ /dev/null@@ -1,793 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import type { ReactNode } from "react";-import { createElement } from "react";-import { renderToStaticMarkup } from "react-dom/server";-import { beforeEach, describe, expect, it, vi } from "vitest";--const harness = vi.hoisted(() => ({- submit: vi.fn(),- buttons: [] as {- children: ReactNode;- onClick?: () => void;- isDisabled?: boolean;- }[],- amounts: [] as {- "aria-label"?: string;- onChange?: (value: number) => void;- }[],- checkboxes: [] as { onCheckedChange?: (checked: boolean) => void }[],- state: undefined as unknown-}));-vi.mock("react", async (importOriginal) => {- const react = await importOriginal<typeof import("react")>();- return {- ...react,- useState: (seed: unknown) => {- if (harness.state === undefined)- harness.state = typeof seed === "function" ? seed() : seed;- return [- harness.state,- (value: unknown) => {- harness.state =- typeof value === "function" ? value(harness.state) : value;- }- ];- }- };-});-vi.mock("@carbon/react", () => {- const Box = ({ children }: { children: ReactNode }) =>- createElement("div", null, children);- return {- Button: (props: {- children: ReactNode;- onClick?: () => void;- isDisabled?: boolean;- }) => {- harness.buttons.push(props);- return createElement("button", null, props.children);- },- Select: Box,- SelectContent: Box,- SelectItem: Box,- SelectTrigger: Box,- SelectValue: Box,- Table: Box,- Tbody: Box,- Td: Box,- Tfoot: Box,- Th: Box,- Thead: Box,- Tr: Box,- Card: Box,- CardContent: Box,- CardDescription: Box,- CardFooter: Box,- CardHeader: Box,- CardTitle: Box,- HStack: Box,- Checkbox: (props: { onCheckedChange?: (checked: boolean) => void }) => {- harness.checkboxes.push(props);- return null;- },- NumberField: (props: {- value: number;- formatOptions: Intl.NumberFormatOptions;- "aria-label"?: string;- onChange?: (value: number) => void;- }) => {- harness.amounts.push(props);- return createElement(- "output",- null,- new Intl.NumberFormat("en-US", props.formatOptions).format(props.value)- );- },- NumberInput: Box,- NumberInputGroup: Box,- cn: (...args: unknown[]) =>- args.filter((x) => typeof x === "string").join(" ")- };-});-vi.mock("@lingui/react/macro", () => ({- Trans: ({ children }: { children: ReactNode }) => children,- useLingui: () => ({- t: (parts: TemplateStringsArray, ...values: unknown[]) =>- parts.reduce((s, p, i) => s + p + (values[i] ?? ""), "")- })-}));-vi.mock("react-router", () => ({- generatePath: (s: string) => s,- useFetcher: () => ({ state: "idle", submit: harness.submit })-}));-vi.mock("~/components", () => ({- DateTime: () => null,- Hyperlink: ({ children }: { children: ReactNode }) => children-}));-vi.mock("~/components/Enumerable", () => ({ Enumerable: () => null }));-vi.mock("@react-aria/i18n", () => ({- useLocale: () => ({ locale: "en-US" }),- useNumberFormatter: () => new Intl.NumberFormat("en-US")-}));-// The apply table edits its amounts in a Grid through EditableNumber cells.-// The Grid stand-in renders every cell and registers each editable cell as an-// amount input labelled like the column ("Applied amount for INV1"), whose-// onChange commits through the cell's own update callback.-type CellUpdate = (key: string, value: string, row: unknown) => unknown;-vi.mock("~/components/Editable", () => ({- EditableNumber: (onUpdate: CellUpdate) => ({ onUpdate })-}));-vi.mock("~/components/Grid", () => {- const labels: Record<string, string> = {- appliedAmount: "Applied amount",- discountAmount: "Discount",- writeOffAmount: "Write-off"- };- type Row = { id: string; invoiceId: string };- type Column = {- accessorKey?: string;- cell?: (ctx: { row: { original: Row } }) => ReactNode;- };- return {- default: ({- data,- columns,- canEdit,- editableComponents- }: {- data: Row[];- columns: Column[];- canEdit: boolean;- editableComponents: Record<string, { onUpdate: CellUpdate }>;- }) =>- createElement(- "div",- null,- data.map((row) => {- if (canEdit) {- // Like the Grid, only a shown column's editor is reachable.- for (const { accessorKey: key } of columns) {- const editor = key ? editableComponents[key] : undefined;- if (!key || !editor) continue;- harness.amounts.push({- "aria-label": `${labels[key]} for ${row.invoiceId}`,- onChange: (value: number) =>- void editor.onUpdate(key, String(value), row)- });- }- }- return createElement(- "div",- { key: row.id },- columns.map((column, i) =>- createElement(- "span",- { key: i },- column.cell?.({ row: { original: row } })- )- )- );- })- )- };-});-vi.mock("~/hooks", () => ({- usePermissions: () => ({ can: () => true }),- useCompanyToday: () => ({ toString: () => "2026-09-07" }),- useCurrencyDecimals: () => 2,- useCurrencyFormatter: ({ currency = "USD" } = {}) =>- new Intl.NumberFormat("en-US", { style: "currency", currency })-}));--import AvailableCreditsTable from "./AvailableCreditsTable";-import PaymentApplications from "./PaymentApplications";-import PaymentApplyTable from "./PaymentApplyTable";--const props = {- paymentId: "current",- paymentType: "Receipt" as const,- paymentCurrency: "EUR",- baseCurrency: "USD",- currencyDecimals: 2,- paymentTotal: 170,- paymentExchangeRate: 1.2,- availableCredit: 0,- priorSources: [],- openInvoices: [- {- id: "one",- invoiceId: "INV1",- dateDue: null,- currencyCode: "EUR",- exchangeRate: 1.1,- totalAmount: 100,- balance: 100,- remainingDocument: 110,- status: "Submitted"- },- {- id: "two",- invoiceId: "INV2",- dateDue: null,- currencyCode: "EUR",- exchangeRate: 1.2,- totalAmount: 50,- balance: 50,- remainingDocument: 60,- status: "Submitted"- }- ],- existingApplications: []-};-function render(overrides = {}) {- harness.buttons = [];- harness.amounts = [];- harness.checkboxes = [];- return renderToStaticMarkup(- createElement(PaymentApplyTable, { ...props, ...overrides })- );-}-function click(label: string) {- const button = harness.buttons.find((b) =>- renderToStaticMarkup(createElement("span", null, b.children)).includes(- label- )- );- expect(button).toBeDefined();- button?.onClick?.();-}-function editAmount(label: string, value: number) {- const field = harness.amounts.find((input) => input["aria-label"] === label);- expect(field).toBeDefined();- field?.onChange?.(value);-}-function savedApplications() {- click("Save applications");- const formData = harness.submit.mock.calls.at(-1)?.[0] as FormData;- expect(formData).toBeInstanceOf(FormData);- return JSON.parse(String(formData.get("applications")));-}-beforeEach(() => {- harness.state = undefined;- harness.buttons = [];- harness.amounts = [];- harness.checkboxes = [];- harness.submit.mockClear();-});-describe("payment composer document funding", () => {- it.each(["Receipt", "Disbursement"])(- "applies %s refunds to memos and reopens exact principal",- (paymentType) => {- const overrides = {- paymentType,- isRefund: true,- paymentTotal: 110,- openInvoices: [props.openInvoices[0]]- };- const html = render(overrides);- expect(html).toContain("Refund memos");- expect(harness.amounts).toHaveLength(1);- click("Auto apply");- render(overrides);- const apps = savedApplications();- expect(apps).toEqual([- expect.objectContaining({- targetMemoId: "one",- appliedAmount: 100,- sourceAmount: 110- })- ]);- expect(apps[0]).not.toHaveProperty("targetSalesInvoiceId");- expect(apps[0]).not.toHaveProperty("targetPurchaseInvoiceId");- harness.state = undefined;- render({ ...overrides, existingApplications: apps });- expect(savedApplications()).toEqual(apps);- }- );- it("applies an employee disbursement to reimbursements without discount or write-off", () => {- const overrides = {- paymentType: "Disbursement" as const,- isReimbursement: true,- paymentTotal: 110,- openInvoices: [props.openInvoices[0]]- };- const html = render(overrides);- expect(html).toContain("Apply to reimbursements");- // One amount input, not three — there is no negotiated settlement with an- // employee, and `replaceInvoiceSettlements` refuses a non-zero adjustment.- expect(harness.amounts).toHaveLength(1);- click("Auto apply");- render(overrides);- const apps = savedApplications();- expect(apps).toEqual([- expect.objectContaining({- targetReimbursementId: "one",- appliedAmount: 100,- sourceAmount: 110,- discountAmount: 0,- writeOffAmount: 0- })- ]);- expect(apps[0]).not.toHaveProperty("targetSalesInvoiceId");- expect(apps[0]).not.toHaveProperty("targetPurchaseInvoiceId");- expect(apps[0]).not.toHaveProperty("targetMemoId");- // Reopening the draft seeds from targetReimbursementId and resaves as-is.- harness.state = undefined;- render({ ...overrides, existingApplications: apps });- expect(savedApplications()).toEqual(apps);- });-- const highRate = {- paymentTotal: 0,- paymentExchangeRate: 16000,- availableCredit: 160.01,- priorSources: [- {- paymentId: "prior",- postingDate: "2026-09-01",- exchangeRate: 16000,- remainingDocument: 160.01,- remainingBase: 0.01- }- ],- openInvoices: [- {- ...props.openInvoices[0],- exchangeRate: 16000,- totalAmount: 0.01,- balance: 0.01,- remainingDocument: 160.01- }- ]- };- const highRateApplication = {- targetSalesInvoiceId: "one",- targetPurchaseInvoiceId: null,- appliedAmount: 0.01,- sourceAmount: 160.01,- discountAmount: 0,- writeOffAmount: 0,- targetExchangeRate: 16000,- sourceExchangeRate: 16000,- appliedDate: "2026-09-07"- };-- it.each([false, true])(- "manual base .01 consumes160.00 and preserves a document cent (reopened:%s)",- (reopened) => {- const overrides = {- ...highRate,- existingApplications: reopened ? [highRateApplication] : []- };- render(overrides);- editAmount("Applied amount for INV1", 0.01);- render(overrides);- expect(savedApplications()).toEqual([- expect.objectContaining({ appliedAmount: 0.01, sourceAmount: 160 })- ]);- }- );-- it.each(["Discount", "Write-off"])(- "%s zero edit does not promote a rounded partial amount to full document relief",- (label) => {- const overrides = {- ...highRate,- existingApplications: [{ ...highRateApplication, sourceAmount: 160 }]- };- render(overrides);- editAmount(`${label} for INV1`, 0);- render(overrides);- expect(savedApplications()).toEqual([- expect.objectContaining({- appliedAmount: 0.01,- sourceAmount: 160,- discountAmount: 0,- writeOffAmount: 0- })- ]);- }- );-- it.each(["checkbox", "Auto apply"])(- "%s retains all160.01 source units for an exact full application",- (selection) => {- render(highRate);- if (selection === "checkbox")- harness.checkboxes[0]?.onCheckedChange?.(true);- else click(selection);- render(highRate);- expect(savedApplications()).toEqual([- expect.objectContaining({ appliedAmount: 0.01, sourceAmount: 160.01 })- ]);- }- );-- it.each(["checkbox", "Auto apply"])(- "%s retains the final document cent even when its carrying base is zero",- (selection) => {- const overrides = {- ...highRate,- availableCredit: 0.01,- priorSources: [- {- ...highRate.priorSources[0],- remainingDocument: 0.01,- remainingBase: 0- }- ],- openInvoices: [- { ...highRate.openInvoices[0], remainingDocument: 0.01, balance: 0 }- ]- };- render(overrides);- if (selection === "checkbox")- harness.checkboxes[0]?.onCheckedChange?.(true);- else click(selection);- render(overrides);- expect(savedApplications()).toEqual([- expect.objectContaining({ appliedAmount: 0, sourceAmount: 0.01 })- ]);- }- );-- it("discount and write-off edits still reduce cash on an exact full selection", () => {- render();- harness.checkboxes[0]?.onCheckedChange?.(true);- render();- editAmount("Discount for INV1", 10);- render();- editAmount("Write-off for INV1", 5);- render();- expect(savedApplications()).toEqual([- expect.objectContaining({- appliedAmount: 85,- sourceAmount: 93.5,- discountAmount: 10,- writeOffAmount: 5- })- ]);- });-- it("auto applies 170 EUR to invoices carrying 100 and 50 USD at distinct snapshots", () => {- render();- click("Auto apply");- const html = render();- expect(html).toContain("$100.00");- expect(html).toContain("$50.00");- expect(html).toContain("€110.00");- expect(html).toContain("€60.00");- click("Save applications");- const submitted = harness.submit.mock.calls[0][0] as FormData;- expect(JSON.parse(String(submitted.get("applications")))).toEqual([- expect.objectContaining({- targetSalesInvoiceId: "one",- appliedAmount: 100,- sourceAmount: 110,- targetExchangeRate: 1.1,- sourceExchangeRate: 1.2- }),- expect.objectContaining({- targetSalesInvoiceId: "two",- appliedAmount: 50,- sourceAmount: 60,- targetExchangeRate: 1.2,- sourceExchangeRate: 1.2- })- ]);- });- it("aggregates reopened funding splits into one invoice and resaves exact principal", () => {- const existingApplications = [- {- targetSalesInvoiceId: "one",- targetPurchaseInvoiceId: null,- appliedAmount: 40,- discountAmount: 0,- writeOffAmount: 0,- sourceAmount: 44,- sourcePaymentId: null,- targetExchangeRate: 1.1,- sourceExchangeRate: 1.2,- appliedDate: "2026-09-07"- },- {- targetSalesInvoiceId: "one",- targetPurchaseInvoiceId: null,- appliedAmount: 60,- discountAmount: 0,- writeOffAmount: 0,- sourceAmount: 66,- sourcePaymentId: "prior",- targetExchangeRate: 1.1,- sourceExchangeRate: 1.1,- appliedDate: "2026-09-07"- }- ];- const html = render({ existingApplications });- expect(html).toContain("$100.00");- click("Save applications");- const submitted = harness.submit.mock.calls[0][0] as FormData;- expect(JSON.parse(String(submitted.get("applications")))).toEqual([- expect.objectContaining({- appliedAmount: 100,- sourceAmount: 110,- sourceExchangeRate: 1.2- })- ]);- });- it("auto applies a prior document cent on a zero-cash draft even when base rounds to zero", () => {- const overrides = {- paymentTotal: 0,- paymentExchangeRate: 100000,- availableCredit: 0.01,- priorSources: [- {- paymentId: "prior",- postingDate: "2026-09-01",- exchangeRate: 100000,- remainingDocument: 0.01,- remainingBase: 0- }- ],- openInvoices: [- {- ...props.openInvoices[0],- exchangeRate: 100000,- totalAmount: 0.0000001,- balance: 0,- remainingDocument: 0.01- }- ]- };- render(overrides);- click("Auto apply");- render(overrides);- click("Save applications");- const submitted = harness.submit.mock.calls[0][0] as FormData;- expect(JSON.parse(String(submitted.get("applications")))).toEqual([- expect.objectContaining({ appliedAmount: 0, sourceAmount: 0.01 })- ]);- });-});--describe("customer deposits fund only their own document", () => {- const ra1 = { type: "rentalAgreement" as const, id: "ra-1" };- const scoped = {- paymentTotal: 0,- priorSources: [- {- paymentId: "deposit",- postingDate: "2026-09-01",- exchangeRate: 1.2,- remainingDocument: 60,- remainingBase: 50,- scope: { ...ra1, readableId: "RA000001" }- }- ],- openInvoices: [- { ...props.openInvoices[0], rentalAgreementIds: ["ra-3"] },- { ...props.openInvoices[1], rentalAgreementIds: ["ra-1"] }- ]- };-- it("lists a deposit apart from on-account credit and auto applies it only to its agreement's invoice", () => {- const html = render(scoped);- expect(html).toContain("Deposit for RA000001 (its invoices only)");- expect(html).not.toContain("On-account credit available");- click("Auto apply");- render(scoped);- expect(savedApplications()).toEqual([- expect.objectContaining({- targetSalesInvoiceId: "two",- appliedAmount: 50,- sourceAmount: 60- })- ]);- });-- it("selecting another document's invoice draws nothing from the deposit", () => {- render(scoped);- harness.checkboxes[0]?.onCheckedChange?.(true);- render(scoped);- harness.checkboxes[1]?.onCheckedChange?.(true);- render(scoped);- expect(savedApplications()).toEqual([- expect.objectContaining({ targetSalesInvoiceId: "two", sourceAmount: 60 })- ]);- });-- it("a deposit payment lists only its document's invoices and refuses an application to another", () => {- const deposit = {- paymentScope: { ...ra1, readableId: "RA000001" },- openInvoices: scoped.openInvoices- };- const html = render(deposit);- expect(html).toContain("INV2");- expect(html).not.toContain("INV1");- harness.state = undefined;- const refused = render({- ...deposit,- existingApplications: [- {- targetSalesInvoiceId: "one",- targetPurchaseInvoiceId: null,- appliedAmount: 100,- discountAmount: 0,- writeOffAmount: 0,- sourceAmount: 110,- targetExchangeRate: 1.1,- sourceExchangeRate: 1.2,- appliedDate: "2026-09-07"- }- ]- });- expect(refused).toContain(- "A deposit for RA000001 can only be applied to that agreement's invoices"- );- const save = harness.buttons.find((b) =>- renderToStaticMarkup(createElement("span", null, b.children)).includes(- "Save applications"- )- );- expect(save?.isDisabled).toBe(true);- });-});--it("displays staged memo base and document amounts and retains a zero-base document cent", () => {- const html = renderToStaticMarkup(- createElement(AvailableCreditsTable, {- paymentId: "current",- side: "sales",- currency: "USD",- documentCurrency: "EUR",- documentDecimals: 2,- credits: [- {- id: "m",- memoId: "CM1",- direction: "Credit",- currencyCode: "EUR",- exchangeRate: 100000,- remaining: 0,- remainingDocument: 0.01- }- ],- openInvoices: [- {- id: "i",- invoiceId: "INV",- exchangeRate: 100000,- balance: 0,- remainingDocument: 0.01- }- ],- staged: [{ memoId: "m", invoiceId: "i", amount: 0, sourceAmount: 0.01 }]- })- );- expect(html).toContain("€0.01");- expect(html).toContain("$0.00");- click("Apply credits");- expect(- JSON.parse(- String((harness.submit.mock.calls[0][0] as FormData).get("applications"))- )- ).toEqual([{ memoId: "m", invoiceId: "i", amount: 0, sourceAmount: 0.01 }]);-});-it("payment history aggregates invoice splits and subtracts only current document cash from unapplied", () => {- const app = {- id: "a",- targetSalesInvoiceId: "one",- salesInvoice: { invoiceId: "INV1" },- appliedAmount: 40,- discountAmount: 0,- writeOffAmount: 0,- sourceAmount: 44,- sourcePaymentId: null,- targetExchangeRate: 1.1,- sourceExchangeRate: 1.2,- fxGainLossAmount: -3.33333,- appliedDate: "2026-09-07"- };- const html = renderToStaticMarkup(- createElement(PaymentApplications, {- paymentTotal: 44,- paymentCurrency: "EUR",- baseCurrency: "USD",- applications: [- app,- {- ...app,- id: "b",- appliedAmount: 60,- sourceAmount: 66,- sourcePaymentId: "prior",- sourceExchangeRate: 1.1,- fxGainLossAmount: 0- }- ] as any- })- );- expect(html.match(/INV1/g)).toHaveLength(1);- expect(html).toContain("$100.00");- expect(html).toContain("€0.00");- expect(html).toContain("€110.00");-});--const memoHighRateProps = {- paymentId: "current",- side: "sales" as const,- currency: "USD",- documentCurrency: "EUR",- documentDecimals: 2,- credits: [- {- id: "m",- memoId: "CM1",- direction: "Credit",- currencyCode: "EUR",- exchangeRate: 16000,- remaining: 0.01,- remainingDocument: 160.01- }- ],- openInvoices: [- {- id: "i",- invoiceId: "INV",- exchangeRate: 16000,- balance: 0.01,- remainingDocument: 160.01- }- ]-};-it.each([false, true])(- "manual memo base .01 preserves a document cent (reopened: %s)",- (reopened) => {- const creditProps = {- ...memoHighRateProps,- staged: reopened- ? [{ memoId: "m", invoiceId: "i", amount: 0.01, sourceAmount: 160.01 }]- : []- };- renderToStaticMarkup(createElement(AvailableCreditsTable, creditProps));- expect(harness.amounts).toHaveLength(1);- harness.amounts[0]?.onChange?.(0.01);- harness.buttons = [];- renderToStaticMarkup(createElement(AvailableCreditsTable, creditProps));- click("Apply credits");- const submitted = harness.submit.mock.calls.at(-1)?.[0] as FormData;- expect(JSON.parse(String(submitted.get("applications")))).toEqual([- { memoId: "m", invoiceId: "i", amount: 0.01, sourceAmount: 160 }- ]);- }-);-it("full memo checkbox selection retains the exact document remainder", () => {- renderToStaticMarkup(createElement(AvailableCreditsTable, memoHighRateProps));- harness.checkboxes[0]?.onCheckedChange?.(true);- harness.buttons = [];- renderToStaticMarkup(createElement(AvailableCreditsTable, memoHighRateProps));- click("Apply credits");- const submitted = harness.submit.mock.calls.at(-1)?.[0] as FormData;- expect(JSON.parse(String(submitted.get("applications")))).toEqual([- { memoId: "m", invoiceId: "i", amount: 0.01, sourceAmount: 160.01 }- ]);-});-it("shows an empty state when every supplied invoice is filtered out", () => {- const html = render({- openInvoices: [- { ...props.openInvoices[0], currencyCode: "USD" },- { ...props.openInvoices[1], remainingDocument: 0 }- ]- });- expect(html).toContain("No open invoices");- expect(harness.amounts).toHaveLength(0);- const autoApply = harness.buttons.find((b) =>- renderToStaticMarkup(createElement("span", null, b.children)).includes(- "Auto apply"- )- );- expect(autoApply?.isDisabled).toBe(true);-});diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsxindex f3155982f0..fd661c5c1b 100644--- a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx@@ -20,7 +20,6 @@ import {type FundingScope,type FundingSource,formatDate,- fundableDocumentAmounts,fundingScopeCovers,INPUT_FORMAT,round,@@ -44,59 +43,18 @@ import {usePermissions} from "~/hooks";import { path } from "~/utils/path";--// One row in the apply table — an open invoice for the payment's-// counterparty, plus the user's selection + entered amounts.-type OpenInvoice = {- id: string;- invoiceId: string;- dateDue: string | null;- currencyCode: string;- exchangeRate: number;- totalAmount: number;- balance: number;- remainingDocument: number;- status: string | null;- // The documents the invoice bills: a customer deposit funds only invoices of- // its own rental agreement or sales order.- rentalAgreementIds?: string[];- salesOrderIds?: string[];-};--type ExistingApplication = {- targetMemoId?: string | null;- targetReimbursementId?: string | null;- sourceAmount: number | null;- sourcePaymentId?: string | null;- targetSalesInvoiceId: string | null;- targetPurchaseInvoiceId: string | null;- appliedAmount: number;- discountAmount: number;- writeOffAmount: number;- targetExchangeRate: number;- sourceExchangeRate: number;- appliedDate: string;-};--// The invoice's read-only fields plus the editable selection state.-type ApplyRow = {- sourceAmount: number;- id: string;- invoiceId: string;- dateDue: string | null;- currencyCode: string;- exchangeRate: number;- balance: number;- remainingDocument: number;- rentalAgreementIds?: string[];- salesOrderIds?: string[];- checked: boolean;- appliedAmount: number;- discountAmount: number;- writeOffAmount: number;-};--type AmountField = "appliedAmount" | "discountAmount" | "writeOffAmount";+import {+ type AmountField,+ type ApplyRow,+ autoApplyRows,+ buildApplications,+ type ExistingApplication,+ fundingRequests,+ type OpenInvoice,+ seedApplyRows,+ toggleApplyRow,+ updateApplyAmount+} from "./payment-logic";type PaymentApplyTableProps = {isRefund?: boolean;@@ -179,79 +137,29 @@ const PaymentApplyTable = ({// Discount and write-off only exist on a trade invoice settlement.const hasAdjustments = !isRefund && !isReimbursement;const canEdit = permissions.can("update", "invoicing");- const seed = useMemo<ApplyRow[]>(() => {- const byInvoice = new Map<- string,- {- appliedAmount: number;- discountAmount: number;- writeOffAmount: number;- sourceAmount: number;- }- >();- for (const a of existingApplications) {- const id = isReimbursement- ? a.targetReimbursementId- : isRefund- ? a.targetMemoId- : isReceipt- ? a.targetSalesInvoiceId- : a.targetPurchaseInvoiceId;- if (!id) continue;- const existing = byInvoice.get(id) ?? {- appliedAmount: 0,- discountAmount: 0,- writeOffAmount: 0,- sourceAmount: 0- };- existing.appliedAmount = round(existing.appliedAmount + a.appliedAmount);- existing.discountAmount = round(- existing.discountAmount + a.discountAmount- );- existing.writeOffAmount = round(- existing.writeOffAmount + a.writeOffAmount- );- existing.sourceAmount = toDocumentAmount(- existing.sourceAmount +- (a.sourceAmount ??- toDocumentAmount(- a.appliedAmount,- a.targetExchangeRate,- currencyDecimals- )),- 1,+ const targets = useMemo(+ () => ({ isReceipt, isRefund, isReimbursement }),+ [isReceipt, isRefund, isReimbursement]+ );+ const seed = useMemo<ApplyRow[]>(+ () =>+ seedApplyRows({+ openInvoices,+ existingApplications,+ targets,+ paymentCurrency,+ paymentScope,currencyDecimals- );- byInvoice.set(id, existing);- }- return openInvoices- .filter(- (inv) =>- inv.currencyCode === paymentCurrency &&- inv.remainingDocument > 0 &&- // A deposit lists only its own document's invoices (and any it is- // already applied to, so the refusal below can say why).- (fundingScopeCovers(paymentScope, inv) || byInvoice.has(inv.id))- )- .map((inv) => ({- ...inv,- checked: byInvoice.has(inv.id),- appliedAmount: 0,- discountAmount: 0,- writeOffAmount: 0,- sourceAmount: 0,- ...byInvoice.get(inv.id)- }));- }, [- openInvoices,- existingApplications,- isReceipt,- isRefund,- isReimbursement,- paymentCurrency,- paymentScope,- currencyDecimals- ]);+ }),+ [+ openInvoices,+ existingApplications,+ targets,+ paymentCurrency,+ paymentScope,+ currencyDecimals+ ]+ );const [rows, setRows] = useState<ApplyRow[]>(seed);const currentPayment = useMemo(() => ({@@ -278,19 +186,7 @@ const PaymentApplyTable = ({priorSources,currencyDecimals,isAR: isReceipt,- requests: rows- .filter((r) => r.checked)- .map((r) => ({- targetId: r.id,- targetExchangeRate: r.exchangeRate,- remainingDocument: r.remainingDocument,- remainingBase: r.balance,- requestedDocumentPrincipal: r.sourceAmount,- discountAmount: r.discountAmount,- writeOffAmount: r.writeOffAmount,- rentalAgreementIds: r.rentalAgreementIds,- salesOrderIds: r.salesOrderIds- }))+ requests: fundingRequests(rows)}),error: null};@@ -353,99 +249,19 @@ const PaymentApplyTable = ({: 0;const toggleRow = useCallback((id: string, checked: boolean) =>- setRows((prev) => {- const toggled = prev.find((r) => r.id === id);- // What this row can draw once every other selected row keeps its- // amount: deposits reach only their own document's invoices.- const available = toggled- ? fundableDocumentAmounts({- currentPayment,- priorSources,- currencyDecimals,- requests: [- ...prev- .filter((r) => r.id !== id && r.checked)- .map((r) => ({ ...r, maximumDocument: r.sourceAmount })),- { ...toggled, maximumDocument: toggled.remainingDocument }- ]- }).at(-1)!- : 0;- return prev.map((r) => {- if (r.id !== id) return r;- if (!checked)- return {- ...r,- checked: false,- sourceAmount: 0,- appliedAmount: 0,- discountAmount: 0,- writeOffAmount: 0- };- const sourceAmount = Math.min(available, r.remainingDocument);- return {- ...r,- checked: true,- sourceAmount,- appliedAmount:- sourceAmount === r.remainingDocument- ? r.balance- : Math.min(- r.balance,- toBaseAmount(sourceAmount, r.exchangeRate)- ),- discountAmount: 0,- writeOffAmount: 0- };- });- }),+ setRows((prev) =>+ toggleApplyRow(prev, id, checked, {+ currentPayment,+ priorSources,+ currencyDecimals+ })+ ),[currentPayment, priorSources, currencyDecimals]);const updateAmount = useCallback((id: string, field: AmountField, value: number) =>setRows((prev) =>- prev.map((r) => {- if (r.id !== id) return r;- const next = { ...r, [field]: round(Math.max(0, value)) };- if (field === "appliedAmount")- next.sourceAmount = toDocumentAmount(- next.appliedAmount,- r.exchangeRate,- currencyDecimals- );- else if (- toDocumentAmount(- r.sourceAmount +- toDocumentAmount(- r.discountAmount + r.writeOffAmount,- r.exchangeRate,- currencyDecimals- ),- 1,- currencyDecimals- ) === r.remainingDocument- ) {- next.appliedAmount = Math.max(- 0,- round(r.balance - next.discountAmount - next.writeOffAmount)- );- next.sourceAmount = Math.max(- 0,- toDocumentAmount(- r.remainingDocument -- toDocumentAmount(- next.discountAmount + next.writeOffAmount,- r.exchangeRate,- currencyDecimals- ),- 1,- currencyDecimals- )- );- }- next.checked =- next.sourceAmount + next.discountAmount + next.writeOffAmount > 0;- return next;- })+ updateApplyAmount(prev, id, field, value, currencyDecimals)),[currencyDecimals]);@@ -602,53 +418,14 @@ const PaymentApplyTable = ({const onAutoApply = useCallback(() =>- setRows((prev) => {- // Rows in order, each as much as the funding it may use allows.- const amounts = fundableDocumentAmounts({- currentPayment,- priorSources,- currencyDecimals,- requests: prev.map((r) => ({- ...r,- maximumDocument: r.remainingDocument- }))- });- const requests = prev.map((r, i) => ({- targetId: r.id,- targetExchangeRate: r.exchangeRate,- remainingDocument: r.remainingDocument,- remainingBase: r.balance,- requestedDocumentPrincipal: amounts[i]!,- discountAmount: 0,- writeOffAmount: 0,- rentalAgreementIds: r.rentalAgreementIds,- salesOrderIds: r.salesOrderIds- }));- const result = allocatePaymentFunding({+ setRows((prev) =>+ autoApplyRows(prev, {currentPayment,priorSources,- requests,currencyDecimals,- isAR: isReceipt- });- return prev.map((r) => {- const apps = result.applications.filter((a) => a.targetId === r.id);- return {- ...r,- checked: apps.length > 0,- sourceAmount: toDocumentAmount(- apps.reduce((sum, a) => sum + a.sourceAmount, 0),- 1,- currencyDecimals- ),- appliedAmount: round(- apps.reduce((sum, a) => sum + a.appliedAmount, 0)- ),- discountAmount: 0,- writeOffAmount: 0- };- });- }),+ isReceipt+ })+ ),[currentPayment, priorSources, currencyDecimals, isReceipt]);const onClear = useCallback(@@ -667,25 +444,11 @@ const PaymentApplyTable = ({);const onSave = () => {if (preview.error) return;- const applications = rows- .filter(- (r) =>- r.checked && r.sourceAmount + r.discountAmount + r.writeOffAmount > 0- )- .map((r) => ({- targetSalesInvoiceId: hasAdjustments && isReceipt ? r.id : undefined,- targetPurchaseInvoiceId:- hasAdjustments && !isReceipt ? r.id : undefined,- targetMemoId: isRefund ? r.id : undefined,- targetReimbursementId: isReimbursement ? r.id : undefined,- appliedAmount: r.appliedAmount,- sourceAmount: r.sourceAmount,- discountAmount: r.discountAmount,- writeOffAmount: r.writeOffAmount,- targetExchangeRate: r.exchangeRate,- sourceExchangeRate: paymentExchangeRate,- appliedDate: today- }));+ const applications = buildApplications(rows, {+ targets,+ paymentExchangeRate,+ today+ });const formData = new FormData();formData.set("applications", JSON.stringify(applications));fetcher.submit(formData, {diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.test.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.test.tsxdeleted file mode 100644index 47e6f4cecb..0000000000--- a/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.test.tsx+++ /dev/null@@ -1,276 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import type { ComponentProps, ReactNode } from "react";-import { createElement } from "react";-import { renderToStaticMarkup } from "react-dom/server";-import { beforeEach, describe, expect, it, vi } from "vitest";--const harness = vi.hoisted(() => ({- states: [] as unknown[],- stateIndex: 0,- values: {} as Record<string, unknown>,- typeChange: undefined as- | ((option: { value: string; label: string }) => void)- | undefined,- currencyChange: undefined as- | ((option: { value: string; label: string }) => void)- | undefined,- currencies: [- { code: "USD", name: "US Dollar", decimalPlaces: 2 },- { code: "EUR", name: "Euro", decimalPlaces: 2 },- { code: "JPY", name: "Japanese Yen", decimalPlaces: 0 },- { code: "BHD", name: "Bahraini Dinar", decimalPlaces: 3 }- ]-}));--// Match the neighboring server-rendered composer tests while retaining each-// PaymentForm state slot between renders to exercise selector callbacks.-vi.mock("react", async (importOriginal) => {- const react = await importOriginal<typeof import("react")>();- return {- ...react,- useState: (seed: unknown) => {- const index = harness.stateIndex++;- if (!(index in harness.states))- harness.states[index] = typeof seed === "function" ? seed() : seed;- return [- harness.states[index],- (value: unknown) => {- harness.states[index] =- typeof value === "function" ? value(harness.states[index]) : value;- }- ];- }- };-});-// PaymentForm imports nothing from @carbon/react; `useCurrencies` needs useMount.-vi.mock("@carbon/react", () => ({- useMount: () => undefined-}));-vi.mock("@carbon/form", () => ({- ValidatedForm: ({- children,- defaultValues- }: {- children: ReactNode;- defaultValues: Record<string, unknown>;- }) => {- harness.values = defaultValues;- return createElement("form", null, children);- }-}));-vi.mock("~/components/Form", () => {- const Field = () => null;- return {- Account: Field,- Customer: () => createElement("input", { name: "customerId" }),- CustomFormFields: Field,- DatePicker: Field,- Employee: () => createElement("input", { name: "employeeId" }),- Hidden: ({ name, value }: { name: string; value?: string }) =>- createElement("input", { type: "hidden", name, value, readOnly: true }),- Input: Field,- SelectControlled: ({- options,- onChange- }: {- options: { label: string; value: string }[];- onChange: typeof harness.typeChange;- }) => {- harness.typeChange = onChange;- return createElement(- "select",- null,- options.map((o) =>- createElement("option", { key: o.value, value: o.value }, o.label)- )- );- },- SequenceOrCustomId: Field,- Submit: Field,- Supplier: () => createElement("input", { name: "supplierId" }),- TextArea: Field,- Currency: ({ onChange }: { onChange?: typeof harness.currencyChange }) => {- harness.currencyChange = onChange;- return null;- },- Number: ({- name,- label,- formatOptions- }: {- name: string;- label: string;- formatOptions: Intl.NumberFormatOptions;- }) =>- createElement("input", {- name,- "aria-label": label,- readOnly: true,- value: new Intl.NumberFormat("en-US", formatOptions).format(- Number(harness.values[name])- )- })- };-});-vi.mock("@lingui/react/macro", () => ({- Trans: ({ children }: { children: ReactNode }) => children,- useLingui: () => ({- t: (parts: TemplateStringsArray, ...values: unknown[]) =>- parts.reduce(- (result, part, index) => result + part + (values[index] ?? ""),- ""- )- })-}));-// The currency list is read through the query cache (`useCurrencies`).-vi.mock("@carbon/query", () => ({- RefreshRate: { Never: Number.POSITIVE_INFINITY },- useLoaderQuery: () => ({- data: { data: harness.currencies },- isFetching: false- })-}));-vi.mock("react-router", () => ({- generatePath: (path: string) => path,- useFetcher: () => ({ state: "idle" })-}));-vi.mock("~/hooks/useCompanySettings", () => ({- useCompanySettings: () => ({ showCurrencyTrailingZeros: true })-}));-vi.mock("~/hooks", async () => {- const { useCurrencyDecimals } = await import("~/hooks/useCurrencies");- return {- useCurrencyDecimals,- usePermissions: () => ({ can: () => true }),- useUser: () => ({ company: { baseCurrencyCode: "USD" } })- };-});--import PaymentForm from "./PaymentForm";--const initialValues: ComponentProps<typeof PaymentForm>["initialValues"] = {- paymentType: "Receipt",- customerId: "customer",- paymentDate: "2026-09-08",- currencyCode: "EUR",- exchangeRate: 0.8,- totalAmount: 120.8,- bankAccount: "bank"-};--function render(values = initialValues) {- harness.stateIndex = 0;- return renderToStaticMarkup(- createElement(PaymentForm, { initialValues: values })- );-}--beforeEach(() => {- harness.states = [];- harness.stateIndex = 0;- harness.currencyChange = undefined;- harness.typeChange = undefined;-});--describe("PaymentForm refund directions", () => {- it("seeds the visible payment kind in the form's registered defaults", () => {- render();- expect(harness.values.paymentKind).toBe("customer-payment");- });- it.each([- ["customer-refund", "Disbursement", "customerId", "supplierId"],- ["supplier-refund", "Receipt", "supplierId", "customerId"]- ])(- "offers %s and submits its cash direction with one party",- (kind, direction, party, otherParty) => {- const html = render();- expect(html).toContain("Refund to Customer");- expect(html).toContain("Refund from Supplier");- harness.typeChange?.({ value: kind, label: kind });- const next = render();- expect(next).toContain(- `name="paymentType" readonly="" value="${direction}"`- );- expect(next).toContain(`name="${party}"`);- expect(next).toContain(`name="${otherParty}" readonly="" value=""`);- }- );-});--describe("PaymentForm employee payee", () => {- it("mounts only the employee field and blanks both trade parties", () => {- const html = render();- expect(html).toContain("Reimbursement to Employee");- harness.typeChange?.({- value: "employee-payment",- label: "employee-payment"- });- const next = render();- // Always cash OUT — an employee payment is never a receipt.- expect(next).toContain(- 'name="paymentType" readonly="" value="Disbursement"'- );- expect(next).toContain('name="employeeId"');- expect(next).toContain('name="customerId" readonly="" value=""');- expect(next).toContain('name="supplierId" readonly="" value=""');- });-- it("seeds the employee kind from a saved payment and blanks employeeId for a trade party", () => {- render({- ...initialValues,- customerId: "",- employeeId: "employee",- paymentType: "Disbursement"- });- expect(harness.values.paymentKind).toBe("employee-payment");- harness.states = [];- expect(render()).toContain('name="employeeId" readonly="" value=""');- });-});--describe("PaymentForm document currency", () => {- it.each([undefined, "payment-id"])(- "labels document cash in EUR for payment id %s while the company uses USD",- (id) => {- const html = render({ ...initialValues, id, status: "Draft" });- expect(html).toContain(- 'aria-label="Total Amount" readonly="" value="€120.80"'- );- expect(html).not.toContain("$120.80");- }- );-- it.each([- ["JPY", 123, "¥123"],- ["BHD", 123.456, "BHD 123.456"]- ] as const)(- "uses %s document settlement precision",- (currencyCode, totalAmount, formatted) => {- expect(render({ ...initialValues, currencyCode, totalAmount })).toContain(- `aria-label="Total Amount" readonly="" value="${formatted}"`- );- }- );-- it.each([undefined, "payment-id"])(- "updates currency and decimal precision after selection for payment id %s",- (id) => {- const values = {- ...initialValues,- id,- status: "Draft",- totalAmount: 123.456- };- render(values);- harness.currencyChange?.({ value: "BHD", label: "Bahraini Dinar" });- expect(render(values)).toContain('value="BHD 123.456"');- harness.currencyChange?.({ value: "JPY", label: "Japanese Yen" });- expect(render(values)).toContain('value="¥123"');- harness.currencyChange?.({ value: "EUR", label: "Euro" });- expect(render(values)).toContain('value="€123.46"');- }- );-});diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.tsxindex 6b8600ce2f..9d57eb6ef0 100644--- a/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.tsx+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.tsx@@ -31,6 +31,11 @@ import {paymentValidator} from "~/modules/invoicing/invoicing.models";import { path } from "~/utils/path";+import {+ initialPaymentKind,+ paymentDocumentCurrency,+ paymentKindFields+} from "./payment-logic";// Builds the "new payment" URL pre-filled from an invoice. side "ar" seeds the// customer (→ Receipt); "ap" seeds the supplier (→ Disbursement). Lives with the@@ -107,7 +112,10 @@ const PaymentForm = ({const { t } = useLingui();const { company } = useUser();const [currencyCode, setCurrencyCode] = useState(- initialValues.currencyCode || company?.baseCurrencyCode || "USD"+ paymentDocumentCurrency(+ initialValues.currencyCode,+ company?.baseCurrencyCode+ ));const currencyDecimals = useCurrencyDecimals(currencyCode);const permissions = usePermissions();@@ -115,25 +123,12 @@ const PaymentForm = ({const isLocked = isPaymentLocked(initialValues.status);const canMutate = permissions.can("update", "invoicing");- // Cash direction and subledger party are independent for refunds. An employee- // payee is neither: it is always cash OUT against the reimbursement control- // account, so it has a single kind rather than a payment/refund pair.- const initialKind = initialValues.employeeId- ? "employee-payment"- : initialValues.supplierId- ? initialValues.paymentType === "Receipt"- ? "supplier-refund"- : "supplier-payment"- : initialValues.paymentType === "Disbursement"- ? "customer-refund"- : "customer-payment";+ const initialKind = initialPaymentKind(initialValues);const [paymentKind, setPaymentKind] = useState(initialKind);- const isEmployee = paymentKind === "employee-payment";- const isCustomer = paymentKind.startsWith("customer-");- const currentType =- paymentKind === "customer-payment" || paymentKind === "supplier-refund"- ? "Receipt"- : "Disbursement";+ const kindFields = paymentKindFields(paymentKind);+ const isEmployee = kindFields.party === "employeeId";+ const isCustomer = kindFields.party === "customerId";+ const currentType = kindFields.paymentType;// The deposit picker follows the selected customer; picking a customer clears// a document that belonged to the previous one.@@ -211,17 +206,9 @@ const PaymentForm = ({{/* Exactly one party field is mounted, and the other two areblanked — the validator's one-of-three refine (and the DB'swidened payment_party_check) rejects anything else. */}- {isEmployee ? (- <>- <Hidden name="customerId" value="" />- <Hidden name="supplierId" value="" />- </>- ) : (- <>- <Hidden name={isCustomer ? "supplierId" : "customerId"} value="" />- <Hidden name="employeeId" value="" />- </>- )}+ {kindFields.blank.map((field) => (+ <Hidden key={field} name={field} value="" />+ ))}<Hidden name="salesOrderId" value={depositIds.salesOrderId} /><Hidden name="rentalAgreementId" value={depositIds.rentalAgreementId} />{isEditing && <Hidden name="paymentId" />}diff --git a/apps/erp/app/modules/invoicing/ui/Payment/payment-logic.test.ts b/apps/erp/app/modules/invoicing/ui/Payment/payment-logic.test.tsnew file mode 100644index 0000000000..3adad0457d--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Payment/payment-logic.test.ts@@ -0,0 +1,694 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ allocatePaymentFunding,+ type FundingScope,+ type FundingSource,+ toBaseAmount+} from "@carbon/utils";+import { describe, expect, it } from "vitest";+import {+ type ApplyRow,+ type ApplyTargets,+ aggregateApplications,+ autoApplyRows,+ buildApplications,+ buildCreditApplications,+ type ExistingApplication,+ fundingRequests,+ initialPaymentKind,+ type OpenInvoice,+ type PaymentApplication,+ paymentDocumentCurrency,+ paymentKindFields,+ seedApplyRows,+ seedCreditRows,+ toggleApplyRow,+ toggleCreditRow,+ unappliedPaymentCash,+ updateApplyAmount,+ updateCreditAmount+} from "./payment-logic";++describe("payment kind", () => {+ it.each([+ ["customer-payment", "Receipt", "customerId", ["supplierId", "employeeId"]],+ [+ "customer-refund",+ "Disbursement",+ "customerId",+ ["supplierId", "employeeId"]+ ],+ [+ "supplier-payment",+ "Disbursement",+ "supplierId",+ ["customerId", "employeeId"]+ ],+ ["supplier-refund", "Receipt", "supplierId", ["customerId", "employeeId"]],+ // An employee is always paid out, never a receipt.+ [+ "employee-payment",+ "Disbursement",+ "employeeId",+ ["customerId", "supplierId"]+ ]+ ])(+ "%s submits a %s to %s and blanks the other parties",+ (kind, paymentType, party, blank) => {+ expect(paymentKindFields(kind)).toEqual({ paymentType, party, blank });+ }+ );++ it.each([+ "customer-payment",+ "customer-refund",+ "supplier-payment",+ "supplier-refund",+ "employee-payment"+ ])("a saved %s reopens as the same kind", (kind) => {+ const { paymentType, party } = paymentKindFields(kind);+ expect(initialPaymentKind({ paymentType, [party]: "party-id" })).toBe(kind);+ });++ it.each([+ ["EUR", "USD", "EUR"],+ ["", "USD", "USD"],+ [undefined, undefined, "USD"]+ ])(+ "enters the total of a %s payment in a %s company as %s",+ (currency, base, expected) => {+ expect(paymentDocumentCurrency(currency, base)).toBe(expected);+ }+ );+});++describe("apply to invoices", () => {+ const TODAY = "2026-09-07";+ const receipt: ApplyTargets = {+ isReceipt: true,+ isRefund: false,+ isReimbursement: false+ };++ // A EUR payment in a USD company: each invoice carries its own rate snapshot.+ const invoice = (overrides: Partial<OpenInvoice> = {}): OpenInvoice => ({+ id: "one",+ invoiceId: "INV1",+ dateDue: null,+ currencyCode: "EUR",+ exchangeRate: 1.1,+ totalAmount: 100,+ balance: 100,+ remainingDocument: 110,+ status: "Submitted",+ ...overrides+ });+ const two = invoice({+ id: "two",+ invoiceId: "INV2",+ exchangeRate: 1.2,+ totalAmount: 50,+ balance: 50,+ remainingDocument: 60+ });++ type Setup = {+ targets: ApplyTargets;+ openInvoices: OpenInvoice[];+ existingApplications: ExistingApplication[];+ paymentTotal: number;+ paymentExchangeRate: number;+ priorSources: FundingSource[];+ paymentScope: FundingScope | null;+ };+ function base(overrides: Partial<Setup> = {}) {+ const setup: Setup = {+ targets: receipt,+ openInvoices: [invoice(), two],+ existingApplications: [],+ paymentTotal: 170,+ paymentExchangeRate: 1.2,+ priorSources: [],+ paymentScope: null,+ ...overrides+ };+ const funding = {+ currentPayment: {+ paymentId: "current",+ postingDate: TODAY,+ exchangeRate: setup.paymentExchangeRate,+ remainingDocument: setup.paymentTotal,+ remainingBase: toBaseAmount(+ setup.paymentTotal,+ setup.paymentExchangeRate+ ),+ scope: setup.paymentScope+ },+ priorSources: setup.priorSources,+ currencyDecimals: 2+ };+ const rows = seedApplyRows({+ openInvoices: setup.openInvoices,+ existingApplications: setup.existingApplications,+ targets: setup.targets,+ paymentCurrency: "EUR",+ paymentScope: setup.paymentScope,+ currencyDecimals: 2+ });+ return {+ rows,+ funding,+ autoApply: (from: ApplyRow[] = rows) =>+ autoApplyRows(from, {+ ...funding,+ isReceipt: setup.targets.isReceipt+ }),+ select: (id: string, from: ApplyRow[] = rows) =>+ toggleApplyRow(from, id, true, funding),+ save: (from: ApplyRow[]) =>+ buildApplications(from, {+ targets: setup.targets,+ paymentExchangeRate: setup.paymentExchangeRate,+ today: TODAY+ })+ };+ }++ // What a saved draft reads back: the database holds null, not a missing key.+ const reopen = (apps: ReturnType<ReturnType<typeof base>["save"]>) =>+ apps.map((app) => ({+ ...app,+ targetSalesInvoiceId: app.targetSalesInvoiceId ?? null,+ targetPurchaseInvoiceId: app.targetPurchaseInvoiceId ?? null+ }));++ it("auto applies 170 EUR to invoices of 110 and 60 EUR at their own rates", () => {+ const table = base();+ expect(table.save(table.autoApply())).toEqual([+ {+ targetSalesInvoiceId: "one",+ targetPurchaseInvoiceId: undefined,+ targetMemoId: undefined,+ targetReimbursementId: undefined,+ appliedAmount: 100,+ sourceAmount: 110,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1.1,+ sourceExchangeRate: 1.2,+ appliedDate: TODAY+ },+ {+ targetSalesInvoiceId: "two",+ targetPurchaseInvoiceId: undefined,+ targetMemoId: undefined,+ targetReimbursementId: undefined,+ appliedAmount: 50,+ sourceAmount: 60,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1.2,+ sourceExchangeRate: 1.2,+ appliedDate: TODAY+ }+ ]);+ });++ it.each([+ ["a receipt", receipt, "targetSalesInvoiceId"],+ [+ "a disbursement",+ { isReceipt: false, isRefund: false, isReimbursement: false },+ "targetPurchaseInvoiceId"+ ],+ [+ "a refund receipt",+ { isReceipt: true, isRefund: true, isReimbursement: false },+ "targetMemoId"+ ],+ [+ "a refund disbursement",+ { isReceipt: false, isRefund: true, isReimbursement: false },+ "targetMemoId"+ ],+ [+ "an employee payment",+ { isReceipt: false, isRefund: false, isReimbursement: true },+ "targetReimbursementId"+ ]+ ] as const)(+ "%s targets %s only, and resaves unchanged when reopened",+ (_kind, targets, column) => {+ const table = base({+ targets,+ paymentTotal: 110,+ openInvoices: [invoice()]+ });+ const saved = table.save(table.autoApply());+ expect(saved).toEqual([+ {+ targetSalesInvoiceId: undefined,+ targetPurchaseInvoiceId: undefined,+ targetMemoId: undefined,+ targetReimbursementId: undefined,+ [column]: "one",+ appliedAmount: 100,+ sourceAmount: 110,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1.1,+ sourceExchangeRate: 1.2,+ appliedDate: TODAY+ }+ ]);++ const reopened = base({+ targets,+ paymentTotal: 110,+ openInvoices: [invoice()],+ existingApplications: reopen(saved)+ });+ expect(reopened.save(reopened.rows)).toEqual(saved);+ }+ );++ it("sums a reopened draft's funding splits into one row per invoice", () => {+ const split = {+ targetSalesInvoiceId: "one",+ targetPurchaseInvoiceId: null,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1.1,+ appliedDate: TODAY+ };+ const table = base({+ existingApplications: [+ {+ ...split,+ appliedAmount: 40,+ sourceAmount: 44,+ sourcePaymentId: null,+ sourceExchangeRate: 1.2+ },+ {+ ...split,+ appliedAmount: 60,+ sourceAmount: 66,+ sourcePaymentId: "prior",+ sourceExchangeRate: 1.1+ }+ ]+ });+ expect(table.save(table.rows)).toEqual([+ expect.objectContaining({+ targetSalesInvoiceId: "one",+ appliedAmount: 100,+ sourceAmount: 110,+ sourceExchangeRate: 1.2+ })+ ]);+ });++ it("moves cash out of a fully relieved row as discount and write-off are entered", () => {+ // 110 EUR at 1.1 relieves 100 USD. A 10 USD discount is 11 EUR and a 5 USD+ // write-off 5.50 EUR, so the cash left is 110 - 16.50 = 93.50 EUR.+ const table = base();+ const discounted = updateApplyAmount(+ table.select("one"),+ "one",+ "discountAmount",+ 10,+ 2+ );+ const writtenOff = updateApplyAmount(+ discounted,+ "one",+ "writeOffAmount",+ 5,+ 2+ );+ expect(table.save(writtenOff)).toEqual([+ expect.objectContaining({+ appliedAmount: 85,+ sourceAmount: 93.5,+ discountAmount: 10,+ writeOffAmount: 5+ })+ ]);+ });++ it("selecting an invoice in full relieves its whole carrying balance", () => {+ // 110 EUR at 1.1 converts to 100.00, but the invoice still carries 100.01.+ const table = base({ openInvoices: [invoice({ balance: 100.01 })] });+ expect(table.save(table.select("one"))).toEqual([+ expect.objectContaining({ appliedAmount: 100.01, sourceAmount: 110 })+ ]);+ });++ it("shows nothing for invoices in another currency or with nothing open", () => {+ expect(+ base({+ openInvoices: [+ invoice({ currencyCode: "USD" }),+ invoice({ id: "two", remainingDocument: 0 })+ ]+ }).rows+ ).toEqual([]);+ });++ describe("at a rate where one base cent is 160.01 document units", () => {+ // 0.01 USD carried, 160.01 EUR open, funded by a prior 160.01 EUR receipt.+ const highRate = (overrides: Partial<Setup> = {}) =>+ base({+ paymentTotal: 0,+ paymentExchangeRate: 16000,+ priorSources: [+ {+ paymentId: "prior",+ postingDate: "2026-09-01",+ exchangeRate: 16000,+ remainingDocument: 160.01,+ remainingBase: 0.01+ }+ ],+ openInvoices: [+ invoice({+ exchangeRate: 16000,+ totalAmount: 0.01,+ balance: 0.01,+ remainingDocument: 160.01+ })+ ],+ ...overrides+ });+ const saved = (sourceAmount: number): ExistingApplication => ({+ targetSalesInvoiceId: "one",+ targetPurchaseInvoiceId: null,+ appliedAmount: 0.01,+ sourceAmount,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 16000,+ sourceExchangeRate: 16000,+ appliedDate: TODAY+ });++ it.each([+ ["a new draft", []],+ ["a reopened full application", [saved(160.01)]]+ ])(+ "converts a typed 0.01 base to 160.00 document units on %s",+ (_draft, existingApplications) => {+ const table = highRate({ existingApplications });+ expect(+ table.save(+ updateApplyAmount(table.rows, "one", "appliedAmount", 0.01, 2)+ )+ ).toEqual([+ expect.objectContaining({ appliedAmount: 0.01, sourceAmount: 160 })+ ]);+ }+ );++ it.each(["discountAmount", "writeOffAmount"] as const)(+ "a zero %s edit does not promote a partial 160.00 to full relief",+ (field) => {+ const table = highRate({ existingApplications: [saved(160)] });+ expect(+ table.save(updateApplyAmount(table.rows, "one", field, 0, 2))+ ).toEqual([+ expect.objectContaining({ appliedAmount: 0.01, sourceAmount: 160 })+ ]);+ }+ );++ it.each(["select", "autoApply"] as const)(+ "%s keeps all 160.01 document units for a full application",+ (action) => {+ const table = highRate();+ const rows =+ action === "select" ? table.select("one") : table.autoApply();+ expect(table.save(rows)).toEqual([+ expect.objectContaining({ appliedAmount: 0.01, sourceAmount: 160.01 })+ ]);+ }+ );++ it.each([+ ["select", 16000],+ ["autoApply", 16000],+ ["autoApply", 100000]+ ] as const)(+ "%s at %s keeps the last document cent when its carrying base is zero",+ (action, rate) => {+ const table = highRate({+ paymentExchangeRate: rate,+ priorSources: [+ {+ paymentId: "prior",+ postingDate: "2026-09-01",+ exchangeRate: rate,+ remainingDocument: 0.01,+ remainingBase: 0+ }+ ],+ openInvoices: [+ invoice({ exchangeRate: rate, balance: 0, remainingDocument: 0.01 })+ ]+ });+ const rows =+ action === "select" ? table.select("one") : table.autoApply();+ expect(table.save(rows)).toEqual([+ expect.objectContaining({ appliedAmount: 0, sourceAmount: 0.01 })+ ]);+ }+ );+ });++ describe("customer deposits fund only their own document", () => {+ const ra1 = {+ type: "rentalAgreement" as const,+ id: "ra-1",+ readableId: "RA000001"+ };+ const deposits = (overrides: Partial<Setup> = {}) =>+ base({+ paymentTotal: 0,+ priorSources: [+ {+ paymentId: "deposit",+ postingDate: "2026-09-01",+ exchangeRate: 1.2,+ remainingDocument: 60,+ remainingBase: 50,+ scope: ra1+ }+ ],+ openInvoices: [+ invoice({ rentalAgreementIds: ["ra-3"] }),+ { ...two, rentalAgreementIds: ["ra-1"] }+ ],+ ...overrides+ });++ it("auto applies a deposit only to its agreement's invoice", () => {+ const table = deposits();+ expect(table.save(table.autoApply())).toEqual([+ expect.objectContaining({+ targetSalesInvoiceId: "two",+ appliedAmount: 50,+ sourceAmount: 60+ })+ ]);+ });++ it("draws nothing from the deposit for another document's invoice", () => {+ const table = deposits();+ expect(table.save(table.select("two", table.select("one")))).toEqual([+ expect.objectContaining({+ targetSalesInvoiceId: "two",+ sourceAmount: 60+ })+ ]);+ });++ it("lists only the deposit payment's own invoices", () => {+ expect(+ deposits({+ priorSources: [],+ paymentTotal: 170,+ paymentScope: ra1+ }).rows.map((r) => r.id)+ ).toEqual(["two"]);+ });++ it("still lists another document's invoice it is applied to, and refuses it", () => {+ const table = deposits({+ priorSources: [],+ paymentTotal: 170,+ paymentScope: ra1,+ existingApplications: [+ {+ targetSalesInvoiceId: "one",+ targetPurchaseInvoiceId: null,+ appliedAmount: 100,+ discountAmount: 0,+ writeOffAmount: 0,+ sourceAmount: 110,+ targetExchangeRate: 1.1,+ sourceExchangeRate: 1.2,+ appliedDate: TODAY+ }+ ]+ });+ expect(table.rows.map((r) => [r.id, r.checked])).toEqual([+ ["one", true],+ ["two", false]+ ]);+ expect(() =>+ allocatePaymentFunding({+ ...table.funding,+ isAR: true,+ requests: fundingRequests(table.rows)+ })+ ).toThrow(/RA000001/);+ });+ });+});++describe("apply available credits", () => {+ // A 160.01 EUR credit carried at 0.01 USD, against an invoice of the same size.+ const credit = (+ exchangeRate: number,+ remaining: number,+ remainingDocument: number+ ) => ({+ id: "m",+ memoId: "CM1",+ direction: "Credit",+ currencyCode: "EUR",+ exchangeRate,+ remaining,+ remainingDocument+ });+ const openInvoice = (+ exchangeRate: number,+ balance: number,+ remainingDocument: number+ ) => ({+ id: "i",+ invoiceId: "INV",+ exchangeRate,+ balance,+ remainingDocument+ });++ it("resaves a staged document cent whose base amount is zero", () => {+ const staged = [+ { memoId: "m", invoiceId: "i", amount: 0, sourceAmount: 0.01 }+ ];+ expect(+ buildCreditApplications(+ seedCreditRows(+ [credit(100000, 0, 0.01)],+ [openInvoice(100000, 0, 0.01)],+ staged,+ 2+ )+ )+ ).toEqual(staged);+ });++ it.each([+ ["a new draft", []],+ [+ "a reopened full application",+ [{ memoId: "m", invoiceId: "i", amount: 0.01, sourceAmount: 160.01 }]+ ]+ ])(+ "converts a typed 0.01 base to 160.00 document units on %s",+ (_draft, staged) => {+ const rows = seedCreditRows(+ [credit(16000, 0.01, 160.01)],+ [openInvoice(16000, 0.01, 160.01)],+ staged,+ 2+ );+ expect(+ buildCreditApplications(updateCreditAmount(rows, "m", 0.01, 2))+ ).toEqual([+ { memoId: "m", invoiceId: "i", amount: 0.01, sourceAmount: 160 }+ ]);+ }+ );++ it("selecting a credit that clears the invoice keeps the exact document remainder", () => {+ const invoices = [openInvoice(16000, 0.01, 160.01)];+ const rows = seedCreditRows([credit(16000, 0.01, 160.01)], invoices, [], 2);+ expect(+ buildCreditApplications(+ toggleCreditRow(+ rows,+ "m",+ true,+ new Map(invoices.map((i) => [i.id, i]))+ )+ )+ ).toEqual([+ { memoId: "m", invoiceId: "i", amount: 0.01, sourceAmount: 160.01 }+ ]);+ });+});++describe("applications history", () => {+ const split = (overrides: Partial<PaymentApplication>) =>+ ({+ id: "a",+ targetSalesInvoiceId: "one",+ targetPurchaseInvoiceId: null,+ targetMemoId: null,+ targetReimbursementId: null,+ appliedAmount: 40,+ discountAmount: 0,+ writeOffAmount: 0,+ sourceAmount: 44,+ sourcePaymentId: null,+ targetExchangeRate: 1.1,+ sourceExchangeRate: 1.2,+ fxGainLossAmount: -3.33333,+ appliedDate: "2026-09-07",+ ...overrides+ }) as PaymentApplication;++ // 44 EUR of this payment plus 66 EUR drawn from a prior receipt, both on INV1.+ const splits = [+ split({}),+ split({+ id: "b",+ appliedAmount: 60,+ sourceAmount: 66,+ sourcePaymentId: "prior",+ sourceExchangeRate: 1.1,+ fxGainLossAmount: 0+ })+ ];++ it("shows one row per invoice with its splits summed", () => {+ expect(aggregateApplications(splits)).toEqual([+ {+ ...splits[0],+ appliedAmount: 100,+ sourceAmount: 110,+ fxGainLossAmount: -3.33333,+ sourceRates: [1.2, 1.1]+ }+ ]);+ });++ it("counts only this payment's own cash against its unapplied amount", () => {+ expect(unappliedPaymentCash(44, splits)).toBe(0);+ });+});diff --git a/apps/erp/app/modules/invoicing/ui/Payment/payment-logic.ts b/apps/erp/app/modules/invoicing/ui/Payment/payment-logic.tsnew file mode 100644index 0000000000..ef8a832c61--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Payment/payment-logic.ts@@ -0,0 +1,663 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// Pure logic behind the payment form and the settlement composers (apply to+// invoices, apply credits, applications history).++import {+ allocatePaymentFunding,+ type FundingRequest,+ type FundingScope,+ type FundingSource,+ fundableDocumentAmounts,+ fundingScopeCovers,+ round,+ toBaseAmount,+ toDocumentAmount+} from "@carbon/utils";+import type { getInvoiceSettlements } from "~/modules/invoicing/invoicing.service";++// ---------------------------------------------------------------------------+// Payment form+// ---------------------------------------------------------------------------++const PARTY_FIELDS = ["customerId", "supplierId", "employeeId"] as const;+type PartyField = (typeof PARTY_FIELDS)[number];++/**+ * Cash direction and subledger party are independent for refunds. An employee+ * payee is neither: it is always cash OUT against the reimbursement control+ * account, so it has a single kind rather than a payment/refund pair.+ */+export function initialPaymentKind(values: {+ employeeId?: string | null;+ supplierId?: string | null;+ paymentType?: string | null;+}): string {+ return values.employeeId+ ? "employee-payment"+ : values.supplierId+ ? values.paymentType === "Receipt"+ ? "supplier-refund"+ : "supplier-payment"+ : values.paymentType === "Disbursement"+ ? "customer-refund"+ : "customer-payment";+}++/**+ * What a payment kind submits: its cash direction, the one party field it+ * mounts, and the two it blanks (the validator and `payment_party_check`+ * refuse anything but exactly one party).+ */+export function paymentKindFields(kind: string): {+ paymentType: "Receipt" | "Disbursement";+ party: PartyField;+ blank: PartyField[];+} {+ const party: PartyField =+ kind === "employee-payment"+ ? "employeeId"+ : kind.startsWith("customer-")+ ? "customerId"+ : "supplierId";+ return {+ paymentType:+ kind === "customer-payment" || kind === "supplier-refund"+ ? "Receipt"+ : "Disbursement",+ party,+ blank: PARTY_FIELDS.filter((field) => field !== party)+ };+}++/** The total is entered in the payment's own currency, not the company's. */+export function paymentDocumentCurrency(+ currencyCode: string | null | undefined,+ baseCurrencyCode: string | null | undefined+): string {+ return currencyCode || baseCurrencyCode || "USD";+}++// ---------------------------------------------------------------------------+// Apply to invoices / memos / reimbursements+// ---------------------------------------------------------------------------++// An open invoice for the payment's counterparty.+export type OpenInvoice = {+ id: string;+ invoiceId: string;+ dateDue: string | null;+ currencyCode: string;+ exchangeRate: number;+ totalAmount: number;+ balance: number;+ remainingDocument: number;+ status: string | null;+ // The documents the invoice bills: a customer deposit funds only invoices of+ // its own rental agreement or sales order.+ rentalAgreementIds?: string[];+ salesOrderIds?: string[];+};++export type ExistingApplication = {+ targetMemoId?: string | null;+ targetReimbursementId?: string | null;+ sourceAmount: number | null;+ sourcePaymentId?: string | null;+ targetSalesInvoiceId: string | null;+ targetPurchaseInvoiceId: string | null;+ appliedAmount: number;+ discountAmount: number;+ writeOffAmount: number;+ targetExchangeRate: number;+ sourceExchangeRate: number;+ appliedDate: string;+};++// The invoice's read-only fields plus the editable selection state.+export type ApplyRow = {+ sourceAmount: number;+ id: string;+ invoiceId: string;+ dateDue: string | null;+ currencyCode: string;+ exchangeRate: number;+ balance: number;+ remainingDocument: number;+ rentalAgreementIds?: string[];+ salesOrderIds?: string[];+ checked: boolean;+ appliedAmount: number;+ discountAmount: number;+ writeOffAmount: number;+};++export type AmountField = "appliedAmount" | "discountAmount" | "writeOffAmount";++// Which kind of document the payment settles.+export type ApplyTargets = {+ isReceipt: boolean;+ isRefund: boolean;+ isReimbursement: boolean;+};++export type ApplyFunding = {+ currentPayment: FundingSource;+ priorSources: FundingSource[];+ currencyDecimals: number;+};++/**+ * The rows the composer opens with: open documents in the payment's currency,+ * with what a saved draft already applies to each (its funding splits summed).+ */+export function seedApplyRows({+ openInvoices,+ existingApplications,+ targets: { isReceipt, isRefund, isReimbursement },+ paymentCurrency,+ paymentScope,+ currencyDecimals+}: {+ openInvoices: OpenInvoice[];+ existingApplications: ExistingApplication[];+ targets: ApplyTargets;+ paymentCurrency: string;+ paymentScope: FundingScope | null;+ currencyDecimals: number;+}): ApplyRow[] {+ const byInvoice = new Map<+ string,+ {+ appliedAmount: number;+ discountAmount: number;+ writeOffAmount: number;+ sourceAmount: number;+ }+ >();+ for (const a of existingApplications) {+ const id = isReimbursement+ ? a.targetReimbursementId+ : isRefund+ ? a.targetMemoId+ : isReceipt+ ? a.targetSalesInvoiceId+ : a.targetPurchaseInvoiceId;+ if (!id) continue;+ const existing = byInvoice.get(id) ?? {+ appliedAmount: 0,+ discountAmount: 0,+ writeOffAmount: 0,+ sourceAmount: 0+ };+ existing.appliedAmount = round(existing.appliedAmount + a.appliedAmount);+ existing.discountAmount = round(existing.discountAmount + a.discountAmount);+ existing.writeOffAmount = round(existing.writeOffAmount + a.writeOffAmount);+ existing.sourceAmount = toDocumentAmount(+ existing.sourceAmount ++ (a.sourceAmount ??+ toDocumentAmount(+ a.appliedAmount,+ a.targetExchangeRate,+ currencyDecimals+ )),+ 1,+ currencyDecimals+ );+ byInvoice.set(id, existing);+ }+ return openInvoices+ .filter(+ (inv) =>+ inv.currencyCode === paymentCurrency &&+ inv.remainingDocument > 0 &&+ // A deposit lists only its own document's invoices (and any it is+ // already applied to, so the allocator's refusal can say why).+ (fundingScopeCovers(paymentScope, inv) || byInvoice.has(inv.id))+ )+ .map((inv) => ({+ ...inv,+ checked: byInvoice.has(inv.id),+ appliedAmount: 0,+ discountAmount: 0,+ writeOffAmount: 0,+ sourceAmount: 0,+ ...byInvoice.get(inv.id)+ }));+}++/** The selected rows as allocator requests. */+export function fundingRequests(rows: ApplyRow[]): FundingRequest[] {+ return rows+ .filter((r) => r.checked)+ .map((r) => ({+ targetId: r.id,+ targetExchangeRate: r.exchangeRate,+ remainingDocument: r.remainingDocument,+ remainingBase: r.balance,+ requestedDocumentPrincipal: r.sourceAmount,+ discountAmount: r.discountAmount,+ writeOffAmount: r.writeOffAmount,+ rentalAgreementIds: r.rentalAgreementIds,+ salesOrderIds: r.salesOrderIds+ }));+}++/**+ * Selecting a row fills it with what it can draw once every other selected+ * row keeps its amount (deposits reach only their own document's invoices).+ * A full draw relieves the whole base balance, so no carrying cent is left.+ */+export function toggleApplyRow(+ rows: ApplyRow[],+ id: string,+ checked: boolean,+ { currentPayment, priorSources, currencyDecimals }: ApplyFunding+): ApplyRow[] {+ const toggled = rows.find((r) => r.id === id);+ const available = toggled+ ? fundableDocumentAmounts({+ currentPayment,+ priorSources,+ currencyDecimals,+ requests: [+ ...rows+ .filter((r) => r.id !== id && r.checked)+ .map((r) => ({ ...r, maximumDocument: r.sourceAmount })),+ { ...toggled, maximumDocument: toggled.remainingDocument }+ ]+ }).at(-1)!+ : 0;+ return rows.map((r) => {+ if (r.id !== id) return r;+ if (!checked)+ return {+ ...r,+ checked: false,+ sourceAmount: 0,+ appliedAmount: 0,+ discountAmount: 0,+ writeOffAmount: 0+ };+ const sourceAmount = Math.min(available, r.remainingDocument);+ return {+ ...r,+ checked: true,+ sourceAmount,+ appliedAmount:+ sourceAmount === r.remainingDocument+ ? r.balance+ : Math.min(r.balance, toBaseAmount(sourceAmount, r.exchangeRate)),+ discountAmount: 0,+ writeOffAmount: 0+ };+ });+}++/**+ * An edited base amount. Applied converts to document cash at the row's rate;+ * a discount or write-off on a row that relieves the whole document moves+ * cash out of the row so the row still relieves it exactly.+ */+export function updateApplyAmount(+ rows: ApplyRow[],+ id: string,+ field: AmountField,+ value: number,+ currencyDecimals: number+): ApplyRow[] {+ return rows.map((r) => {+ if (r.id !== id) return r;+ const next = { ...r, [field]: round(Math.max(0, value)) };+ if (field === "appliedAmount")+ next.sourceAmount = toDocumentAmount(+ next.appliedAmount,+ r.exchangeRate,+ currencyDecimals+ );+ else if (+ toDocumentAmount(+ r.sourceAmount ++ toDocumentAmount(+ r.discountAmount + r.writeOffAmount,+ r.exchangeRate,+ currencyDecimals+ ),+ 1,+ currencyDecimals+ ) === r.remainingDocument+ ) {+ next.appliedAmount = Math.max(+ 0,+ round(r.balance - next.discountAmount - next.writeOffAmount)+ );+ next.sourceAmount = Math.max(+ 0,+ toDocumentAmount(+ r.remainingDocument -+ toDocumentAmount(+ next.discountAmount + next.writeOffAmount,+ r.exchangeRate,+ currencyDecimals+ ),+ 1,+ currencyDecimals+ )+ );+ }+ next.checked =+ next.sourceAmount + next.discountAmount + next.writeOffAmount > 0;+ return next;+ });+}++/** Fill rows in order, each with as much as the funding it may use allows. */+export function autoApplyRows(+ rows: ApplyRow[],+ {+ currentPayment,+ priorSources,+ currencyDecimals,+ isReceipt+ }: ApplyFunding & { isReceipt: boolean }+): ApplyRow[] {+ const amounts = fundableDocumentAmounts({+ currentPayment,+ priorSources,+ currencyDecimals,+ requests: rows.map((r) => ({ ...r, maximumDocument: r.remainingDocument }))+ });+ const requests = rows.map((r, i) => ({+ targetId: r.id,+ targetExchangeRate: r.exchangeRate,+ remainingDocument: r.remainingDocument,+ remainingBase: r.balance,+ requestedDocumentPrincipal: amounts[i]!,+ discountAmount: 0,+ writeOffAmount: 0,+ rentalAgreementIds: r.rentalAgreementIds,+ salesOrderIds: r.salesOrderIds+ }));+ const result = allocatePaymentFunding({+ currentPayment,+ priorSources,+ requests,+ currencyDecimals,+ isAR: isReceipt+ });+ return rows.map((r) => {+ const apps = result.applications.filter((a) => a.targetId === r.id);+ return {+ ...r,+ checked: apps.length > 0,+ sourceAmount: toDocumentAmount(+ apps.reduce((sum, a) => sum + a.sourceAmount, 0),+ 1,+ currencyDecimals+ ),+ appliedAmount: round(apps.reduce((sum, a) => sum + a.appliedAmount, 0)),+ discountAmount: 0,+ writeOffAmount: 0+ };+ });+}++/**+ * What Save applications posts. Each row targets exactly one column: a trade+ * invoice by direction, a memo for a refund, a reimbursement for an employee.+ */+export function buildApplications(+ rows: ApplyRow[],+ {+ targets: { isReceipt, isRefund, isReimbursement },+ paymentExchangeRate,+ today+ }: { targets: ApplyTargets; paymentExchangeRate: number; today: string }+) {+ // Discount and write-off only exist on a trade invoice settlement.+ const hasAdjustments = !isRefund && !isReimbursement;+ return rows+ .filter(+ (r) =>+ r.checked && r.sourceAmount + r.discountAmount + r.writeOffAmount > 0+ )+ .map((r) => ({+ targetSalesInvoiceId: hasAdjustments && isReceipt ? r.id : undefined,+ targetPurchaseInvoiceId: hasAdjustments && !isReceipt ? r.id : undefined,+ targetMemoId: isRefund ? r.id : undefined,+ targetReimbursementId: isReimbursement ? r.id : undefined,+ appliedAmount: r.appliedAmount,+ sourceAmount: r.sourceAmount,+ discountAmount: r.discountAmount,+ writeOffAmount: r.writeOffAmount,+ targetExchangeRate: r.exchangeRate,+ sourceExchangeRate: paymentExchangeRate,+ appliedDate: today+ }));+}++// ---------------------------------------------------------------------------+// Apply available credits (memos)+// ---------------------------------------------------------------------------++// A posted, balance-reducing memo the party can apply to an open invoice.+export type AvailableCredit = {+ id: string;+ memoId: string;+ direction: string;+ currencyCode: string;+ exchangeRate: number;+ remaining: number;+ remainingDocument: number;+};++export type OpenInvoiceOption = {+ id: string;+ invoiceId: string;+ exchangeRate: number;+ balance: number;+ remainingDocument: number;+};++export type StagedCredit = {+ memoId: string;+ invoiceId: string;+ amount: number;+ sourceAmount?: number | null;+};++export type CreditRow = {+ id: string;+ memoId: string;+ direction: string;+ remaining: number;+ remainingDocument: number;+ checked: boolean;+ invoiceId: string; // target invoice id+ amount: number;+ sourceAmount: number;+ exchangeRate: number;+};++/** Credits pre-filled from what this Draft payment already stages. */+export function seedCreditRows(+ credits: AvailableCredit[],+ openInvoices: OpenInvoiceOption[],+ staged: StagedCredit[],+ documentDecimals: number+): CreditRow[] {+ // staged is keyed by the memo's row id (== credit.id).+ const stagedByMemo = new Map(staged.map((s) => [s.memoId, s]));+ return credits.map((c) => {+ const s = stagedByMemo.get(c.id);+ return {+ id: c.id,+ memoId: c.memoId,+ direction: c.direction,+ remaining: c.remaining,+ remainingDocument: c.remainingDocument,+ exchangeRate: c.exchangeRate,+ checked: Boolean(s),+ invoiceId:+ s?.invoiceId ??+ openInvoices.find((i) => i.exchangeRate === c.exchangeRate)?.id ??+ "",+ amount: s?.amount ?? 0,+ sourceAmount:+ s?.sourceAmount ??+ (s ? toDocumentAmount(s.amount, c.exchangeRate, documentDecimals) : 0)+ };+ });+}++/**+ * The most a credit can apply to an invoice at the same rate. When either+ * side is used up in full, its own base amount is taken so no cent of+ * carrying base is left behind.+ */+export function creditCap(+ row: CreditRow,+ invoice: OpenInvoiceOption | undefined+): { amount: number; sourceAmount: number } {+ if (!invoice || invoice.exchangeRate !== row.exchangeRate)+ return { amount: 0, sourceAmount: 0 };+ const sourceAmount = Math.min(+ row.remainingDocument,+ invoice.remainingDocument+ );+ const amount =+ sourceAmount === invoice.remainingDocument+ ? invoice.balance+ : sourceAmount === row.remainingDocument+ ? row.remaining+ : toBaseAmount(sourceAmount, row.exchangeRate);+ return { amount, sourceAmount };+}++export function toggleCreditRow(+ rows: CreditRow[],+ id: string,+ checked: boolean,+ invoicesById: ReadonlyMap<string, OpenInvoiceOption>+): CreditRow[] {+ return rows.map((r) =>+ r.id !== id+ ? r+ : {+ ...r,+ checked,+ ...(checked+ ? creditCap(r, invoicesById.get(r.invoiceId))+ : { amount: 0, sourceAmount: 0 })+ }+ );+}++export function changeCreditInvoice(+ rows: CreditRow[],+ id: string,+ invoiceId: string,+ invoicesById: ReadonlyMap<string, OpenInvoiceOption>+): CreditRow[] {+ return rows.map((r) =>+ r.id !== id+ ? r+ : {+ ...r,+ invoiceId,+ ...(r.checked ? creditCap(r, invoicesById.get(invoiceId)) : {})+ }+ );+}++export function updateCreditAmount(+ rows: CreditRow[],+ id: string,+ value: number,+ documentDecimals: number+): CreditRow[] {+ return rows.map((r) => {+ if (r.id !== id) return r;+ const amount = round(Math.max(0, value));+ const sourceAmount = toDocumentAmount(+ amount,+ r.exchangeRate,+ documentDecimals+ );+ return { ...r, amount, sourceAmount, checked: sourceAmount > 0 };+ });+}++export function buildCreditApplications(rows: CreditRow[]) {+ return rows+ .filter((r) => r.checked && r.sourceAmount > 0 && r.invoiceId)+ .map((r) => ({+ memoId: r.id,+ invoiceId: r.invoiceId,+ amount: r.amount,+ sourceAmount: r.sourceAmount+ }));+}++// ---------------------------------------------------------------------------+// Applications history+// ---------------------------------------------------------------------------++export type PaymentApplication = NonNullable<+ Awaited<ReturnType<typeof getInvoiceSettlements>>["data"]+>[number];++/** One row per target document: its funding splits summed. */+export function aggregateApplications(splits: PaymentApplication[]) {+ const byInvoice = new Map<+ string,+ PaymentApplication & { sourceRates: number[] }+ >();+ for (const a of splits) {+ const id =+ a.targetSalesInvoiceId ??+ a.targetPurchaseInvoiceId ??+ a.targetMemoId ??+ a.targetReimbursementId ??+ a.id;+ const existing = byInvoice.get(id);+ if (!existing) {+ byInvoice.set(id, { ...a, sourceRates: [Number(a.sourceExchangeRate)] });+ continue;+ }+ existing.appliedAmount = round(+ existing.appliedAmount + Number(a.appliedAmount)+ );+ existing.discountAmount = round(+ existing.discountAmount + Number(a.discountAmount)+ );+ existing.writeOffAmount = round(+ existing.writeOffAmount + Number(a.writeOffAmount)+ );+ existing.sourceAmount =+ (existing.sourceAmount ?? 0) + Number(a.sourceAmount ?? 0);+ existing.fxGainLossAmount = round(+ Number(existing.fxGainLossAmount ?? 0) + Number(a.fxGainLossAmount ?? 0)+ );+ existing.sourceRates = [+ ...new Set([...existing.sourceRates, Number(a.sourceExchangeRate)])+ ];+ }+ return [...byInvoice.values()];+}++/** This payment's own cash not yet applied; prior payments' splits draw none of it. */+export function unappliedPaymentCash(+ paymentTotal: number,+ splits: PaymentApplication[]+): number {+ return (+ paymentTotal -+ splits.reduce(+ (s, a) => s + (a.sourcePaymentId ? 0 : Number(a.sourceAmount ?? 0)),+ 0+ )+ );+}diff --git a/apps/erp/app/modules/invoicing/ui/Reimbursement/ReimbursementEditForm.test.tsx b/apps/erp/app/modules/invoicing/ui/Reimbursement/ReimbursementEditForm.test.tsxdeleted file mode 100644index 4e5bf2ad8c..0000000000--- a/apps/erp/app/modules/invoicing/ui/Reimbursement/ReimbursementEditForm.test.tsx+++ /dev/null@@ -1,204 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import type { ComponentProps, ReactNode } from "react";-import { createElement } from "react";-import { renderToStaticMarkup } from "react-dom/server";-import { describe, expect, it, vi } from "vitest";--/**- * Server-rendered markup, same harness style as the neighbouring- * `PaymentForm.test.tsx`: the form's own composition is what is under test, so- * the field library is stubbed down to the attributes that decide what gets- * SUBMITTED and at what precision.- */-const harness = vi.hoisted(() => ({- currencies: [- { code: "USD", name: "US Dollar", decimalPlaces: 2 },- { code: "EUR", name: "Euro", decimalPlaces: 2 },- { code: "JPY", name: "Japanese Yen", decimalPlaces: 0 }- ]-}));--vi.mock("@carbon/react", () => {- const Box = ({ children }: { children?: ReactNode }) =>- createElement("div", null, children);- return {- Button: Box,- Card: Box,- CardContent: Box,- CardHeader: Box,- CardTitle: Box,- HStack: Box,- Status: Box,- useMount: () => undefined,- useRouteData: () => undefined- };-});-vi.mock("@carbon/form", () => ({- ValidatedForm: ({ children }: { children: ReactNode }) =>- createElement("form", null, children)-}));-vi.mock("~/components/Form", () => {- const Field = () => null;- return {- CustomFormFields: Field,- DatePicker: Field,- Input: Field,- TextArea: Field,- Hidden: ({ name }: { name: string }) =>- createElement("input", { type: "hidden", name, readOnly: true }),- Currency: ({ isReadOnly }: { isReadOnly?: boolean }) =>- createElement("input", {- name: "currencyCode",- readOnly: Boolean(isReadOnly)- }),- NumberControlled: ({- name,- label,- value,- formatOptions,- step- }: {- name: string;- label: string;- value: number;- formatOptions: Intl.NumberFormatOptions;- step?: number;- }) =>- createElement("input", {- name,- "aria-label": label,- "data-step": step,- readOnly: true,- value: new Intl.NumberFormat("en-US", formatOptions).format(value)- })- };-});-vi.mock("~/components/Form/ExchangeRate", () => ({- default: ({ name, value }: { name: string; value: number }) =>- createElement("input", {- name,- "aria-label": "Exchange Rate",- readOnly: true,- value: String(value)- })-}));-vi.mock("~/components/DocumentLineEditor", () => ({- DocumentLineEditor: ({ currencyCode }: { currencyCode: string }) =>- createElement("div", { "data-lines-currency": currencyCode })-}));-vi.mock("@lingui/react/macro", () => ({- Trans: ({ children }: { children: ReactNode }) => children,- useLingui: () => ({- t: (parts: TemplateStringsArray, ...values: unknown[]) =>- parts.reduce(- (result, part, index) => result + part + (values[index] ?? ""),- ""- )- })-}));-// The currency list is read through the query cache (`useCurrencies`).-vi.mock("@carbon/query", () => ({- RefreshRate: { Never: Number.POSITIVE_INFINITY },- useLoaderQuery: () => ({- data: { data: harness.currencies },- isFetching: false- })-}));-vi.mock("react-router", () => ({- Link: ({ children }: { children?: ReactNode }) =>- createElement("a", null, children)-}));-vi.mock("~/utils/path", () => ({- path: {- to: {- api: { currencies: "/api/accounting/currencies" },- authenticatedRoot: "/x",- reimbursement: (id: string) => `/x/reimbursements/${id}`- }- }-}));-vi.mock("~/hooks", async () => {- const { useCurrencyDecimals } = await import("~/hooks/useCurrencies");- const { useCurrencyFormatter } = await import("~/hooks/useCurrencyFormatter");- return {- useCurrencyDecimals,- useCurrencyFormatter,- useUser: () => ({ company: { baseCurrencyCode: "USD" } })- };-});-vi.mock("~/hooks/useCompanySettings", () => ({- useCompanySettings: () => ({ showCurrencyTrailingZeros: true })-}));--import ReimbursementEditForm from "./ReimbursementEditForm";--type Props = ComponentProps<typeof ReimbursementEditForm>;--const initialValues: Props["initialValues"] = {- id: "rmb_1",- reimbursementDate: "2026-09-20",- currencyCode: "EUR",- exchangeRate: 0.92,- amount: 120.8,- reference: undefined,- notes: undefined-};--function render(values: Props["initialValues"] = initialValues) {- return renderToStaticMarkup(- createElement(ReimbursementEditForm, {- reimbursementId: "rmb_1",- initialValues: values,- initialLines: [],- dimensions: []- })- );-}--describe("ReimbursementEditForm currency and rate", () => {- /**- * The currency used to be editable while `exchangeRate` was a bare `<Hidden>`- * nobody recomputed, so USD→EUR saved a EUR payable at rate 1 — and the money- * inputs kept the ORIGINAL currency's decimals, which react-aria's- * `parse(format(x))` blur commit turns into real rounding.- */- it("does not let the currency be changed away from the stored rate", () => {- expect(render()).toContain('name="currencyCode" readonly=""');- });-- it("submits the stored rate through a visible field, not a hidden one", () => {- const html = render();- expect(html).toContain('name="exchangeRate" aria-label="Exchange Rate"');- expect(html).toContain('value="0.92"');- // Exactly one `exchangeRate` input, or the form posts the value twice.- expect((html.match(/name="exchangeRate"/g) ?? []).length).toBe(1);- expect(html).not.toContain('type="hidden" name="exchangeRate"');- });-- it("keeps a base-currency document on the hidden pass-through at rate 1", () => {- const html = render({- ...initialValues,- currencyCode: "USD",- exchangeRate: 1- });- expect(html).toContain('type="hidden" name="exchangeRate"');- expect((html.match(/name="exchangeRate"/g) ?? []).length).toBe(1);- });-- it("formats and steps the amount at the DOCUMENT currency's precision", () => {- expect(render()).toContain(- 'aria-label="Amount" data-step="0.01" readonly="" value="€120.80"'- );- // 0 decimals and a whole-unit step, or a typed ¥123.4 commits as ¥123.- expect(- render({ ...initialValues, currencyCode: "JPY", amount: 123 })- ).toContain('aria-label="Amount" data-step="1" readonly="" value="¥123"');- });-- it("hands the line editor the same currency the header is denominated in", () => {- expect(render()).toContain('data-lines-currency="EUR"');- });-});diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.test.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.test.tsxdeleted file mode 100644index 58a343f77e..0000000000--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.test.tsx+++ /dev/null@@ -1,94 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import type { ReactNode } from "react";-import { createElement } from "react";-import { renderToStaticMarkup } from "react-dom/server";-import { describe, expect, it, vi } from "vitest";--vi.mock("@carbon/auth", async (importOriginal) => ({- ...(await importOriginal<typeof import("@carbon/auth")>()),- useCarbon: () => ({ carbon: null })-}));-vi.mock("@carbon/form", () => ({- ValidatedForm: ({ children }: { children: ReactNode }) =>- createElement("form", null, children)-}));-vi.mock("@carbon/react", () => {- const Box = ({ children }: { children?: ReactNode }) =>- createElement("div", null, children);- return {- Card: Box,- CardContent: Box,- CardDescription: Box,- CardFooter: Box,- CardHeader: Box,- CardTitle: Box,- VStack: Box,- cn: (...classes: unknown[]) => classes.filter(Boolean).join(" "),- toast: { error: vi.fn() }- };-});-vi.mock("@lingui/react/macro", () => ({- Trans: ({ children }: { children: ReactNode }) => children,- useLingui: () => ({- t: (parts: TemplateStringsArray, ...values: unknown[]) =>- parts.reduce(- (result, part, index) => result + part + (values[index] ?? ""),- ""- )- })-}));-// The two pickers under test render the customer they are scoped to.-vi.mock("~/components/Form", () => {- const Field = () => null;- const ScopedPicker = ({- name,- customer- }: {- name: string;- customer?: string;- }) => createElement("input", { name, "data-customer": customer ?? "" });- return {- Currency: Field,- Customer: Field,- CustomerContact: ScopedPicker,- CustomerLocation: ScopedPicker,- CustomFormFields: Field,- DatePicker: Field,- Hidden: Field,- Input: Field,- Location: Field,- SequenceOrCustomId: Field,- Submit: Field- };-});-vi.mock("~/components/Form/PaymentTerm", () => ({ default: () => null }));-vi.mock("~/hooks", () => ({- usePermissions: () => ({ can: () => true }),- useRouteData: () => undefined-}));--import SalesInvoiceForm from "./SalesInvoiceForm";--function render() {- return renderToStaticMarkup(- createElement(SalesInvoiceForm, {- initialValues: {- customerId: "cust_sold_to",- invoiceCustomerId: "cust_billing",- locationId: "loc_1"- }- })- );-}--describe("SalesInvoiceForm", () => {- it.each(["invoiceCustomerContactId", "invoiceCustomerLocationId"])(- "scopes %s to the invoice customer, not the sold-to customer",- (name) => {- expect(render()).toContain(`name="${name}" data-customer="cust_billing"`);- }- );-});diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsxindex bbf6674d8c..15fbb4f621 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsx@@ -105,9 +105,8 @@ const SalesInvoiceForm = ({ initialValues }: SalesInvoiceFormProps) => {const [customerData, paymentTermData] = await Promise.all([// 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.+ // suppression). ts-ignore, not ts-expect-error: an unused+ // expect-error directive fails the typecheck when the cliff recedes.carbon?.from("customer").select(diff --git a/apps/erp/app/modules/items/items.service.test.ts b/apps/erp/app/modules/items/items.service.test.tsindex 5aed6464b8..3d24126b15 100644--- a/apps/erp/app/modules/items/items.service.test.ts+++ b/apps/erp/app/modules/items/items.service.test.ts@@ -2,52 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import { describe, expect, it } from "vitest";import {- type CompiledQuery,- type DatabaseConnection,- DummyDriver,- Kysely as KyselyClient,- PostgresAdapter,- PostgresIntrospector,- PostgresQueryCompiler,- type QueryResult-} from "kysely";-import { beforeEach, describe, expect, it, vi } from "vitest";--// diffMethod now lives in items.service. Importing the real module drags in the-// items.service graph, which transitively loads @carbon/content/glossary — whose-// module-load-time Lingui `msg` macro isn't transformed under plain vitest and-// throws. The pure diffMethod under test needs none of it, so stub glossary; the-// diffMethod under test stays the genuine implementation.-vi.mock("@carbon/content/glossary", () => ({- terms: {},- getEntry: vi.fn(),- lookupEntry: vi.fn(),- hasEntry: vi.fn(),- termSlug: vi.fn()-}));--// The postings (get-method copies a revision's make method) run their own-// transactions; the boundary here is the call.-const { serverFnInvoke } = vi.hoisted(() => ({ serverFnInvoke: vi.fn() }));-vi.mock("../shared/shared.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- invokePosting: (_from: unknown, name: string, input: unknown) =>- serverFnInvoke(name, input)-}));--const {- createRevision,- deleteItem,diffMethod,duplicateMethodOperationStep,+ getItemDemand,getLockVerdict,getUnreleasedChangeOrderIssue,getUnreleasedChangeOrderItems,- LOCKED_REVISION_MESSAGE,- removeChangeNoticeAffectedItem-} = await import("./items.service");+ LOCKED_REVISION_MESSAGE+} from "./items.service";// A minimal live methodMaterial row (only the fields diffMethod compares + id).function baseMaterial(over: Record<string, unknown> = {}) {@@ -580,347 +544,6 @@ describe("diffMethod — supplier parts", () => {});});-// The boundary is the Postgres wire: a driver that records what Kysely sends-// and answers the item insert with the id the database would have generated.-// `failOn` makes the first statement containing that text throw, as the-// database would on a constraint violation (`code` is its SQLSTATE).-class RecordingDriver extends DummyDriver {- readonly sent: CompiledQuery[] = [];- readonly log: string[] = [];- constructor(- private readonly failOn?: string,- private readonly code?: string- ) {- super();- }- override async acquireConnection(): Promise<DatabaseConnection> {- return {- executeQuery: async <R>(- query: CompiledQuery- ): Promise<QueryResult<R>> => {- if (this.failOn && query.sql.includes(this.failOn)) {- throw Object.assign(- new Error(`failed: ${this.failOn}`),- this.code ? { code: this.code } : {}- );- }- this.sent.push(query);- this.log.push(query.sql);- const rows = query.sql.startsWith('insert into "item"')- ? [{ id: "item-b" }]- : [];- return { rows: rows as R[] };- },- // biome-ignore lint/correctness/useYield: never streamed- streamQuery: async function* () {- throw new Error("not streamed");- }- };- }- override async beginTransaction() {- this.log.push("BEGIN");- }- override async commitTransaction() {- this.log.push("COMMIT");- }- override async rollbackTransaction() {- this.log.push("ROLLBACK");- }-}--function recordingDatabase(failOn?: string, code?: string) {- const driver = new RecordingDriver(failOn, code);- const db = new KyselyClient<KyselyDatabase>({- dialect: {- createAdapter: () => new PostgresAdapter(),- createDriver: () => driver,- createIntrospector: (k) => new PostgresIntrospector(k),- createQueryCompiler: () => new PostgresQueryCompiler()- }- }) as unknown as Kysely<KyselyDatabase>;- return { db, driver };-}--describe("createRevision", () => {- const item = {- id: "item-a",- readableId: "P-100",- revision: "A",- name: "Bracket",- type: "Part",- replenishmentSystem: "Make",- defaultMethodType: "Make to Order",- itemTrackingType: "Inventory",- unitOfMeasureCode: "EA",- description: null,- sourcingType: "Specified",- thumbnailPath: null,- mpn: null,- modelUploadId: null,- companyId: "c1"- } as never;-- beforeEach(() => {- serverFnInvoke.mockReset().mockResolvedValue({ data: null, error: null });- });-- // The caller's supabase client: the permission gate.- function revisionClient(gate: { error: { message: string } | null }) {- const rpc = vi.fn().mockResolvedValue({ data: null, ...gate });- return { client: { rpc } as never, rpc };- }-- it("inserts the revision and what it inherits in one transaction", async () => {- const { client, rpc } = revisionClient({ error: null });- const { db, driver } = recordingDatabase();-- const result = await createRevision(client, db, {- item,- revision: "B",- createdBy: "u1"- });-- expect(result).toEqual({ data: { id: "item-b" }, error: null });- expect(rpc).toHaveBeenCalledWith("assert_company_access", {- p_company_id: "c1",- p_permission: "parts_create"- });-- // The item first (its interceptor creates the rows the updates land on),- // and the price breaks after the supplier parts they hang off.- expect(- driver.log.map((sql) => sql.match(/^\w+( into)? "\w+"|^\w+$/)?.[0])- ).toEqual([- "BEGIN",- 'insert into "item"',- 'update "itemReplenishment"',- 'update "itemPlanning"',- 'update "itemCost"',- 'insert into "supplierPart"',- 'insert into "supplierPartPrice"',- "COMMIT"- ]);-- const [insert, ...copies] = driver.sent;- expect(insert.parameters).toEqual(- expect.arrayContaining(["P-100", "B", "Bracket", "c1", "u1", true])- );- // Kysely bypasses RLS: both sides of every statement name the company,- // and the rows move from the source revision to the new one only.- for (const query of copies) {- expect(query.parameters).toContain("c1");- expect(query.parameters).toContain("item-a");- expect(query.parameters).toContain("item-b");- }- const [replenishment, planning, , supplierParts, prices] = copies.map(- (query) => query.sql- );- expect(replenishment).toContain(- 'where "target"."itemId" = $3 and "target"."companyId" = $4 and "source"."itemId" = $5 and "source"."companyId" = $6'- );- expect(planning).toContain('"target"."locationId" = "source"."locationId"');- expect(supplierParts).toContain('where "itemId" = $3 and "companyId" = $4');- expect(prices).toContain(- '"target"."supplierId" = "source"."supplierId" and "target"."companyId" = "source"."companyId"'- );-- // The method is copied once the revision is committed.- expect(serverFnInvoke).toHaveBeenCalledWith("get-method", {- type: "itemToItem",- sourceId: "item-a",- targetId: "item-b"- });- });-- it("leaves no revision behind when the copy fails", async () => {- const { client } = revisionClient({ error: null });- const { db, driver } = recordingDatabase('insert into "supplierPart"');-- const result = await createRevision(client, db, {- item,- revision: "B",- createdBy: "u1"- });-- expect(result).toEqual({- data: null,- error: { message: 'failed: insert into "supplierPart"' }- });- // The item insert rolls back with the copy; there is nothing to clean up.- expect(driver.log.at(-1)).toBe("ROLLBACK");- expect(driver.log).not.toContain("COMMIT");- expect(driver.log.some((sql) => sql.startsWith("delete"))).toBe(false);- expect(serverFnInvoke).not.toHaveBeenCalled();- });-- it("writes nothing for a caller who cannot create parts in the company", async () => {- const denied = { message: "Not authorized for this company" };- const { client } = revisionClient({ error: denied });- const { db, driver } = recordingDatabase();-- const result = await createRevision(client, db, {- item,- revision: "B",- createdBy: "u1"- });-- expect(result).toEqual({ data: null, error: denied });- expect(driver.log).toEqual([]);- expect(serverFnInvoke).not.toHaveBeenCalled();- });-});--describe("deleteItem", () => {- function gateClient(gate: { error: { message: string } | null }) {- const rpc = vi.fn().mockResolvedValue({ data: null, ...gate });- return { client: { rpc } as never, rpc };- }-- it("deletes the item's price breaks and the item in one transaction", async () => {- const { client, rpc } = gateClient({ error: null });- const { db, driver } = recordingDatabase();-- const result = await deleteItem(client, db, "item-b", "c1");-- expect(result).toEqual({ data: null, error: null });- expect(rpc).toHaveBeenCalledWith("assert_company_access", {- p_company_id: "c1",- p_permission: "parts_delete"- });- // A price break restricts the delete of its supplier part, which the item- // delete cascades to, so the price breaks go first.- expect(driver.log).toEqual([- "BEGIN",- 'delete from "supplierPartPrice" where "companyId" = $1 and "supplierPartId" in (select "id" from "supplierPart" where "itemId" in ($2) and "companyId" = $3)',- 'delete from "item" where "id" in ($1) and "companyId" = $2',- "COMMIT"- ]);- expect(driver.sent.map((query) => query.parameters)).toEqual([- ["c1", "item-b", "c1"],- ["item-b", "c1"]- ]);- });-- it("keeps the price breaks when the item itself cannot be deleted", async () => {- const { client } = gateClient({ error: null });- const { db, driver } = recordingDatabase('delete from "item"', "23503");-- const result = await deleteItem(client, db, "item-b", "c1");-- // The route maps a 23503 to its friendly message, so the code survives.- expect(result).toEqual({- data: null,- error: { code: "23503", message: 'failed: delete from "item"' }- });- expect(driver.log.at(-1)).toBe("ROLLBACK");- expect(driver.log).not.toContain("COMMIT");- });-- it("writes nothing for a caller who cannot delete parts in the company", async () => {- const denied = { message: "Not authorized for this company" };- const { client } = gateClient({ error: denied });- const { db, driver } = recordingDatabase();-- const result = await deleteItem(client, db, "item-b", "c1");-- expect(result).toEqual({ data: null, error: denied });- expect(driver.log).toEqual([]);- });-});--describe("removeChangeNoticeAffectedItem", () => {- // The caller's supabase client: reads the affected row, vouches for the- // delete, and removes the affected row at the end.- function affectedItemClient(row: Record<string, unknown>) {- const deleted: string[] = [];- const client = {- rpc: vi.fn().mockResolvedValue({ data: null, error: null }),- from: (table: string) => {- const builder = {- select: () => builder,- eq: () => builder,- maybeSingle: () => Promise.resolve({ data: row, error: null }),- delete: () => {- deleted.push(table);- return builder;- },- then: (onF: (v: unknown) => unknown) =>- Promise.resolve({ data: null, error: null }).then(onF)- };- return builder;- }- };- return { client: client as never, deleted };- }-- it("discards a Revision draft, price breaks first, then removes the row", async () => {- const { client, deleted } = affectedItemClient({- draftMakeMethodId: "mm-1",- newItemId: "item-b"- });- const { db, driver } = recordingDatabase();-- const result = await removeChangeNoticeAffectedItem(- client,- db,- "aff-1",- "c1"- );-- expect(result.error).toBeNull();- // The draft method goes with its item, so only the item is deleted.- expect(- driver.log.map((sql) => sql.match(/^delete from "\w+"|^\w+$/)?.[0])- ).toEqual([- "BEGIN",- 'delete from "supplierPartPrice"',- 'delete from "item"',- "COMMIT"- ]);- expect(deleted).toEqual(["changeOrderAffectedItem"]);- });-- it("deletes only the Draft method for a Version", async () => {- const { client, deleted } = affectedItemClient({- draftMakeMethodId: "mm-1",- newItemId: null- });- const { db, driver } = recordingDatabase();-- await removeChangeNoticeAffectedItem(client, db, "aff-1", "c1");-- expect(driver.log).toEqual([- "BEGIN",- 'delete from "makeMethod" where "id" in ($1) and "companyId" = $2',- "COMMIT"- ]);- expect(deleted).toEqual(["changeOrderAffectedItem"]);- });-- it("keeps the affected row when its draft cannot be discarded", async () => {- const { client, deleted } = affectedItemClient({- draftMakeMethodId: "mm-1",- newItemId: "item-b"- });- const { db, driver } = recordingDatabase('delete from "item"', "23503");-- const result = await removeChangeNoticeAffectedItem(- client,- db,- "aff-1",- "c1"- );-- expect(result.error).toEqual({- code: "23503",- message: 'failed: delete from "item"'- });- expect(driver.log.at(-1)).toBe("ROLLBACK");- // The row is the only pointer at the draft; it stays with it.- expect(deleted).toEqual([]);- });-});-describe("diffMethod — attributes", () => {it("reports one entry per changed attribute column", () => {const { attributes } = diffMethod({@@ -970,40 +593,30 @@ describe("diffMethod — attributes", () => {});describe("getItemDemand", () => {+ // Answers every table with its rows, or with the error given for it.function mockClient(rowsByTable: Record<string, unknown[]>,errorsByTable: Record<string, unknown> = {}) {- const reads: Array<{- table: string;- filters: Array<[string, string, unknown]>;- }> = [];- const client: any = {- from: (table: string) => {- const read = { table, filters: [] as Array<[string, string, unknown]> };- reads.push(read);- const builder: any = {- select: () => builder,- eq: (column: string, value: unknown) => {- read.filters.push(["eq", column, value]);- return builder;- },- in: (column: string, value: unknown) => {- read.filters.push(["in", column, value]);- return builder;- },- order: () => builder,- then: (resolve: (v: unknown) => void) =>- resolve(- errorsByTable[table]- ? { data: null, error: errorsByTable[table] }- : { data: rowsByTable[table] ?? [], error: null }- )- };- return builder;- }+ return {+ client: {+ from: (table: string) => {+ const builder: any = {+ select: () => builder,+ eq: () => builder,+ in: () => builder,+ order: () => builder,+ then: (resolve: (v: unknown) => void) =>+ resolve(+ errorsByTable[table]+ ? { data: null, error: errorsByTable[table] }+ : { data: rowsByTable[table] ?? [], error: null }+ )+ };+ return builder;+ }+ } as any};- return { client, reads };}const args = {@@ -1013,36 +626,7 @@ describe("getItemDemand", () => {periods: ["p1", "p2"]};- it("reads demandProjection alongside demandActual and demandForecast", async () => {- const { getItemDemand } = await import("./items.service");- const { client, reads } = mockClient({});-- await getItemDemand(client, args);-- expect(reads.map((r) => r.table).sort()).toEqual([- "demandActual",- "demandForecast",- "demandProjection"- ]);- });-- it("scopes the projection read to the item, location, company and periods", async () => {- const { getItemDemand } = await import("./items.service");- const { client, reads } = mockClient({});-- await getItemDemand(client, args);-- const projectionRead = reads.find((r) => r.table === "demandProjection");- expect(projectionRead?.filters).toEqual([- ["eq", "itemId", "item_1"],- ["eq", "locationId", "loc_1"],- ["eq", "companyId", "co_1"],- ["in", "periodId", ["p1", "p2"]]- ]);- });-it("returns the projection rows as `projections`, defaulting every series to []", async () => {- const { getItemDemand } = await import("./items.service");const projectionRow = {id: "dp_1",itemId: "item_1",@@ -1063,8 +647,6 @@ describe("getItemDemand", () => {});it("tells an item with no demand apart from a failed read", async () => {- const { getItemDemand } = await import("./items.service");-const empty = await getItemDemand(mockClient({}).client, args);expect(empty.error).toBeNull();@@ -1078,39 +660,28 @@ describe("getItemDemand", () => {});describe("getLockVerdict", () => {- it("allows edits when the revision is not locked", () => {- for (const releaseControl of ["off", "warn", "enforce"] as const) {+ it.each(["off", "warn", "enforce"] as const)(+ "allows edits on an unlocked revision under release control %s",+ (releaseControl) => {expect(getLockVerdict({ isLocked: false, releaseControl })).toEqual({ok: true,warn: false});}- });-- it("allows edits on a locked revision when release control is off", () => {- expect(getLockVerdict({ isLocked: true, releaseControl: "off" })).toEqual({- ok: true,- warn: false- });- });-- it("allows edits with a warning on a locked revision when release control is warn", () => {- expect(getLockVerdict({ isLocked: true, releaseControl: "warn" })).toEqual({- ok: true,- warn: true,- message: LOCKED_REVISION_MESSAGE- });- });-- it("blocks edits on a locked revision when release control is enforce", () => {- expect(- getLockVerdict({ isLocked: true, releaseControl: "enforce" })- ).toEqual({- ok: false,- warn: false,- message: LOCKED_REVISION_MESSAGE- });- });+ );++ it.each([+ ["off", { ok: true, warn: false }],+ ["warn", { ok: true, warn: true, message: LOCKED_REVISION_MESSAGE }],+ ["enforce", { ok: false, warn: false, message: LOCKED_REVISION_MESSAGE }]+ ] as const)(+ "gives a locked revision under release control %s the matching verdict",+ (releaseControl, verdict) => {+ expect(getLockVerdict({ isLocked: true, releaseControl })).toEqual(+ verdict+ );+ }+ );});type Row = Record<string, unknown> | null;diff --git a/apps/erp/app/modules/postings.server.ts b/apps/erp/app/modules/postings.server.tsindex 74ff0976ba..b7c7664230 100644--- a/apps/erp/app/modules/postings.server.ts+++ b/apps/erp/app/modules/postings.server.ts@@ -32,7 +32,7 @@ import * as shared from "./shared/shared.service";import { invokePosting } from "./shared/shared.service";/**- * The permission each posting checks a caller's client against. Pinned by+ * The permission each posting checks a caller's client against. Checked by* `apps/erp/test/posting-permissions.test.ts`.*/export const postingPermissions = {diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex 4a59c0ed03..7a18321daa 100644--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@ -145,7 +145,7 @@ pnpm --filter erp test- **Job edits** (`production.server.ts`, published) — `updateJobDetails` (the details form), `configureJob`, `createJob` (`x+/job+/new.tsx`: the records must be the company's, refused for an item an unreleased change notice holds and for a Make to Asset item that cannot complete to an asset; the route shows those two on the item field), `createJobs` (`x+/job+/bulk.new.tsx`), `insertJob` (the API's and workflows' create: Draft or Planned only), `createSalesOrderLineJob` (unpublished, `x+/sales-order+/$orderId.$lineId.job.tsx`; the line must be on the order) and `convertSalesOrderLinesToJobs` (`$orderId.lines.jobs.tsx`). Every job creation goes through `jobCreationRefusal` (the records are the company's, no unreleased change notice holds the item, the Make to Asset rule); `orderPlannedJobs` skips an item a change notice holds. `deleteJobs` and the property panel's / jobs table's field writes through `x+/job+/update.tsx` — `setJobItem` (re-pulls the method), `setJobDeadline` (re-ranks priority, one read and one write for all jobs), `setJobQuantity` (recalculates), `setJobSalesOrderLine`, `setJobFields` — and `updateJobDetails` and `configureJob` refuse a locked job (`readUnlockedJobs` / `requireJob`).- **Job method** (`production.server.ts`, published) — Get Method is `copyMethodToJob` (`upsertJobMethod`, then the job's requirements and dependencies) and `copyMethodToMaterial`; `createJobMaterial` / `updateJobMaterial` / `deleteJobMaterial` / `deleteJobMaterials` and `createJobOperation` / `updateJobOperation` / `deleteJobOperation` / `deleteJobOperations` (the plural two are unpublished: Delete Selected, one recalculation) / `reorderJobOperations` / `setJobOperationStatus` (a Done operation returns its unconsumed picks) / `setJobOperationDueDate` / `syncJobOperationProcedure` back the bill of material and bill of process routes under `x+/job+/methods+/`; Get Method and the material, operation and procedure writes refuse a locked job (`requireJob`). Save Method (`x+/job+/methods+/save.tsx`) is `upsertMakeMethodFromJob` / `upsertMakeMethodFromJobMethod`: parts update and the target method's revision lock, as the items' Save Method. `completeOperation` (published) reports a good quantity on an untracked operation: it records it, backflushes (`issue`), and at the target sets the operation Done, posts its ended events and returns its picks. `createProductionEvent` / `updateProductionEvent` save a production event and post an ended one to the GL (`post-production-event`; a skipped posting is returned as `postingError`). `createProductionQuantity` records a production quantity (refuses a locked job, keeps a scrap reason only on Scrap); `updateProductionQuantity` corrects one and needs accounting update, so it is not published. The procedure properties panel posts to `setProcedureFields`. The bare row writes (`upsertJobMaterial`, `upsertJobOperation`, `upsertJobMethod`, `upsertProductionEvent`, `updateJob`) are building blocks in `production.service.ts` and are never tools.- `cancelJob` (`production.server.ts`, published as `production_cancelJob`) — the one cancel path, used by the job page's Cancel (`x+/job+/$jobId.cancel.tsx`), the status route and planning's Cancel action: refuses another company's job (`notFound`), sets Cancelled and clears the assignee only while the job is in `fromStatuses` (default `CANCELLABLE_JOB_STATUSES`; a refusal is a `conflict` and changes nothing), then returns its unconsumed picked material (`post-picking` `returnJobRemainders`, which sweeps only a Completed or Cancelled job) and cancels its open picking-list lines; a failure of either is a `warning`, the job stays Cancelled. Pinned by `test/database/cancel-job.test.ts`. Planning edits a job only while `isJobEditableFromPlanning` (`production.models.ts`: Draft / Planned)-- `getPlanningActions` / `getPlanningActionsByIds` — the persisted MRP worklist (`planningAction`, written by `generatePlanningActions` in `@carbon/planning` after every MRP run; statuses `Open` / `Dismissed` / `Actioned`). `dismissPlanningActions` / `reopenDismissedPlanningActions` (Dismissed ↔ Open; both return the ids they changed, which the routes report), `markPlanningActionsActioned` (the conditional Open → Actioned claim that is the apply path's lock — an empty result means another apply got there first; it returns the row's suggested quantity and date, which Apply writes instead of the page's possibly stale read) and `reopenPlanningActions` (its rollback, Actioned → Open), `assignPlanningActions` (sets the assignee and marks it overridden so the next MRP run keeps it; Open and Dismissed rows only, returning the ids it changed). `settleNewSupplyPlanningActions` is the page's Order button's settle: the suggested orders it submits carry no action id, so after the PO lines (`Order`) or jobs (`Make`) are created it flips the Open / Dismissed action of each ordered (item, week) pair at the location to Actioned — otherwise the suggestion stayed on the page beside its order until the next MRP run. An Apply reads its actions (`getPlanningActionsByIds`) and their jobs / PO lines in one statement each (Kysely, the ids as parameters — never a PostgREST URL), then applies set-based: `applyProductionPlanningDateActions(db, …)` moves every Expedite / Defer in one transaction (the claim, the jobs, the jobs already on the target dates, one UPDATE of due date + deadline type + priority via the pure `nextJobPriority` — a "No Deadline" job becomes `Soft Deadline`, `deadlineTypeForPlanningDate`, since the job form hides the due date for No Deadline), and the route sends one `schedule-inputs-changed` event for the batch; Increase / Decrease / Cancel call postings with their own transactions, so they run per job, three jobs at a time, each claimed right before its change. The transaction-scoped claim and release live in `planning-action-claims.ts` (`claimPlanningActions` / `releasePlanningActionClaims`), shared with purchasing's `applyPurchasingPlanningActions`. Bad input to either planning route answers 400, a failed read or write 500. `releasePlanningActionClaim` gives a failed per-job apply's claim back (deleting it instead when MRP has already written an Open row for the same need), and `updatePlanningJob` is planning's single-job write (the drawer's inline edit, and Increase / Decrease), guarded on Draft / Planned in the UPDATE itself; a quantity change restates `scrapQuantity` from the item's scrap rate. `planDraftJob` (`production.server.ts`) is the drawer's Plan on a Draft job (`planJob` intent), in `releaseJobs`' order: the requirements recalculation (a failure leaves the job Draft), the guarded Draft → Planned flip, then MRP, so the job counts as supply. It sends no scheduler notice — the scheduler places only released jobs. `replanAfterItemChange` (`production.server.ts`) runs MRP after an item's planning or manufacturing settings are saved, so the planning pages follow them at once. `planningAction` is read-only through the API; its writers use the service role. Applied from `x+/production+/planning.update.tsx` (one service-function call per `action`: `order` (`orderPlannedJobs`), `updateJob` (`updatePlannedJob`), `planJob` (`planJobFromPlanning`), `apply` and its typed aliases (`applyPlanningActions`), `dismiss` (`dismissProductionPlanningActions`), `reopen` (`reopenProductionPlanningActions`), `assign` (`assignProductionPlanningActions`); a dismiss / reopen / assign that changes nothing is a `conflict`) and `x+/purchasing+/planning.update.tsx`; `usePlanningActions` reads both routes' answers; UI in `ui/Planning/`: `ProductionPlanningTable` + `ProductionPlanningOrderDrawer`, `planningColumns.tsx` (the column set shared with purchasing: the Stock Availability week strip via `PlanningWeekStrip` + `planning-week-geometry.ts`, `LatestOrderDate`, `PlanningFence` + `planning-fence.ts`), `PlanningActionLines` (the expanded row), `PlanningOrderGrids` + `PlanningDrawerParts` (the drawer's suggested / open-order grids, `periodIdFor`, the "N More After" button), `usePlanningActions` (the dismiss / reopen / assign / apply fetcher), and `planning-action-scope.ts` (`resolvePlanningActionScope`, `actionsOfTypes`, `PLANNING_ACTIONS_COLUMN`, `PLANNING_ASSIGNEE_COLUMN`, `PLANNING_DRAWER_PARAM` — pure, re-exported from `production.models.ts` so vitest can import it), `planned-orders-from-actions.ts` (pure: the drawer's suggested orders, the row's Order / Make quantity and a bulk order are the item's open Order / Make actions — `openNewSupplyActions`, `plannedOrdersFromActions`, `productionOrdersFromActions`, `supplierConversionFactor` — never sized again on screen, so a shortfall MRP folded into an Increase is not offered twice), `planning-increase.ts` (pure: `chartedOrderQuantity` charts an order at its open Increase), and `planning-review.ts` (pure: `planningActionNeedsReview` — Review vs Apply from the order's LIVE status, `purchaseOrderStatus` / `jobStatus` from `getPlanningActions`, not MRP's run-time `requiresManualAction` stamp, so a PO reopened since applies at once; a date move on a supplier-promised line stays Review — and `purchaseOrderPlanningMenu`, which order commands a row's ⋯ offers; `PlanningActionHandlers.purchaseOrderMenuItems` carries them, purchasing only). Both planning grids put the open order drawer's item in the address (`?item=<itemId>`, `useLinkedDrawerItem` in `~/hooks/useDrawerItem`), so a link reopens it; the loader reads that row on its own (`drawerItem`) when it is not on the page. Tests: `planning-action-writes.test.ts`, `apps/erp/test/apply-production-planning-date-actions.test.ts`, `planning-action-scope.test.ts`, `planning-fence.test.ts`, `planning-increase.test.ts`, `planning-review.test.ts`, `planned-orders-from-actions.test.ts`, `planning-week-geometry.test.ts`+- `getPlanningActions` / `getPlanningActionsByIds` — the persisted MRP worklist (`planningAction`, written by `generatePlanningActions` in `@carbon/planning` after every MRP run; statuses `Open` / `Dismissed` / `Actioned`). `dismissPlanningActions` / `reopenDismissedPlanningActions` (Dismissed ↔ Open; both return the ids they changed, which the routes report), `markPlanningActionsActioned` (the conditional Open → Actioned claim that is the apply path's lock — an empty result means another apply got there first; it returns the row's suggested quantity and date, which Apply writes instead of the page's possibly stale read) and `reopenPlanningActions` (its rollback, Actioned → Open), `assignPlanningActions` (sets the assignee and marks it overridden so the next MRP run keeps it; Open and Dismissed rows only, returning the ids it changed). `settleNewSupplyPlanningActions` is the page's Order button's settle: the suggested orders it submits carry no action id, so after the PO lines (`Order`) or jobs (`Make`) are created it flips the Open / Dismissed action of each ordered (item, week) pair at the location to Actioned — otherwise the suggestion stayed on the page beside its order until the next MRP run. An Apply reads its actions (`getPlanningActionsByIds`) and their jobs / PO lines in one statement each (Kysely, the ids as parameters — never a PostgREST URL), then applies set-based: `applyProductionPlanningDateActions(db, …)` moves every Expedite / Defer in one transaction (the claim, the jobs, the jobs already on the target dates, one UPDATE of due date + deadline type + priority via the pure `nextJobPriority` — a "No Deadline" job becomes `Soft Deadline`, `deadlineTypeForPlanningDate`, since the job form hides the due date for No Deadline), and the route sends one `schedule-inputs-changed` event for the batch; Increase / Decrease / Cancel call postings with their own transactions, so they run per job, three jobs at a time, each claimed right before its change. The transaction-scoped claim and release live in `planning-action-claims.ts` (`claimPlanningActions` / `releasePlanningActionClaims`), shared with purchasing's `applyPurchasingPlanningActions`. Bad input to either planning route answers 400, a failed read or write 500. `releasePlanningActionClaim` gives a failed per-job apply's claim back (deleting it instead when MRP has already written an Open row for the same need), and `updatePlanningJob` is planning's single-job write (the drawer's inline edit, and Increase / Decrease), guarded on Draft / Planned in the UPDATE itself; a quantity change restates `scrapQuantity` from the item's scrap rate. `planDraftJob` (`production.server.ts`) is the drawer's Plan on a Draft job (`planJob` intent), in `releaseJobs`' order: the requirements recalculation (a failure leaves the job Draft), the guarded Draft → Planned flip, then MRP, so the job counts as supply. It sends no scheduler notice — the scheduler places only released jobs. `replanAfterItemChange` (`production.server.ts`) runs MRP after an item's planning or manufacturing settings are saved, so the planning pages follow them at once. `planningAction` is read-only through the API; its writers use the service role. Applied from `x+/production+/planning.update.tsx` (one service-function call per `action`: `order` (`orderPlannedJobs`), `updateJob` (`updatePlannedJob`), `planJob` (`planJobFromPlanning`), `apply` and its typed aliases (`applyPlanningActions`), `dismiss` (`dismissProductionPlanningActions`), `reopen` (`reopenProductionPlanningActions`), `assign` (`assignProductionPlanningActions`); a dismiss / reopen / assign that changes nothing is a `conflict`) and `x+/purchasing+/planning.update.tsx`; `usePlanningActions` reads both routes' answers; UI in `ui/Planning/`: `ProductionPlanningTable` + `ProductionPlanningOrderDrawer`, `planningColumns.tsx` (the column set shared with purchasing: the Stock Availability week strip via `PlanningWeekStrip` + `planning-week-geometry.ts`, `LatestOrderDate`, `PlanningFence` + `planning-fence.ts`), `PlanningActionLines` (the expanded row), `PlanningOrderGrids` + `PlanningDrawerParts` (the drawer's suggested / open-order grids, `periodIdFor`, the "N More After" button), `usePlanningActions` (the dismiss / reopen / assign / apply fetcher), and `planning-action-scope.ts` (`resolvePlanningActionScope`, `actionsOfTypes`, `PLANNING_ACTIONS_COLUMN`, `PLANNING_ASSIGNEE_COLUMN`, `PLANNING_DRAWER_PARAM` — pure, re-exported from `production.models.ts` so vitest can import it), `planned-orders-from-actions.ts` (pure: the drawer's suggested orders, the row's Order / Make quantity and a bulk order are the item's open Order / Make actions — `openNewSupplyActions`, `plannedOrdersFromActions`, `productionOrdersFromActions`, `supplierConversionFactor` — never sized again on screen, so a shortfall MRP folded into an Increase is not offered twice), `planning-increase.ts` (pure: `chartedOrderQuantity` charts an order at its open Increase), and `planning-review.ts` (pure: `planningActionNeedsReview` — Review vs Apply from the order's LIVE status, `purchaseOrderStatus` / `jobStatus` from `getPlanningActions`, not MRP's run-time `requiresManualAction` stamp, so a PO reopened since applies at once; a date move on a supplier-promised line stays Review — and `purchaseOrderPlanningMenu`, which order commands a row's ⋯ offers; `PlanningActionHandlers.purchaseOrderMenuItems` carries them, purchasing only). Both planning grids put the open order drawer's item in the address (`?item=<itemId>`, `useLinkedDrawerItem` in `~/hooks/useDrawerItem`), so a link reopens it; the loader reads that row on its own (`drawerItem`) when it is not on the page. Tests: `apps/erp/test/apply-production-planning-date-actions.test.ts` (`nextJobPriority`, `planJobDateMoves`), `planning-action-scope.test.ts`, `planning-fence.test.ts`, `planning-increase.test.ts`, `planning-review.test.ts`, `planned-orders-from-actions.test.ts`, `planning-week-geometry.test.ts`- `upsertMaintenanceDispatch` / `upsertMaintenanceSchedule` — maintenance management- `updateAssemblyStepHiddenComponents` — autosave for a step's hidden list (route `x+/assembly+/$id.steps.hidden.$stepId.tsx`). The rule "a step never hides its own parts" lives in ONE place, the `assembly_step_strip_own_hidden_components` BEFORE trigger (migration `20260925063121`), which strips + dedupes on every insert/update of either array — no service strips it by hand.- `getAssemblyInstruction(s)` / `upsertAssemblyInstructionStep` / `getAssemblyInstructionStepMaterials` — assembly instruction authoring; the step upsert derives `instructionText` from the tiptap `description` (viewer/MES consume the plain text)diff --git a/apps/erp/app/modules/production/planning-action-writes.test.ts b/apps/erp/app/modules/production/planning-action-writes.test.tsdeleted file mode 100644index 19a3ec4a1a..0000000000--- a/apps/erp/app/modules/production/planning-action-writes.test.ts+++ /dev/null@@ -1,267 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import type { KyselyDatabase } from "@carbon/database/client";-import {- type CompiledQuery,- type DatabaseConnection,- DummyDriver,- Kysely,- PostgresAdapter,- PostgresIntrospector,- PostgresQueryCompiler,- type QueryResult-} from "kysely";-import { describe, expect, it, vi } from "vitest";-import type { PlanningActionKind } from "./production.service";--// Same module-graph stubs as production.service.test.ts: the functions under-// test need neither the glossary nor the Lingui macro.-vi.mock("@carbon/content/glossary", () => ({- terms: {},- getEntry: vi.fn(),- lookupEntry: vi.fn(),- hasEntry: vi.fn(),- termSlug: vi.fn(),- glossaryEntries: () => []-}));-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray | string, ...values: unknown[]) =>- Array.isArray(strings)- ? strings.reduce(- (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),- ""- )- : String(strings)-}));--const {- assignPlanningActions,- dismissPlanningActions,- getPlanningActionsByIds,- markPlanningActionsActioned,- reopenDismissedPlanningActions,- settleNewSupplyPlanningActions-} = await import("./production.service");--// The Postgres wire is the boundary: every statement is recorded as compiled-// SQL with its parameters, and the rows the database would have changed come-// back as the result.-class RecordingDriver extends DummyDriver {- readonly sent: CompiledQuery[] = [];- constructor(private readonly rows: unknown[] = []) {- super();- }- override async acquireConnection(): Promise<DatabaseConnection> {- return {- executeQuery: async <R>(- query: CompiledQuery- ): Promise<QueryResult<R>> => {- this.sent.push(query);- return { rows: this.rows as R[] };- },- // biome-ignore lint/correctness/useYield: never streamed- streamQuery: async function* () {- throw new Error("not streamed");- }- };- }-}--function database(changedIds: string[] = []) {- const driver = new RecordingDriver(changedIds.map((id) => ({ id })));- const db = new Kysely<KyselyDatabase>({- dialect: {- createAdapter: () => new PostgresAdapter(),- createDriver: () => driver,- createIntrospector: (k) => new PostgresIntrospector(k),- createQueryCompiler: () => new PostgresQueryCompiler()- }- });- return { db, driver };-}--const args = {- ids: ["a1", "a2", "a3"],- companyId: "c1",- userId: "u1",- kind: "Make" as PlanningActionKind-};--// The routes reported the ids they were SENT ("Dismissed 5") while the update-// skipped rows that had changed since the page loaded.-describe("planning action worklist writes return the rows they changed", () => {- it("dismiss changes only Open rows and returns their ids", async () => {- const { db, driver } = database(["a1"]);- const result = await dismissPlanningActions(db, args);- expect(result).toEqual({ data: [{ id: "a1" }], error: null });- const [statement] = driver.sent;- expect(statement?.sql).toMatch(/^update "planningAction"/);- expect(statement?.sql).toContain('"status" = $');- expect(statement?.sql).toContain('returning "id"');- expect(statement?.parameters).toContain("Open");- expect(statement?.parameters).toContain("c1");- });-- it("reopen changes only Dismissed rows and returns their ids", async () => {- const { db, driver } = database(["a2"]);- const result = await reopenDismissedPlanningActions(db, args);- expect(result).toEqual({ data: [{ id: "a2" }], error: null });- expect(driver.sent[0]?.parameters).toContain("Dismissed");- });-- // Assign had no status condition: it re-owned actions already applied.- it("assign never changes an applied action", async () => {- const { db, driver } = database(["a1", "a3"]);- const result = await assignPlanningActions(db, {- ...args,- assignee: "u2"- });- expect(result).toEqual({ data: [{ id: "a1" }, { id: "a3" }], error: null });- const [statement] = driver.sent;- expect(statement?.sql).toContain('"status" in ($');- expect(statement?.parameters).toEqual(- expect.arrayContaining(["Open", "Dismissed", "c1"])- );- expect(statement?.parameters).not.toContain("Actioned");- });-- // The claim is the lock of the apply path: only Open rows flip, in ONE- // statement, and the caller gets back exactly the rows it now holds.- it("claim flips only Open rows to Actioned in one statement", async () => {- const { db, driver } = database(["a1"]);- const result = await markPlanningActionsActioned(db, args);- expect(result).toEqual({ data: [{ id: "a1" }], error: null });- expect(driver.sent).toHaveLength(1);- expect(driver.sent[0]?.parameters).toEqual(- expect.arrayContaining(["Actioned", "Open", "c1", "a1", "a2", "a3"])- );- });-- // The writes run past row-level security, so the page's permission was the- // only check: a purchasing user could dismiss production's actions by id.- it.each([- ["dismiss", dismissPlanningActions],- ["reopen", reopenDismissedPlanningActions],- [- "assign",- (db: Kysely<KyselyDatabase>, a: typeof args) =>- assignPlanningActions(db, { ...a, assignee: "u2" })- ]- ] as const)("%s writes only its own page's actions", async (_, write) => {- const make = database(["a1"]);- await write(make.db, args);- expect(make.driver.sent[0]?.sql).toContain('"jobId" is not null');- expect(make.driver.sent[0]?.sql).not.toContain('"purchaseOrderLineId"');- expect(make.driver.sent[0]?.parameters).toContain("Make");-- const buy = database(["a1"]);- await write(buy.db, { ...args, kind: "Buy" });- expect(buy.driver.sent[0]?.sql).toContain(- '"purchaseOrderLineId" is not null'- );- expect(buy.driver.sent[0]?.sql).not.toContain('"jobId"');- expect(buy.driver.sent[0]?.parameters).toContain("Order");- });-- it("sends nothing for an empty id list", async () => {- const { db, driver } = database();- const result = await dismissPlanningActions(db, { ...args, ids: [] });- expect(result).toEqual({ data: [], error: null });- expect(driver.sent).toHaveLength(0);- });-});--// Apply read each action on its own; a batch of N is now one statement — and-// the ids travel as parameters, never in a PostgREST URL, so a bulk Apply on a-// page of busy items (hundreds of ids) cannot overrun the gateway.-describe("getPlanningActionsByIds", () => {- it("reads the whole batch in one company-scoped statement", async () => {- const ids = Array.from({ length: 500 }, (_, i) => `a${i}`);- const { db, driver } = database();- const result = await getPlanningActionsByIds(db, { ids, companyId: "c1" });- expect(result).toEqual({ data: [], error: null });- expect(driver.sent).toHaveLength(1);- const [statement] = driver.sent;- expect(statement?.sql).toMatch(/^select \* from "planningAction"/);- expect(statement?.sql).toContain('"id" in (');- expect(statement?.parameters).toContain("c1");- expect(statement?.parameters).toEqual(expect.arrayContaining(ids));- });-- it("reports a failed read instead of throwing", async () => {- const { db } = database();- const failing = db.withPlugin({- transformQuery: (args) => args.node,- transformResult: async () => {- throw new Error("connection refused");- }- });- const result = await getPlanningActionsByIds(failing, {- ids: ["a1"],- companyId: "c1"- });- expect(result).toEqual({- data: null,- error: { message: "connection refused" }- });- });-});--// The page's Order button raised PO lines and jobs but never touched the-// suggestions they answered, which stayed Open on the page until the next MRP-// run re-derived the worklist.-describe("settleNewSupplyPlanningActions", () => {- const settle = {- companyId: "c1",- locationId: "l1",- userId: "u1",- type: "Order" as const- };-- it("settles each ordered (item, week) in one statement", async () => {- const { db, driver } = database(["a1", "a2"]);- const result = await settleNewSupplyPlanningActions(db, {- ...settle,- ordered: [- { itemId: "i1", periodId: "p1" },- { itemId: "i1", periodId: "p1" },- { itemId: "i2", periodId: "p2" }- ]- });- expect(result).toEqual({ data: [{ id: "a1" }, { id: "a2" }], error: null });- expect(driver.sent).toHaveLength(1);- const [statement] = driver.sent;- expect(statement?.sql).toMatch(/^update "planningAction"/);- // pairs, never a cross product: ordering i1 in p1 and i2 in p2 must not- // settle i1's p2 suggestion- expect(statement?.sql).toContain(- '("itemId" = $9 and "periodId" = $10) or ("itemId" = $11 and "periodId" = $12)'- );- expect(statement?.parameters).toEqual([- "Actioned",- "u1",- expect.any(String),- "c1",- "l1",- "Order",- "Open",- "Dismissed",- "i1",- "p1",- "i2",- "p2"- ]);- });-- it("sends nothing when no order was placed", async () => {- const { db, driver } = database();- const result = await settleNewSupplyPlanningActions(db, {- ...settle,- ordered: []- });- expect(result).toEqual({ data: [], error: null });- expect(driver.sent).toHaveLength(0);- });-});diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.tsindex b223ca88b3..53ad202486 100644--- a/apps/erp/app/modules/production/production.models.ts+++ b/apps/erp/app/modules/production/production.models.ts@@ -200,6 +200,16 @@ export function isAssemblyPlanRunning(return job.status === "Queued" && age < ASSEMBLY_PLAN_QUEUED_STALE_MS;}+/** Start a motion plan unless the model is still converting or a plan is live. */+export function shouldStartAssemblyPlan(+ processingStatus: string | null | undefined,+ planJob: { status: string; createdAt: string } | null | undefined+): boolean {+ const isConverting =+ processingStatus === "Queued" || processingStatus === "Processing";+ return !isConverting && !isAssemblyPlanRunning(planJob);+}+export const jobOperationStatus = ["Todo","Ready",diff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.tsindex b62c187c51..6cc3a61acf 100644--- a/apps/erp/app/modules/production/production.server.ts+++ b/apps/erp/app/modules/production/production.server.ts@@ -94,7 +94,8 @@ import {productionQuantityValidator,salesOrderToJobValidator,scheduleJobUpdateValidator,- scheduleOperationReorderValidator+ scheduleOperationReorderValidator,+ shouldStartAssemblyPlan} from "./production.models";import type { JobStatus } from "./production.service";import * as service from "./production.service";@@ -5247,10 +5248,7 @@ export const generateAssemblySteps = defineServiceFn({result.modelUploadId)]);- const isConverting =- model.data?.processingStatus === "Queued" ||- model.data?.processingStatus === "Processing";- if (!isConverting && !isAssemblyPlanRunning(planJob.data)) {+ if (shouldStartAssemblyPlan(model.data?.processingStatus, planJob.data)) {await service.startAssemblyPlan(ctx, result.modelUploadId);}return { planning: true, created: 0, unmappedComponentCount: 0 };diff --git a/apps/erp/app/modules/production/production.service.test.ts b/apps/erp/app/modules/production/production.service.test.tsindex 2aa74add90..8ff7c2b115 100644--- a/apps/erp/app/modules/production/production.service.test.ts+++ b/apps/erp/app/modules/production/production.service.test.ts@@ -2,493 +2,223 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { describe, expect, it, vi } from "vitest";--// production.service's module graph transitively loads @carbon/content/glossary, whose-// module-load-time Lingui `msg` macros aren't transformed under plain vitest and-// throw. The functions under test need none of it, so stub glossary; the real-// implementations stay under test.-vi.mock("@carbon/content/glossary", () => ({- terms: {},- getEntry: vi.fn(),- lookupEntry: vi.fn(),- hasEntry: vi.fn(),- termSlug: vi.fn(),- glossaryEntries: () => []-}));--// The module graph also pulls @carbon/onboarding, whose content builds Lingui-// `msg` descriptors at module load — the macro isn't transformed under plain-// vitest, so raw `msg` throws. Stub it to a plain string builder so the content-// evaluates without the compiler.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray | string, ...values: unknown[]) =>- Array.isArray(strings)- ? strings.reduce(- (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),- ""- )- : String(strings)-}));--const {- planAssemblyStepMarkerSync,- planAssemblyStepMarkerRemap,- planOrphanStepAdoption,- maxToolQuantityByItem,+import { describe, expect, it } from "vitest";+import {buildAssemblyToolStepLinks,- duplicateJobOperationStep-} = await import("./production.service");+ maxToolQuantityByItem,+ planAssemblyStepMarkerRemap,+ planAssemblyStepMarkerSync,+ planOrphanStepAdoption+} from "./production.service";-// ── Assembly → BoP sync: marker reconciliation ───────────────────────────────describe("planAssemblyStepMarkerSync", () => {- it("maps existing synced steps by their source marker (update targets)", () => {- const { targetIdBySourceId } = planAssemblyStepMarkerSync(- ["src-1", "src-2"],- [- { id: "job-1", assemblyInstructionStepId: "src-1" },- { id: "job-2", assemblyInstructionStepId: "src-2" }- ]- );- expect(targetIdBySourceId.get("src-1")).toBe("job-1");- expect(targetIdBySourceId.get("src-2")).toBe("job-2");- });-- it("leaves a brand-new source unmapped (insert target)", () => {- const { targetIdBySourceId, staleTargetIds } = planAssemblyStepMarkerSync(- ["src-1", "src-new"],- [{ id: "job-1", assemblyInstructionStepId: "src-1" }]- );- expect(targetIdBySourceId.has("src-new")).toBe(false);- expect(staleTargetIds).toEqual([]);- });-- it("marks a synced step whose source was removed as stale (delete target)", () => {- const { staleTargetIds } = planAssemblyStepMarkerSync(- ["src-1"],- [- { id: "job-1", assemblyInstructionStepId: "src-1" },- { id: "job-2", assemblyInstructionStepId: "src-removed" }- ]- );- expect(staleTargetIds).toEqual(["job-2"]);+ it("updates marked steps, leaves new sources to insert, and marks removed ones stale", () => {+ expect(+ planAssemblyStepMarkerSync(+ ["src-1", "src-new"],+ [+ { id: "job-1", assemblyInstructionStepId: "src-1" },+ { id: "job-2", assemblyInstructionStepId: "src-removed" }+ ]+ )+ ).toEqual({+ targetIdBySourceId: new Map([+ ["src-1", "job-1"],+ ["src-removed", "job-2"]+ ]),+ staleTargetIds: ["job-2"]+ });});});-// ── Assembly version activation: marker remap across versions ────────────────describe("planAssemblyStepMarkerRemap", () => {- it("maps a v1 step id to the v2 step copied from it", () => {- const remap = planAssemblyStepMarkerRemap(- [{ id: "v1a", rootStepId: null }],- [{ id: "v2a", rootStepId: "v1a" }]- );- expect(remap.get("v1a")).toBe("v2a");- });-- it("maps across three versions via the flat root chain", () => {+ const step = (id: string, rootStepId: string | null = null) => ({+ id,+ rootStepId+ });++ it.each([+ [+ "maps a v1 step to the v2 step copied from it",+ [step("v1a")],+ [step("v2a", "v1a")],+ [["v1a", "v2a"]]+ ],// v3 copied from v2 still roots at v1.- const remap = planAssemblyStepMarkerRemap(- [{ id: "v2a", rootStepId: "v1a" }],- [{ id: "v3a", rootStepId: "v1a" }]- );- expect(remap.get("v2a")).toBe("v3a");- });-- it("maps regardless of reordering", () => {- const remap = planAssemblyStepMarkerRemap(- [- { id: "v1a", rootStepId: null },- { id: "v1b", rootStepId: null }- ],+ [+ "maps across versions through the flat root",+ [step("v2a", "v1a")],+ [step("v3a", "v1a")],+ [["v2a", "v3a"]]+ ],+ [+ "maps regardless of order",+ [step("v1a"), step("v1b")],+ [step("v2b", "v1b"), step("v2a", "v1a")],[- { id: "v2b", rootStepId: "v1b" },- { id: "v2a", rootStepId: "v1a" }+ ["v1a", "v2a"],+ ["v1b", "v2b"]]- );- expect(remap.get("v1a")).toBe("v2a");- expect(remap.get("v1b")).toBe("v2b");- });-- it("leaves a deleted step unmapped", () => {- const remap = planAssemblyStepMarkerRemap(+ ],+ [+ "leaves a deleted step unmapped",+ [step("v1a"), step("v1gone")],+ [step("v2a", "v1a")],+ [["v1a", "v2a"]]+ ],+ [+ "ignores a step added in the new version",+ [step("v1a")],+ [step("v2a", "v1a"), step("v2new")],+ [["v1a", "v2a"]]+ ],+ // Activation passes every sibling version as old steps.+ [+ "collapses every old version onto the new step",+ [step("v1a"), step("v2a", "v1a")],+ [step("v3a", "v1a")],[- { id: "v1a", rootStepId: null },- { id: "v1gone", rootStepId: null }- ],- [{ id: "v2a", rootStepId: "v1a" }]- );- expect(remap.get("v1a")).toBe("v2a");- expect(remap.has("v1gone")).toBe(false);- });-- it("ignores a step added in the new version", () => {- const remap = planAssemblyStepMarkerRemap(- [{ id: "v1a", rootStepId: null }],- [- { id: "v2a", rootStepId: "v1a" },- { id: "v2new", rootStepId: null }+ ["v1a", "v3a"],+ ["v2a", "v3a"]]+ ],+ ["does not map a step to itself", [step("same")], [step("same")], []]+ ])("%s", (_, oldSteps, newSteps, expected) => {+ expect(planAssemblyStepMarkerRemap(oldSteps, newSteps)).toEqual(+ new Map(expected as [string, string][]));- expect(remap.size).toBe(1);- });-- it("collapses every old version in the group onto the new step", () => {- // activateAssemblyInstructionVersion passes ALL sibling versions as- // otherVersionIds, so oldSteps can span v1 AND v2 while v3 is activated.- // Both collapse to the same target; harmless only because an operation's- // markers all come from ONE version, so at most one entry matches a row.- const remap = planAssemblyStepMarkerRemap(- [- { id: "v1a", rootStepId: null },- { id: "v2a", rootStepId: "v1a" }- ],- [{ id: "v3a", rootStepId: "v1a" }]- );- expect(remap.get("v1a")).toBe("v3a");- expect(remap.get("v2a")).toBe("v3a");- });-- it("does not map a step to itself", () => {- const remap = planAssemblyStepMarkerRemap(- [{ id: "same", rootStepId: null }],- [{ id: "same", rootStepId: null }]- );- expect(remap.size).toBe(0);});});-// ── Assembly → BoP sync: reclaiming orphaned (null-marker) steps ─────────────describe("planOrphanStepAdoption", () => {- it("adopts an orphan matching a source step on sortOrder and name", () => {- const adoption = planOrphanStepAdoption(- [{ id: "src1", title: "Fit cover", sortOrder: 1 }],- [{ id: "orphan1", name: "Fit cover", sortOrder: 1 }],- new Set()- );- expect(adoption.get("orphan1")).toBe("src1");- });-- it("ignores an orphan whose name differs", () => {- const adoption = planOrphanStepAdoption(- [{ id: "src1", title: "Fit cover", sortOrder: 1 }],- [{ id: "handmade", name: "Operator note", sortOrder: 1 }],- new Set()- );- expect(adoption.size).toBe(0);- });-- it("does not claim a source step an existing marked step already owns", () => {- const adoption = planOrphanStepAdoption(- [{ id: "src1", title: "Fit cover", sortOrder: 1 }],- [{ id: "orphan1", name: "Fit cover", sortOrder: 1 }],- new Set(["src1"])- );- expect(adoption.size).toBe(0);- });-- it("adopts a null-titled source step via its positional placeholder name", () => {- // The sync writes name = title || `Step ${index + 1}`, so a null title- // becomes "Step 1" on the job step. Comparing against the raw title would- // never match and would insert a duplicate instead of healing.- const adoption = planOrphanStepAdoption(- [{ id: "src1", title: null, sortOrder: 1 }],- [{ id: "orphan1", name: "Step 1", sortOrder: 1 }],- new Set()- );- expect(adoption.get("orphan1")).toBe("src1");- });-- it("uses the source's own index for the placeholder name", () => {- const adoption = planOrphanStepAdoption(- [- { id: "src1", title: "Real title", sortOrder: 1 },- { id: "src2", title: null, sortOrder: 2 }- ],- [{ id: "orphan2", name: "Step 2", sortOrder: 2 }],- new Set()- );- expect(adoption.get("orphan2")).toBe("src2");- });-- it("adopts orphans that follow the operation's own steps", () => {- const adoption = planOrphanStepAdoption(- [- { id: "src1", title: "Fit cover", sortOrder: 1 },- { id: "src2", title: "Torque bolts", sortOrder: 2 }- ],- [- { id: "own1", name: "Clean bench", sortOrder: 1 },- { id: "own2", name: "Check kit", sortOrder: 2 },- { id: "orphan1", name: "Fit cover", sortOrder: 3 },- { id: "orphan2", name: "Torque bolts", sortOrder: 4 }- ],- new Set()- );- expect([...adoption]).toEqual([- ["orphan1", "src1"],- ["orphan2", "src2"]- ]);- });-- it("adopts by position when sub-assembly rows leave gaps in the source order", () => {- const adoption = planOrphanStepAdoption(+ const src = (id: string, title: string | null, sortOrder: number) => ({+ id,+ title,+ sortOrder+ });+ const orphan = (id: string, name: string, sortOrder: number) => ({+ id,+ name,+ sortOrder+ });++ it.each([+ [+ "adopts an orphan matching a source step on sortOrder and name",+ [src("src1", "Fit cover", 1)],+ [orphan("orphan1", "Fit cover", 1)],+ [],+ [["orphan1", "src1"]]+ ],+ [+ "ignores an orphan whose name differs",+ [src("src1", "Fit cover", 1)],+ [orphan("handmade", "Operator note", 1)],+ [],+ []+ ],+ [+ "does not claim a source step a marked step already owns",+ [src("src1", "Fit cover", 1)],+ [orphan("orphan1", "Fit cover", 1)],+ ["src1"],+ []+ ],+ // The sync names an untitled step `Step ${index + 1}`.+ [+ "adopts an untitled source step by its placeholder name at its own index",+ [src("src1", "Real title", 1), src("src2", null, 2)],+ [orphan("orphan2", "Step 2", 2)],+ [],+ [["orphan2", "src2"]]+ ],+ [+ "adopts orphans that follow the operation's own steps",+ [src("src1", "Fit cover", 1), src("src2", "Torque bolts", 2)],[- { id: "src1", title: "Press bearing", sortOrder: 1 },- { id: "src2", title: "Fit hub", sortOrder: 3 }+ orphan("own1", "Clean bench", 1),+ orphan("own2", "Check kit", 2),+ orphan("orphan1", "Fit cover", 3),+ orphan("orphan2", "Torque bolts", 4)],+ [],[- { id: "orphan1", name: "Press bearing", sortOrder: 1 },- { id: "orphan2", name: "Fit hub", sortOrder: 2 }- ],- new Set()- );- expect([...adoption]).toEqual([- ["orphan1", "src1"],- ["orphan2", "src2"]- ]);- });-- it("adopts each orphan at most once", () => {- const adoption = planOrphanStepAdoption(+ ["orphan1", "src1"],+ ["orphan2", "src2"]+ ]+ ],+ [+ "adopts by position when sub-assembly rows leave gaps in the source order",+ [src("src1", "Press bearing", 1), src("src2", "Fit hub", 3)],+ [orphan("orphan1", "Press bearing", 1), orphan("orphan2", "Fit hub", 2)],+ [],[- { id: "src1", title: "Same", sortOrder: 1 },- { id: "src2", title: "Same", sortOrder: 1 }- ],- [{ id: "orphan1", name: "Same", sortOrder: 1 }],- new Set()- );- expect(adoption.size).toBe(1);+ ["orphan1", "src1"],+ ["orphan2", "src2"]+ ]+ ],+ [+ "adopts each orphan at most once",+ [src("src1", "Same", 1), src("src2", "Same", 1)],+ [orphan("orphan1", "Same", 1)],+ [],+ [["orphan1", "src1"]]+ ]+ ])("%s", (_, sources, orphans, claimed, expected) => {+ expect(+ planOrphanStepAdoption(sources, orphans, new Set(claimed as string[]))+ ).toEqual(new Map(expected as [string, string][]));});});-// ── Assembly → BoP sync: tool quantity ratchet ───────────────────────────────describe("maxToolQuantityByItem", () => {it("takes the max quantity any step asks for, defaulting null to 1", () => {- const max = maxToolQuantityByItem([- { itemId: "T1", quantity: 1 },- { itemId: "T1", quantity: 3 },- { itemId: "T2", quantity: null }- ]);- expect(max.get("T1")).toBe(3);- expect(max.get("T2")).toBe(1);+ expect(+ maxToolQuantityByItem([+ { itemId: "T1", quantity: 1 },+ { itemId: "T1", quantity: 3 },+ { itemId: "T2", quantity: null }+ ])+ ).toEqual(+ new Map([+ ["T1", 3],+ ["T2", 1]+ ])+ );});});-// ── Assembly → BoP sync: tool step links (orphan contract) ────────────────────describe("buildAssemblyToolStepLinks", () => {- const sourceSteps = [{ id: "src-1" }, { id: "src-2" }];- const targetIdBySource = new Map([- ["src-1", "job-1"],- ["src-2", "job-2"]- ]);-- it("links each step's tools to its synced target step", () => {- const links = buildAssemblyToolStepLinks(- sourceSteps,- new Map([- ["src-1", [{ itemId: "T1" }]],- ["src-2", [{ itemId: "T2" }]]- ]),+ const link = (toolsByStep: [string, { itemId: string }[]][]) =>+ buildAssemblyToolStepLinks(+ [{ id: "src-1" }, { id: "src-2" }],+ new Map(toolsByStep),new Map([["T1", "row-T1"],["T2", "row-T2"]]),- targetIdBySource- );- expect(links).toEqual([- { jobOperationToolId: "row-T1", jobOperationStepId: "job-1" },- { jobOperationToolId: "row-T2", jobOperationStepId: "job-2" }- ]);- });-- it("produces NO link for a tool dropped from every source step — its jobOperationTool row (never deleted) becomes operation-level, shown on every step", () => {- // T2 still has a jobOperationTool row from a prior sync (in toolRowIdByItemId)- // but no source step references it anymore. The rebuilt links must omit it.- const links = buildAssemblyToolStepLinks(- sourceSteps,- new Map([["src-1", [{ itemId: "T1" }]]]),new Map([- ["T1", "row-T1"],- ["T2", "row-T2"]- ]),- targetIdBySource+ ["src-1", "job-1"],+ ["src-2", "job-2"]+ ]));- expect(links).toEqual([- { jobOperationToolId: "row-T1", jobOperationStepId: "job-1" }- ]);- expect(links.some((l) => l.jobOperationToolId === "row-T2")).toBe(false);- });-});--// ── duplicateJobOperationStep: link-carrying copy ────────────────────────────-// A tiny fake supabase client: canned rows for selects, records inserts. Only-// the chain shapes these functions use are supported (.select/.eq/.single, bare-// await, .insert(...).select("id").single(), bare-await .insert(...)).-function makeFakeClient(opts: {- rows: Record<string, Record<string, unknown>[]>;- newIdByTable?: Record<string, string>;- errorOnInsert?: string;-}) {- const inserts: { table: string; rows: Record<string, unknown>[] }[] = [];-- function resolve(state: {- table: string;- op?: "insert";- filters: Record<string, unknown>;- insertRows?: Record<string, unknown>[];- single: boolean;- }) {- if (state.op === "insert") {- inserts.push({ table: state.table, rows: state.insertRows ?? [] });- if (opts.errorOnInsert === state.table) {- return {- data: null,- error: { message: `insert failed: ${state.table}` }- };- }- if (state.single) {- const id = opts.newIdByTable?.[state.table] ?? `new_${state.table}`;- return { data: { id }, error: null };- }- return { data: null, error: null };- }- let data = opts.rows[state.table] ?? [];- for (const [col, val] of Object.entries(state.filters)) {- data = data.filter((r) => r[col] === val);- }- return state.single- ? { data: data[0] ?? null, error: null }- : { data, error: null };- }-- function builder(table: string) {- const state = {- table,- filters: {} as Record<string, unknown>,- op: undefined as "insert" | undefined,- insertRows: undefined as Record<string, unknown>[] | undefined,- single: false- };- const b = {- select: () => b,- eq: (col: string, val: unknown) => {- state.filters[col] = val;- return b;- },- insert: (rows: Record<string, unknown> | Record<string, unknown>[]) => {- state.op = "insert";- state.insertRows = Array.isArray(rows) ? rows : [rows];- return b;- },- single: () => {- state.single = true;- return Promise.resolve(resolve(state));- },- then: (onF: (v: unknown) => unknown, onR?: (e: unknown) => unknown) =>- Promise.resolve(resolve(state)).then(onF, onR)- };- return b;- }-- return { client: { from: builder } as never, inserts };-}--describe("duplicateJobOperationStep", () => {- function sourceRows() {- return {- jobOperationStep: [- {- id: "step-1",- operationId: "op-1",- name: "Attach bracket",- description: null,- type: "Task",- unitOfMeasureCode: null,- minValue: null,- maxValue: null,- listValues: null,- sortOrder: 1- },- { id: "step-2", operationId: "op-1", sortOrder: 3 }- ],- jobOperationStepSlide: [- {- stepId: "step-1",- imagePath: "/a.png",- modelUploadId: null,- caption: "c",- sortOrder: 1,- size: "medium",- annotations: "[]"- }- ],- jobOperationToolStep: [- { jobOperationToolId: "tool-1", jobOperationStepId: "step-1" }- ],- jobMaterialStep: [- { jobMaterialId: "mat-1", jobOperationStepId: "step-1", quantity: 5 }- ]- };- }-- it("copies the step and carries its slides/tool-links/material-links onto the clone", async () => {- const { client, inserts } = makeFakeClient({- rows: sourceRows(),- newIdByTable: { jobOperationStep: "step-new" }- });-- const result = await duplicateJobOperationStep(client, {- id: "step-1",- companyId: "c1",- createdBy: "u1"- });- expect(result.error).toBeNull();- expect(result.data).toEqual({ id: "step-new" });- const stepInsert = inserts.find((i) => i.table === "jobOperationStep");- expect(stepInsert?.rows[0]).toMatchObject({- operationId: "op-1",- name: "Attach bracket (copy)",- sortOrder: 4, // max sibling sortOrder (3) + 1- companyId: "c1",- createdBy: "u1"- });-- // Every child is repointed at the clone.- expect(- inserts.find((i) => i.table === "jobOperationStepSlide")?.rows[0]- ).toMatchObject({- stepId: "step-new",- imagePath: "/a.png",- companyId: "c1"- });+ it("links each step's tools to its synced target step", () => {expect(- inserts.find((i) => i.table === "jobOperationToolStep")?.rows+ link([+ ["src-1", [{ itemId: "T1" }]],+ ["src-2", [{ itemId: "T2" }]]+ ])).toEqual([- { jobOperationToolId: "tool-1", jobOperationStepId: "step-new" }- ]);- expect(inserts.find((i) => i.table === "jobMaterialStep")?.rows).toEqual([- { jobMaterialId: "mat-1", jobOperationStepId: "step-new", quantity: 5 }+ { jobOperationToolId: "row-T1", jobOperationStepId: "job-1" },+ { jobOperationToolId: "row-T2", jobOperationStepId: "job-2" }]);});- it("aborts and surfaces the error if copying a child link fails (no further inserts)", async () => {- const { client, inserts } = makeFakeClient({- rows: sourceRows(),- newIdByTable: { jobOperationStep: "step-new" },- errorOnInsert: "jobOperationStepSlide"- });-- const result = await duplicateJobOperationStep(client, {- id: "step-1",- companyId: "c1",- createdBy: "u1"- });-- expect(result.data).toBeNull();- expect(result.error).not.toBeNull();- // The slide copy failed, so the tool/material link copies must never run.- expect(inserts.some((i) => i.table === "jobOperationToolStep")).toBe(false);- expect(inserts.some((i) => i.table === "jobMaterialStep")).toBe(false);+ // The kept tool row then shows on every step of the operation.+ it("links nothing for a tool no source step uses any more", () => {+ expect(link([["src-1", [{ itemId: "T1" }]]])).toEqual([+ { jobOperationToolId: "row-T1", jobOperationStepId: "job-1" }+ ]);});});diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex c7a44dc2a0..68cf542183 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -898,9 +898,9 @@ export async function getActiveProductionEvents(client: SupabaseClient<Database>,companyId: string) {- // 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.+ // TS2589 — supabase select-string instantiation depth sits on TypeScript's+ // limit; the cliff shifts as unrelated modules join the program. ts-ignore,+ // not ts-expect-error, since the error comes and goes.// @ts-ignore TS2589return client.from("productionEvent")@@ -11192,6 +11192,66 @@ export type ProductionPlanningDateApplyResult = {refused: { id: string; jobId: string }[];};+/**+ * The due date, deadline type and priority each moved job is written with.+ * A job is ranked among the jobs already on its new date at its location+ * (`siblings`, in priority order); several jobs moved to one date are placed+ * one after the other, each seeing the ones placed before it. An action whose+ * job was not found is left out: it is refused, since no row changes.+ */+export function planJobDateMoves(+ moves: { jobId: string; suggestedDate: string }[],+ jobs: { id: string; locationId: string | null; deadlineType: DeadlineType }[],+ siblings: {+ locationId: string | null;+ dueDate: string | null;+ priority: number | null;+ deadlineType: DeadlineType;+ }[]+): {+ jobId: string;+ dueDate: string;+ deadlineType: DeadlineType;+ priority: number;+}[] {+ const jobById = new Map(jobs.map((job) => [job.id, job]));+ const siblingsByKey = new Map<+ string,+ { priority: number | null; deadlineType: DeadlineType }[]+ >();+ for (const row of siblings) {+ const key = `${row.locationId}\u001f${row.dueDate}`;+ const list = siblingsByKey.get(key) ?? [];+ list.push({ priority: row.priority, deadlineType: row.deadlineType });+ siblingsByKey.set(key, list);+ }++ const values: {+ jobId: string;+ dueDate: string;+ deadlineType: DeadlineType;+ priority: number;+ }[] = [];+ for (const move of moves) {+ const job = jobById.get(move.jobId);+ if (!job) continue;+ const deadlineType = deadlineTypeForPlanningDate(job.deadlineType);+ const key = `${job.locationId}\u001f${move.suggestedDate}`;+ const placed = siblingsByKey.get(key) ?? [];+ const priority = nextJobPriority(placed, deadlineType);+ placed.push({ priority, deadlineType });+ placed.sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));+ siblingsByKey.set(key, placed);+ values.push({+ jobId: move.jobId,+ dueDate: move.suggestedDate,+ deadlineType,+ priority+ });+ }+ return values;+}+/*** Apply a batch of Expedite / Defer actions to their jobs in ONE transaction,* set-based: the claim, two reads (the jobs, and the jobs that share their@@ -11254,7 +11314,6 @@ export async function applyProductionPlanningDateActions(.where("id", "in", jobIds).where("companyId", "=", companyId).execute();- const jobById = new Map(jobs.map((job) => [job.id, job]));// The jobs already on each target date, per location — the siblings a// moved job is ranked among. One read for every date in the batch.@@ -11267,40 +11326,7 @@ export async function applyProductionPlanningDateActions(.where("id", "not in", jobIds).orderBy("priority", "asc").execute();- const siblingsByKey = new Map<- string,- { priority: number | null; deadlineType: DeadlineType }[]- >();- for (const row of siblingRows) {- const key = `${row.locationId}\u001f${row.dueDate}`;- const list = siblingsByKey.get(key) ?? [];- list.push({ priority: row.priority, deadlineType: row.deadlineType });- siblingsByKey.set(key, list);- }-- const values: {- jobId: string;- dueDate: string;- deadlineType: DeadlineType;- priority: number;- }[] = [];- for (const action of held) {- const job = jobById.get(action.jobId);- if (!job) continue; // refused below: no row changed- const deadlineType = deadlineTypeForPlanningDate(job.deadlineType);- const key = `${job.locationId}\u001f${action.suggestedDate}`;- const siblings = siblingsByKey.get(key) ?? [];- const priority = nextJobPriority(siblings, deadlineType);- siblings.push({ priority, deadlineType });- siblings.sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));- siblingsByKey.set(key, siblings);- values.push({- jobId: action.jobId,- dueDate: action.suggestedDate,- deadlineType,- priority- });- }+ const values = planJobDateMoves(held, jobs, siblingRows);const changedJobs = new Set<string>();if (values.length > 0) {diff --git a/apps/erp/app/modules/production/ui/Batches/batch-builder-logic.ts b/apps/erp/app/modules/production/ui/Batches/batch-builder-logic.tsindex c608a739af..b0da74e463 100644--- a/apps/erp/app/modules/production/ui/Batches/batch-builder-logic.ts+++ b/apps/erp/app/modules/production/ui/Batches/batch-builder-logic.ts@@ -3,9 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.// Pure logic behind the batch builder: signatures, per-candidate value sets,-// duration math, and suggestion scoring. No JSX and no lingui, so vitest can-// import it directly (the ERP barrels drag lingui macros vitest cannot-// transform — see apps/erp/test/batching-migration-guards.test.ts).+// duration math, and suggestion scoring. No JSX and no lingui.import {batchPlanBreakdown as aggregateBatchPlan,diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/DateKanban.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/DateKanban.tsxindex 42a673b08d..987810b441 100644--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/DateKanban.tsx+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/DateKanban.tsx@@ -5,11 +5,9 @@import { getLogger } from "@carbon/logger";import { ClientOnly, cn, toast } from "@carbon/react";import type {- Active,DragEndEvent,DragOverEvent,- DragStartEvent,- Over+ DragStartEvent} from "@dnd-kit/core";import {DndContext,@@ -36,21 +34,23 @@ import { path } from "~/utils/path";import { BoardContainer, ColumnCard } from "./components/ColumnCard";import { JobCard } from "./components/JobCard";import { type KanbanMoveTo, KanbanProvider } from "./context/KanbanContext";-import { getDateOnly, getPendingDueDate } from "./date-utils";+import {+ type BoardDragEvent,+ createDateDragOrigin,+ type DateSubmission,+ type DatesDragState,+ datePlacementSubmission,+ mergePendingDateMoves,+ pendingDateMoves,+ reduceDatesDrag+} from "./drag-lifecycle";import {comparePriorityThenId,- createDragOrigin,- type DragOrigin,- type DragPlacement,- type DragPreview,getColumnPlacement,- getItemPlacement,- isSamePlacement,- isSamePreview,resolveInsertionMarker} from "./placement";import type { Column, DisplaySettings, JobItem, Progress } from "./types";-import { hasDraggableData, kanbanCollisionDetection } from "./utils";+import { kanbanCollisionDetection } from "./utils";// Module constants: a new options object makes a new sensor, and with it new// listeners for every draggable on every render.@@ -68,16 +68,7 @@ type DateKanbanProps = {tags: { name: string }[];} & DisplaySettings;-type DateDragOrigin = DragOrigin<JobItem> & {- dueDate: string | null | undefined;-};--type DateDragState = {- origin: DateDragOrigin;- preview: DragPreview | null;-};--const DateDragPreviewContext = createContext<DateDragState | null>(null);+const DateDragPreviewContext = createContext<DatesDragState>(null);type DatePreviewJobCardProps = {item: JobItem;@@ -122,111 +113,11 @@ function DatePreviewJobCard({);}-function isOriginItemDrag(active: Active, origin: DateDragOrigin) {- return (- hasDraggableData(active) &&- active.data.current?.type === "item" &&- String(active.id) === origin.item.id- );-}--function resolveDragPlacement(- origin: DateDragOrigin,- over: Over | null,- items: readonly JobItem[],- itemsById: ReadonlyMap<string, JobItem>,- columnsById: ReadonlyMap<string, Column>-): DragPreview | null {- if (- !over ||- over.disabled ||- !hasDraggableData(over) ||- !itemsById.has(origin.item.id)- ) {- return null;- }-- const overId = String(over.id);- if (overId === origin.item.id) {- return { ...origin.placement, targetType: "item" };- }-- const overData = over.data.current;- if (overData?.type === "item") {- const overItem = itemsById.get(overId);- if (- !overItem ||- overData.item.id !== overId ||- overData.item.columnId !== overItem.columnId ||- !columnsById.has(overItem.columnId)- ) {- return null;- }-- const placement = getItemPlacement(- origin,- items,- overItem.columnId,- overItem.id- );- return placement ? { ...placement, targetType: "item" } : null;- }-- if (overData?.type === "column") {- if (- overData.column.id !== overId ||- !columnsById.has(overId) ||- overId === origin.placement.columnId- ) {- return null;- }-- const placement = getColumnPlacement(origin, items, overId);- return placement ? { ...placement, targetType: "column" } : null;- }-- return null;-}-function usePendingItems(locationId: string) {- type PendingItem = ReturnType<typeof useFetchers>[number] & {- formData: FormData;- };- type PendingProjection = {- id: string;- priority: number;- columnId: string;- dueDate: string | null | undefined;- };- return useFetchers()- .filter((fetcher): fetcher is PendingItem => {- return (- fetcher.formAction === path.to.priorityDatesUpdate &&- fetcher.formData?.get("locationId") === locationId- );- })- .map((fetcher): PendingProjection => {- const persistenceColumnId = fetcher.formData.get("columnId");- const optimisticColumnId = fetcher.formData.get("optimisticColumnId");- const columnId =- typeof optimisticColumnId === "string" && optimisticColumnId.length > 0- ? optimisticColumnId- : typeof persistenceColumnId === "string"- ? persistenceColumnId- : "";- const id = fetcher.formData.get("id");- const priority = Number(fetcher.formData.get("priority"));-- return {- id: typeof id === "string" ? id : "",- priority,- columnId,- dueDate:- typeof persistenceColumnId === "string"- ? getPendingDueDate(persistenceColumnId)- : undefined- };- });+ return pendingDateMoves(useFetchers(), {+ action: path.to.priorityDatesUpdate,+ locationId+ });}// Surface reschedule failures. useFetchers() returns only in-flight fetchers in@@ -285,154 +176,59 @@ const DateKanban = ({// For date-based kanban, always use the column order from props (don't persist)const columnOrder = useMemo(() => columns.map((col) => col.id), [columns]);- const itemsById = new Map<string, JobItem>(- initialItems.map((item) => [item.id, item])- );-const pendingItems = usePendingItems(locationId);useDateUpdateFailureToast();// Merge pending items and existing items for optimistic updates- for (const pendingItem of pendingItems) {- const item = itemsById.get(pendingItem.id);- if (item) {- itemsById.set(pendingItem.id, { ...item, ...pendingItem });- }- }+ const itemsById = mergePendingDateMoves(initialItems, pendingItems);const baseItems = Array.from(itemsById.values()).sort(comparePriorityThenId);const columnsMap = new Map(columns.map((column) => [column.id, column]));- const dragOriginRef = useRef<DateDragOrigin | null>(null);- const [dragState, setDragState] = useState<DateDragState | null>(null);+ // A ref, not state: dnd-kit can fire the next event before a re-render.+ const dragRef = useRef<DatesDragState>(null);+ const [dragState, setDragState] = useState<DatesDragState>(null);const sensors = useSensors(useSensor(PointerSensor),useSensor(KeyboardSensor, KEYBOARD_SENSOR_OPTIONS));- function createDateDragOrigin(activeItem: JobItem): DateDragOrigin | null {- const placementOrigin = createDragOrigin(baseItems, activeItem);- if (!placementOrigin) return null;- return {- ...placementOrigin,- dueDate:- activeItem.dueDate === undefined- ? undefined- : getDateOnly(activeItem.dueDate)- };- }-- function clearDragState() {- dragOriginRef.current = null;- setDragState(null);+ function dispatchDrag(event: BoardDragEvent) {+ const { state, submission } = reduceDatesDrag(dragRef.current, event, {+ items: baseItems,+ itemsById,+ columnsById: columnsMap,+ locationId+ });+ if (submission) submitDate(submission);+ dragRef.current = state;+ setDragState(state);}function onDragStart(event: DragStartEvent) {- if (- !hasDraggableData(event.active) ||- event.active.data.current?.type !== "item"- ) {- clearDragState();- return;- }-- const activeItem = itemsById.get(String(event.active.id));- if (!activeItem || !columnsMap.has(activeItem.columnId)) {- clearDragState();- return;- }-- const origin = createDateDragOrigin(activeItem);- if (!origin) {- clearDragState();- return;- }-- dragOriginRef.current = origin;- setDragState({ origin, preview: null });+ dispatchDrag({ type: "start", active: event.active });}function onDragOver(event: DragOverEvent) {- const origin = dragOriginRef.current;- if (!origin) return;-- if (!isOriginItemDrag(event.active, origin)) {- setDragState((current) =>- current?.origin === origin && isSamePreview(current.preview, null)- ? current- : { origin, preview: null }- );- return;- }-- const placement = resolveDragPlacement(- origin,- event.over,- baseItems,- itemsById,- columnsMap- );- const preview =- placement && !isSamePlacement(origin.placement, placement)- ? placement- : null;-- setDragState((current) =>- current?.origin === origin && isSamePreview(current.preview, preview)- ? current- : { origin, preview }- );+ dispatchDrag({ type: "over", active: event.active, over: event.over });}function onDragEnd(event: DragEndEvent) {- const origin = dragOriginRef.current;- const placement =- origin && isOriginItemDrag(event.active, origin)- ? resolveDragPlacement(- origin,- event.over,- baseItems,- itemsById,- columnsMap- )- : null;-- if (origin && placement) submitPlacement(origin, placement);-- clearDragState();+ dispatchDrag({ type: "end", active: event.active, over: event.over });}function onDragCancel() {- clearDragState();+ dispatchDrag({ type: "cancel" });}- function submitPlacement(origin: DateDragOrigin, placement: DragPlacement) {- if (- origin.dueDate === undefined ||- isSamePlacement(origin.placement, placement)- ) {- return;- }- const isSameDisplayBucket =- placement.columnId === origin.placement.columnId;- submit(- {- id: origin.item.id,- locationId,- columnId: isSameDisplayBucket- ? (origin.dueDate ?? origin.placement.columnId)- : placement.columnId,- optimisticColumnId: placement.columnId,- priority: placement.priority- },- {- method: "post",- action: path.to.priorityDatesUpdate,- navigate: false,- flushSync: true,- fetcherKey: `job:${origin.item.id}`- }- );+ function submitDate(submission: DateSubmission) {+ submit(submission, {+ method: "post",+ action: path.to.priorityDatesUpdate,+ navigate: false,+ flushSync: true,+ fetcherKey: `job:${submission.id}`+ });}// Phones: "Move to" on a card makes the same move as dropping it on that@@ -450,10 +246,15 @@ const DateKanban = ({},onMove: (itemId, columnId) => {const activeItem = itemsById.get(itemId);- const origin = activeItem ? createDateDragOrigin(activeItem) : null;+ const origin = activeItem+ ? createDateDragOrigin(baseItems, activeItem)+ : null;if (!origin) return;const placement = getColumnPlacement(origin, baseItems, columnId);- if (placement) submitPlacement(origin, placement);+ const submission = placement+ ? datePlacementSubmission(origin, placement, locationId)+ : null;+ if (submission) submitDate(submission);}};diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/Kanban.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/Kanban.tsxindex 56bbab6dec..d31dca69ae 100644--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/Kanban.tsx+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/Kanban.tsx@@ -5,12 +5,10 @@import { ClientOnly, cn, toast } from "@carbon/react";import { withUnorderedLast } from "@carbon/utils";import type {- Active,Announcements,DragEndEvent,DragOverEvent,DragStartEvent,- Over,UniqueIdentifier} from "@dnd-kit/core";import {@@ -22,7 +20,7 @@ import {useSensor,useSensors} from "@dnd-kit/core";-import { arrayMove, SortableContext } from "@dnd-kit/sortable";+import { SortableContext } from "@dnd-kit/sortable";import {createContext,useContext,@@ -40,18 +38,18 @@ import { ItemCard } from "./components/ItemCard";import type { KanbanMoveTo } from "./context/KanbanContext";import { KanbanProvider } from "./context/KanbanContext";import {- calculateFractionalPriority,+ type BoardDragEvent,+ type DragCommit,+ type OperationDragOrigin,+ type OperationItemDrag,+ type OperationsDragState,+ planCommitSubmissions,+ reduceOperationsDrag,+ resolveColumnCommit+} from "./drag-lifecycle";+import {comparePriorityThenId,createDragOrigin,- type DragOrigin,- type DragPreview,- getColumnPlacement,- getInsertionIndex,- getItemsInColumn,- getLogicalSlot,- isSamePlacement,- isSamePreview,- planColumnReorder,resolveInsertionMarker} from "./placement";import type { Column, DisplaySettings, Item, Progress } from "./types";@@ -71,14 +69,7 @@ type KanbanProps = {const COLUMN_ORDER_KEY = "kanban-column-order";-type OperationDragOrigin = DragOrigin<Item>;--type KanbanDragState = {- origin: OperationDragOrigin;- preview: DragPreview | null;-};--const KanbanDragPreviewContext = createContext<KanbanDragState | null>(null);+const KanbanDragPreviewContext = createContext<OperationItemDrag | null>(null);// A new options object makes a new sensor, and with it new listeners for// every card on every render of the board.@@ -127,247 +118,6 @@ function PreviewItemCard({);}-function isOriginItemDrag(active: Active, origin: OperationDragOrigin) {- return (- hasDraggableData(active) &&- active.data.current?.type === "item" &&- String(active.id) === origin.item.id- );-}--function resolveDragPlacement(- origin: OperationDragOrigin,- over: Over | null,- items: readonly Item[],- itemsById: ReadonlyMap<string, Item>,- columnsById: ReadonlyMap<string, Column>-): DragPreview | null {- if (- !over ||- over.disabled ||- !hasDraggableData(over) ||- !itemsById.has(origin.item.id)- ) {- return null;- }-- const overId = String(over.id);- if (overId === origin.item.id) {- return { ...origin.placement, targetType: "item" };- }-- const overData = over.data.current;- if (overData?.type === "item") {- const overItem = itemsById.get(overId);- if (- !overItem ||- overData.item.id !== overId ||- overData.item.columnId !== overItem.columnId ||- !columnsById.has(overItem.columnId)- ) {- return null;- }-- const destinationColumn = columnsById.get(overItem.columnId);- if (!destinationColumn?.type.includes(origin.item.columnType)) {- return null;- }-- // Compute the slot directly rather than via getItemPlacement so the- // insertion marker still renders when the two neighbors share a priority- // (no fractional gap) — the drop renumbers the column, so the preview must- // not disappear just because the fast-path priority is unavailable.- const destinationColumnId = overItem.columnId;- const destinationItems = getItemsInColumn(- items,- destinationColumnId,- origin.item.id- );- const sameColumn = origin.placement.columnId === destinationColumnId;- const insertionIndex = getInsertionIndex(- destinationItems,- overItem.id,- sameColumn,- origin.placement.slot.index- );- if (insertionIndex === null) return null;-- const fractionalPriority = calculateFractionalPriority(- destinationItems[insertionIndex - 1]?.priority,- destinationItems[insertionIndex]?.priority- );- // The marker only needs the slot; the priority just has to be stable per- // slot so isSamePreview can dedupe. Fall back to the previous neighbor's- // priority (or the drag-start priority at the top of the column).- const priority =- fractionalPriority ??- destinationItems[insertionIndex - 1]?.priority ??- origin.placement.priority;-- return {- columnId: destinationColumnId,- priority,- slot: getLogicalSlot(destinationItems, insertionIndex),- targetType: "item"- };- }-- if (overData?.type === "column") {- if (- overData.column.id !== overId ||- !columnsById.has(overId) ||- overId === origin.placement.columnId- ) {- return null;- }-- const destinationColumn = columnsById.get(overId);- if (!destinationColumn?.type.includes(origin.item.columnType)) {- return null;- }-- const placement = getColumnPlacement(origin, items, overId);- return placement ? { ...placement, targetType: "column" } : null;- }-- return null;-}--type DragCommit = {- columnId: string;- updates: { id: string; priority: number }[];-};--/**- * Resolves the priority writes a drop should persist. Unlike- * `resolveDragPlacement` (which drives the live insertion marker and gives up- * when the two neighbors have no numeric gap), this never abandons a valid drop- * over a priority collision: it falls back to renumbering the destination column- * so a fully equal-priority column — every op still at the default `1` because- * the scheduler has not sequenced them — can still be reordered. A no-op drop- * (dropped back in place, invalid/incompatible target) returns null.- */-function resolveDragCommit(- origin: OperationDragOrigin,- over: Over | null,- items: readonly Item[],- itemsById: ReadonlyMap<string, Item>,- columnsById: ReadonlyMap<string, Column>-): DragCommit | null {- if (- !over ||- over.disabled ||- !hasDraggableData(over) ||- !itemsById.has(origin.item.id)- ) {- return null;- }-- const overId = String(over.id);- if (overId === origin.item.id) return null;-- const overData = over.data.current;- if (overData?.type === "item") {- const overItem = itemsById.get(overId);- if (- !overItem ||- overData.item.id !== overId ||- overData.item.columnId !== overItem.columnId ||- !columnsById.has(overItem.columnId)- ) {- return null;- }-- const destinationColumn = columnsById.get(overItem.columnId);- if (!destinationColumn?.type.includes(origin.item.columnType)) {- return null;- }-- const destinationColumnId = overItem.columnId;- const destinationItems = getItemsInColumn(- items,- destinationColumnId,- origin.item.id- );- const sameColumn = origin.placement.columnId === destinationColumnId;- const insertionIndex = getInsertionIndex(- destinationItems,- overItem.id,- sameColumn,- origin.placement.slot.index- );- if (insertionIndex === null) return null;-- const slot = getLogicalSlot(destinationItems, insertionIndex);- if (- isSamePlacement(origin.placement, {- columnId: destinationColumnId,- priority: origin.placement.priority,- slot- })- ) {- return null;- }-- const fractionalPriority = calculateFractionalPriority(- destinationItems[insertionIndex - 1]?.priority,- destinationItems[insertionIndex]?.priority- );- const updates =- fractionalPriority === null- ? planColumnReorder(origin, items, destinationColumnId, insertionIndex)- : [{ id: origin.item.id, priority: fractionalPriority }];-- return updates.length ? { columnId: destinationColumnId, updates } : null;- }-- if (overData?.type === "column") {- if (overData.column.id !== overId) return null;- return resolveColumnCommit(origin, items, columnsById, overId);- }-- return null;-}--/**- * The priority writes for dropping a card on a column's background (it lands- * at the column's end). Shared by the drop and by the phone "Move to" menu.- */-function resolveColumnCommit(- origin: OperationDragOrigin,- items: readonly Item[],- columnsById: ReadonlyMap<string, Column>,- columnId: string-): DragCommit | null {- if (!columnsById.has(columnId) || columnId === origin.placement.columnId) {- return null;- }-- const destinationColumn = columnsById.get(columnId);- if (!destinationColumn?.type.includes(origin.item.columnType)) {- return null;- }-- const placement = getColumnPlacement(origin, items, columnId);- if (placement) {- return {- columnId,- updates: [{ id: origin.item.id, priority: placement.priority }]- };- }-- // A background/empty-column drop whose origin priority collides with an- // existing card — renumber, appending the dragged op to the column's end.- const destinationItems = getItemsInColumn(items, columnId, origin.item.id);- const updates = planColumnReorder(- origin,- items,- columnId,- destinationItems.length- );- return updates.length ? { columnId, updates } : null;-}-const Kanban = ({columns,items: initialItems,@@ -466,9 +216,9 @@ const Kanban = ({);const pickedUpItemColumn = useRef<string | null>(null);- const dragOriginRef = useRef<OperationDragOrigin | null>(null);- const dragTypeRef = useRef<"item" | "column" | null>(null);- const [dragState, setDragState] = useState<KanbanDragState | null>(null);+ // A ref, not state: dnd-kit can fire the next event before a re-render.+ const dragRef = useRef<OperationsDragState>(null);+ const [dragState, setDragState] = useState<OperationItemDrag | null>(null);const [activeColumn, setActiveColumn] = useState<Column | null>(null);const [activeItem, setActiveItem] = useState<Item | null>(null);@@ -684,200 +434,60 @@ const Kanban = ({</KanbanProvider>);+ function dispatchDrag(event: BoardDragEvent) {+ const { state, effect } = reduceOperationsDrag(dragRef.current, event, {+ items,+ itemsById,+ columnsById,+ columnOrder+ });+ if (effect?.type === "reorderColumns") setStoredOrder(effect.columnOrder);+ if (effect?.type === "commit") submitCommit(effect.origin, effect.commit);+ dragRef.current = state;+ setDragState(state?.type === "item" ? state : null);+ }+function clearDragState() {pickedUpItemColumn.current = null;- dragOriginRef.current = null;- dragTypeRef.current = null;- setDragState(null);+ dispatchDrag({ type: "cancel" });setActiveItem(null);setActiveColumn(null);}function onDragStart(event: DragStartEvent) {- if (!hasDraggableData(event.active)) {- clearDragState();- return;- }+ clearDragState();+ dispatchDrag({ type: "start", active: event.active });+ const state = dragRef.current;+ if (!state || !hasDraggableData(event.active)) return;const data = event.active.data.current;- if (data?.type === "column") {- clearDragState();- dragTypeRef.current = "column";+ if (state.type === "column" && data?.type === "column") {setActiveColumn(data.column);- return;}-- if (data?.type === "item") {- clearDragState();- const activeItem = itemsById.get(String(event.active.id));- const origin = activeItem ? createDragOrigin(items, activeItem) : null;-- if (!origin) return;-- dragOriginRef.current = origin;- dragTypeRef.current = "item";+ if (state.type === "item" && data?.type === "item") {pickedUpItemColumn.current = data.item.columnId;- setDragState({ origin, preview: null });setActiveItem(data.item);}}function onDragEnd(event: DragEndEvent) {- const origin = dragOriginRef.current;- const { active, over } = event;- const activeData = hasDraggableData(active)- ? active.data.current- : undefined;-- if (- !dragTypeRef.current ||- !hasDraggableData(active) ||- !over ||- !hasDraggableData(over)- ) {- clearDragState();- return;- }-- if (- dragTypeRef.current === "column" &&- activeData?.type === "column" &&- over.data.current?.type === "column"- ) {- const activeId = active.id;- const overId = over.id;- if (activeId !== overId) {- const activeColumnIndex = columnOrder.findIndex(- (id) => id === activeId- );- const overColumnIndex = columnOrder.findIndex((id) => id === overId);-- if (activeColumnIndex >= 0 && overColumnIndex >= 0) {- setStoredOrder(- arrayMove(columnOrder, activeColumnIndex, overColumnIndex)- );- }- }- clearDragState();- return;- }-- if (- dragTypeRef.current === "item" &&- activeData?.type === "item" &&- origin &&- isOriginItemDrag(active, origin)- ) {- // Resolve the actual priority writes. A pure reorder needs a single- // fractional priority; a collision (e.g. an unsequenced column where every- // card still sits at the default priority) renumbers the whole column, so- // several cards move at once.- const commit = resolveDragCommit(- origin,- over,- items,- itemsById,- columnsById- );-- if (commit) submitCommit(origin, commit);- }-+ dispatchDrag({ type: "end", active: event.active, over: event.over });clearDragState();}// Persists a resolved move: each moved card writes through its own endpoint.function submitCommit(origin: OperationDragOrigin, commit: DragCommit) {- if (- isBatchItem(origin.item) &&- commit.columnId !== origin.placement.columnId- ) {- // A batch dropped on a DIFFERENT work center reassigns the whole batch- // (the server fn writes the work center to every member) and reschedules;- // the priority renumber is left to the resulting replan wave.- submit(- {- intent: "update",- batchId: origin.item.batchId,- workCenterId: commit.columnId- },- {- method: "post",- action: path.to.priorityBatchingUpdate,- navigate: false,- flushSync: true,- fetcherKey: `item:${origin.item.id}`- }- );- } else {- // Within-column reorder (or a non-batch cross-column move). Each- // renumbered card writes through its own endpoint: an operation writes- // its priority (+ work center), a batch card writes every member's- // priority so min(member) lands at the batch's new dispatch slot.- const flushSync = commit.updates.length === 1;- const isBatchCard = (id: string) => {- const target = itemsById.get(id);- return !!target && isBatchItem(target);- };- // Several operations renumbered by one drop go in ONE request. One- // request per card meant one page reload per card, and the board- // stuttered for seconds after the drop.- const operationUpdates = commit.updates.filter(- (update) => !isBatchCard(update.id)- );- if (operationUpdates.length > 1) {- submit(- {- columnId: commit.columnId,- updates: JSON.stringify(operationUpdates)- },- {- method: "post",- action: path.to.priorityOperationUpdate,- navigate: false,- // Not the card's own key: a later move of that card would- // replace this fetcher and drop the other cards' pending order.- fetcherKey: `reorder:${commit.columnId}`- }- );- }- for (const update of commit.updates) {- const target = itemsById.get(update.id);- if (operationUpdates.length > 1 && !isBatchCard(update.id)) {- continue;- }- if (target && isBatchItem(target)) {- submit(- {- intent: "reprioritize",- batchId: target.batchId,- priority: update.priority- },- {- method: "post",- action: path.to.priorityBatchingUpdate,- navigate: false,- flushSync,- fetcherKey: `item:${update.id}`- }- );- } else {- submit(- {- id: update.id,- columnId: commit.columnId,- priority: update.priority- },- {- method: "post",- action: path.to.priorityOperationUpdate,- navigate: false,- flushSync,- fetcherKey: `item:${update.id}`- }- );- }- }+ for (const submission of planCommitSubmissions(origin, commit, itemsById)) {+ submit(submission.payload, {+ method: "post",+ action:+ submission.action === "batching"+ ? path.to.priorityBatchingUpdate+ : path.to.priorityOperationUpdate,+ navigate: false,+ flushSync: submission.flushSync,+ fetcherKey: submission.fetcherKey+ });}}@@ -892,26 +502,7 @@ const Kanban = ({}function onDragOver(event: DragOverEvent) {- const origin = dragOriginRef.current;- if (!origin || !isOriginItemDrag(event.active, origin)) return;-- const placement = resolveDragPlacement(- origin,- event.over,- items,- itemsById,- columnsById- );- const preview =- placement && !isSamePlacement(origin.placement, placement)- ? placement- : null;-- setDragState((current) =>- current?.origin === origin && isSamePreview(current.preview, preview)- ? current- : { origin, preview }- );+ dispatchDrag({ type: "over", active: event.active, over: event.over });}function onDragCancel() {diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.ts b/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.tsnew file mode 100644index 0000000000..e490cd9541--- /dev/null+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.ts@@ -0,0 +1,479 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Active, Over } from "@dnd-kit/core";+import { describe, expect, it } from "vitest";+import {+ type BoardDragEvent,+ type DateSubmission,+ type DatesBoard,+ type DatesDragState,+ mergePendingDateMoves,+ type OperationsBoard,+ type OperationsDragEffect,+ type OperationsDragState,+ pendingDateMoves,+ planCommitSubmissions,+ reduceDatesDrag,+ reduceOperationsDrag+} from "./drag-lifecycle";+import { comparePriorityThenId } from "./placement";+import type { Column, DraggableData, Item, JobItem } from "./types";++// dnd-kit's Active/Over also carry rects, which the reducers never read.+function ref(data: DraggableData) {+ const id = data.type === "item" ? data.item.id : data.column.id;+ return { id, data: { current: data }, disabled: false } as unknown as Active &+ Over;+}+const card = (item: Item) => ref({ type: "item", item });+const lane = (column: Column) => ref({ type: "column", column });++const start = (active: Active): BoardDragEvent => ({ type: "start", active });+const over = (active: Active, target: Over | null): BoardDragEvent => ({+ type: "over",+ active,+ over: target+});+const end = (active: Active, target: Over | null): BoardDragEvent => ({+ type: "end",+ active,+ over: target+});+const cancel: BoardDragEvent = { type: "cancel" };++describe("Operations board drag", () => {+ const columns: Column[] = [+ { id: "wc-1", title: "Work Center 1", type: ["Process"] },+ { id: "wc-2", title: "Work Center 2", type: ["Process"] }+ ];+ const op = (id: string, columnId: string, priority: number) =>+ ({ id, columnId, columnType: "Process", priority, title: id }) as Item;+ const a = op("operation-a", "wc-1", 0);+ const b = op("operation-b", "wc-1", 10);+ const c = op("operation-c", "wc-2", 20);+ // A live batch is one card in its work-center column.+ const batch = {+ id: "batch:BAT1",+ columnId: "wc-1",+ columnType: "Process",+ priority: 5,+ title: "Batch BAT0001",+ batchId: "BAT1",+ batchReadableId: "BAT0001",+ batchStatus: "Active",+ members: []+ } as Item;++ function board(+ items: Item[] = [a, b, c],+ boardColumns: Column[] = columns+ ): OperationsBoard {+ const sorted = [...items].sort(comparePriorityThenId);+ return {+ items: sorted,+ itemsById: new Map(sorted.map((item) => [item.id, item])),+ columnsById: new Map(boardColumns.map((column) => [column.id, column])),+ columnOrder: boardColumns.map((column) => column.id)+ };+ }++ function run(events: BoardDragEvent[], ops = board()) {+ let state: OperationsDragState = null;+ const effects: OperationsDragEffect[] = [];+ for (const event of events) {+ const result = reduceOperationsDrag(state, event, ops);+ state = result.state;+ if (result.effect) effects.push(result.effect);+ }+ return effects;+ }++ const moveAToC = {+ type: "commit",+ commit: { columnId: "wc-2", updates: [{ id: "operation-a", priority: 19 }] }+ };++ it("writes once, on the drop, after hovering across other cards and columns", () => {+ expect(+ run([+ start(card(a)),+ over(card(a), card(b)),+ over(card(a), lane(columns[1]!)),+ over(card(a), card(c)),+ end(card(a), card(c))+ ])+ ).toEqual([expect.objectContaining(moveAToC)]);+ });++ it.each([+ ["outside every target", null],+ ["on its own card", card(a)]+ ])("writes nothing for a drop %s", (_where, target) => {+ expect(run([start(card(a)), end(card(a), target)])).toEqual([]);+ });++ it("does not commit the last hover when the drop lands back on the source card", () => {+ expect(+ run([start(card(a)), over(card(a), card(c)), end(card(a), card(a))])+ ).toEqual([]);+ });++ it("ignores a drop after cancel, then commits a fresh drag", () => {+ expect(+ run([+ start(card(a)),+ over(card(a), card(c)),+ cancel,+ end(card(a), card(c)),+ start(card(a)),+ end(card(a), card(c))+ ])+ ).toEqual([expect.objectContaining(moveAToC)]);+ });++ it("writes once when dnd-kit repeats the end callback", () => {+ expect(+ run([start(card(a)), end(card(a), card(c)), end(card(a), card(c))])+ ).toHaveLength(1);+ });++ it("refuses a drop on a work center that does not run the operation's process", () => {+ const assembly = { id: "wc-2", title: "Assembly", type: ["Assembly"] };+ expect(+ run(+ [start(card(a)), end(card(a), lane(assembly))],+ board([a, b, c], [columns[0]!, assembly])+ )+ ).toEqual([]);+ });++ it("reorders columns locally", () => {+ expect(+ run([start(lane(columns[0]!)), end(lane(columns[0]!), lane(columns[1]!))])+ ).toEqual([{ type: "reorderColumns", columnOrder: ["wc-2", "wc-1"] }]);+ });++ it("drops a cancelled column gesture", () => {+ expect(+ run([+ start(lane(columns[0]!)),+ cancel,+ end(lane(columns[0]!), lane(columns[1]!))+ ])+ ).toEqual([]);+ });++ it("writes a single cross-column move through the operation endpoint", () => {+ const ops = board();+ const [effect] = run([start(card(a)), end(card(a), card(c))], ops);+ if (effect?.type !== "commit") throw new Error("expected a commit");+ expect(+ planCommitSubmissions(effect.origin, effect.commit, ops.itemsById)+ ).toEqual([+ {+ action: "operation",+ payload: { id: "operation-a", columnId: "wc-2", priority: 19 },+ fetcherKey: "item:operation-a",+ flushSync: true+ }+ ]);+ });++ it("sends a renumbered column as one request", () => {+ // Unsequenced operations all sit at priority 1, so there is no gap to drop+ // into and the column is renumbered 1..N.+ const x1 = op("x1", "wc-1", 1);+ const x2 = op("x2", "wc-1", 1);+ const x3 = op("x3", "wc-1", 1);+ const ops = board([x1, x2, x3]);+ const [effect] = run([start(card(x1)), end(card(x1), card(x2))], ops);+ if (effect?.type !== "commit") throw new Error("expected a commit");+ expect(+ planCommitSubmissions(effect.origin, effect.commit, ops.itemsById)+ ).toEqual([+ {+ action: "operation",+ payload: {+ columnId: "wc-1",+ updates: JSON.stringify([+ { id: "x1", priority: 2 },+ { id: "x3", priority: 3 }+ ])+ },+ fetcherKey: "reorder:wc-1",+ flushSync: false+ }+ ]);+ });++ it("reassigns a batch's work center when it is dropped on another column", () => {+ const ops = board([a, b, c, batch]);+ const [effect] = run(+ [start(card(batch)), end(card(batch), lane(columns[1]!))],+ ops+ );+ if (effect?.type !== "commit") throw new Error("expected a commit");+ expect(+ planCommitSubmissions(effect.origin, effect.commit, ops.itemsById)+ ).toEqual([+ {+ action: "batching",+ payload: { intent: "update", batchId: "BAT1", workCenterId: "wc-2" },+ fetcherKey: "item:batch:BAT1",+ flushSync: true+ }+ ]);+ });++ it("reprioritizes, not reassigns, a batch dropped within its own column", () => {+ const ops = board([a, b, c, batch]);+ const [effect] = run([start(card(batch)), end(card(batch), card(a))], ops);+ if (effect?.type !== "commit") throw new Error("expected a commit");+ expect(+ planCommitSubmissions(effect.origin, effect.commit, ops.itemsById)+ ).toEqual([+ {+ action: "batching",+ payload: { intent: "reprioritize", batchId: "BAT1", priority: -1 },+ fetcherKey: "item:batch:BAT1",+ flushSync: true+ }+ ]);+ });+});++describe("Dates board drag", () => {+ const ACTION = "/x/priority/dates/update";+ const columns: Column[] = [+ { id: "2026-08-08", title: "Aug 8", type: ["Job"] },+ { id: "2026-08-15", title: "Aug 15", type: ["Job"] },+ { id: "next-week", title: "Next Week", type: ["Job"] }+ ];+ const job = (+ id: string,+ columnId: string,+ priority: number,+ dueDate?: string | null+ ) =>+ ({+ id,+ columnId,+ columnType: "Job",+ priority,+ dueDate,+ title: id+ }) as JobItem;+ // Week columns hold seven dates: job-a sits in Aug 8 but is due Aug 9.+ const jobs = [+ job("job-a", "2026-08-08", 0, "2026-08-09T15:30:00.000Z"),+ job("job-b", "2026-08-08", 10, "2026-08-10T15:30:00.000Z"),+ job("job-c", "2026-08-15", 20, "2026-08-16T15:30:00.000Z")+ ];++ function pendingFetcher(fields: Record<string, string>) {+ const formData = new FormData();+ for (const [key, value] of Object.entries({+ id: "job-a",+ locationId: "location-1",+ priority: "5",+ ...fields+ })) {+ formData.set(key, value);+ }+ return { formAction: ACTION, formData };+ }++ function board(+ items: JobItem[] = jobs,+ fetchers: { formAction?: string; formData?: FormData }[] = []+ ): DatesBoard {+ const itemsById = mergePendingDateMoves(+ items,+ pendingDateMoves(fetchers, { action: ACTION, locationId: "location-1" })+ );+ return {+ items: [...itemsById.values()].sort(comparePriorityThenId),+ itemsById,+ columnsById: new Map(columns.map((column) => [column.id, column])),+ locationId: "location-1"+ };+ }++ // Drag `id` onto `targetId`, hovering `hovers` first, as the board renders them.+ function drop(+ dates: DatesBoard,+ id: string,+ targetId: string | null,+ hovers: string[] = []+ ) {+ const at = (cardId: string) => card(dates.itemsById.get(cardId)!);+ const events = [+ start(at(id)),+ ...hovers.map((hover) => over(at(id), at(hover))),+ end(at(id), targetId === null ? null : at(targetId))+ ];+ return run(events, dates);+ }++ function run(events: BoardDragEvent[], dates: DatesBoard) {+ let state: DatesDragState = null;+ const submissions: DateSubmission[] = [];+ for (const event of events) {+ const result = reduceDatesDrag(state, event, dates);+ state = result.state;+ if (result.submission) submissions.push(result.submission);+ }+ return submissions;+ }++ it("writes once on the drop and keeps the job's exact date within its week", () => {+ expect(+ drop(board(), "job-a", "job-b", ["job-c", "job-b", "job-c"])+ ).toEqual([+ {+ id: "job-a",+ locationId: "location-1",+ columnId: "2026-08-09",+ optimisticColumnId: "2026-08-08",+ priority: 11+ }+ ]);+ });++ it("takes the destination week's date when moved to another week", () => {+ expect(drop(board(), "job-a", "job-c")).toEqual([+ {+ id: "job-a",+ locationId: "location-1",+ columnId: "2026-08-15",+ optimisticColumnId: "2026-08-15",+ priority: 19+ }+ ]);+ });++ it.each([+ ["outside every target", null],+ ["on its own card", "job-a"]+ ])("writes nothing for a drop %s", (_where, target) => {+ expect(drop(board(), "job-a", target)).toEqual([]);+ });++ it("does not commit the last hover when the drop lands back on the source card", () => {+ expect(drop(board(), "job-a", "job-a", ["job-b"])).toEqual([]);+ });++ it("ignores a drop after cancel, then commits a fresh drag", () => {+ const dates = board();+ const a = card(dates.itemsById.get("job-a")!);+ const b = card(dates.itemsById.get("job-b")!);+ expect(+ run([start(a), over(a, b), cancel, end(a, b), start(a), end(a, b)], dates)+ ).toHaveLength(1);+ });++ it("writes once when dnd-kit repeats the end callback", () => {+ const dates = board();+ const a = card(dates.itemsById.get("job-a")!);+ const b = card(dates.itemsById.get("job-b")!);+ expect(run([start(a), end(a, b), end(a, b)], dates)).toHaveLength(1);+ });++ it("reorders a job with a move still in flight using the date that move persists", () => {+ // job-a was moved from Aug 15 to Aug 9 (shown under Aug 8); the loader+ // still has the old row.+ const dates = board(+ [+ job("job-a", "2026-08-15", 0, "2026-08-16T15:30:00.000Z"),+ job("target", "2026-08-08", 20, "2026-08-16T15:30:00.000Z")+ ],+ [+ pendingFetcher({+ columnId: "2026-08-09",+ optimisticColumnId: "2026-08-08"+ })+ ]+ );+ expect(drop(dates, "job-a", "target", ["target"])).toEqual([+ {+ id: "job-a",+ locationId: "location-1",+ columnId: "2026-08-09",+ optimisticColumnId: "2026-08-08",+ priority: 21+ }+ ]);+ });++ it("keeps an in-flight move to a no-date column as that column", () => {+ const dates = board(+ [jobs[0]!, job("target", "next-week", 20, undefined)],+ [+ pendingFetcher({+ columnId: "next-week",+ optimisticColumnId: "next-week"+ })+ ]+ );+ expect(drop(dates, "job-a", "target", ["target"])).toEqual([+ {+ id: "job-a",+ locationId: "location-1",+ columnId: "next-week",+ optimisticColumnId: "next-week",+ priority: 21+ }+ ]);+ });++ it.each([+ ["missing", {}],+ ["not a real date", { columnId: "2026-02-29" }]+ ])(+ "writes nothing while the in-flight date is %s",+ (_kind, persisted: Record<string, string>) => {+ const dates = board(+ [+ job("job-a", "2026-08-15", 0, "2026-08-16T15:30:00.000Z"),+ job("target", "2026-08-08", 20, "2026-08-16T15:30:00.000Z")+ ],+ [pendingFetcher({ optimisticColumnId: "2026-08-08", ...persisted })]+ );+ expect(dates.itemsById.get("job-a")?.dueDate).toBeUndefined();+ expect(drop(dates, "job-a", "target", ["target"])).toEqual([]);+ }+ );++ it.each([+ ["another location", pendingFetcher({ locationId: "location-2" })],+ ["another action", { ...pendingFetcher({}), formAction: "/x/other" }],+ ["no form data", { formAction: ACTION, formData: undefined }]+ ])("ignores an in-flight fetcher for %s", (_kind, fetcher) => {+ expect(+ pendingDateMoves([fetcher], { action: ACTION, locationId: "location-1" })+ ).toEqual([]);+ });++ it("reads an in-flight move as its optimistic column and persisted date", () => {+ expect(+ pendingDateMoves(+ [+ pendingFetcher({+ columnId: "2026-08-09",+ optimisticColumnId: "2026-08-08"+ })+ ],+ { action: ACTION, locationId: "location-1" }+ )+ ).toEqual([+ {+ id: "job-a",+ priority: 5,+ columnId: "2026-08-08",+ dueDate: "2026-08-09"+ }+ ]);+ });+});diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.tsxdeleted file mode 100644index 12fa0d252b..0000000000--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.tsx+++ /dev/null@@ -1,818 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import type { ReactElement } from "react";-import { createElement } from "react";-import { renderToStaticMarkup } from "react-dom/server";-import { beforeEach, describe, expect, it, vi } from "vitest";-import { DateKanban } from "./DateKanban";-import Kanban from "./Kanban";-import type { Column, Item, JobItem } from "./types";--const submit = vi.hoisted(() => vi.fn());-const arrayMove = vi.hoisted(() =>- vi.fn((items: string[], from: number, to: number) => {- const next = [...items];- const [moved] = next.splice(from, 1);- next.splice(to, 0, moved);- return next;- })-);-const capturedDndProps = vi.hoisted(() => ({- current: null as DndProps | null-}));--type DragItem = Item & {- columnType: string;-};--type DragActive = {- id: string;- data: {- current: { type: "item" | "column"; item?: DragItem; column?: Column };- };-};--type DragOver = DragActive & {- disabled: boolean;-};--type DndProps = {- onDragStart: (event: { active: DragActive }) => void;- onDragOver: (event: { active: DragActive; over: DragOver | null }) => void;- onDragEnd: (event: { active: DragActive; over: DragOver | null }) => void;- onDragCancel: () => void;-};--type TestFetcher = {- formAction: string;- formData: FormData | undefined;- key: string;- state: "loading" | "submitting";- data?: unknown;-};--const fetchers = vi.hoisted(() => ({ current: [] as TestFetcher[] }));--vi.mock("@carbon/content/glossary", () => ({- terms: {},- getEntry: vi.fn(),- lookupEntry: vi.fn(),- hasEntry: vi.fn(),- termSlug: vi.fn(),- glossaryEntries: () => []-}));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn(), info: vi.fn(), warn: vi.fn() })-}));-vi.mock("@carbon/react", () => ({- ClientOnly: () => null,- cn: (...classes: unknown[]) => classes.filter(Boolean).join(" "),- toast: { error: vi.fn() },- // The board's provider reads the dates route's timezone once for its cards.- useRouteData: () => undefined-}));-vi.mock("@lingui/react/macro", () => ({- useLingui: () => ({ t: () => "translated" })-}));-vi.mock("@dnd-kit/core", async () => {- const actual =- await vi.importActual<typeof import("@dnd-kit/core")>("@dnd-kit/core");- return {- ...actual,- DndContext: (props: DndProps) => {- capturedDndProps.current = props;- return null;- },- KeyboardSensor: {},- MouseSensor: {},- PointerSensor: {},- TouchSensor: {},- useSensor: vi.fn((sensor) => sensor),- useSensors: vi.fn((...sensors) => sensors)- };-});-vi.mock("@dnd-kit/sortable", async () => {- const actual =- await vi.importActual<typeof import("@dnd-kit/sortable")>(- "@dnd-kit/sortable"- );- return {- ...actual,- SortableContext: () => null,- arrayMove,- sortableKeyboardCoordinates: vi.fn()- };-});-vi.mock("react-router", () => ({- useFetchers: () => fetchers.current,- useSubmit: () => submit-}));-// The boards moved from x/schedule to x/priority in 7f5f1d2145 (#1151), which-// renamed these helpers scheduleDatesUpdate -> priorityDatesUpdate and-// scheduleOperationUpdate -> priorityOperationUpdate. The mock must carry the-// current keys: an unknown key resolves to `undefined`, which both blanks the-// submit action AND makes the pending-fetcher filters-// (`fetcher.formAction === path.to.priorityDatesUpdate`) match nothing, so the-// optimistic merge silently stops happening.-vi.mock("~/utils/path", () => ({- path: {- to: {- priorityBatchingUpdate: "/x/priority/batching/update",- priorityDatesUpdate: "/x/priority/dates/update",- priorityOperationUpdate: "/x/priority/operations/update"- }- }-}));-vi.mock("./components/ColumnCard", () => ({- BoardContainer: () => null,- ColumnCard: () => null-}));-vi.mock("./components/ItemCard", () => ({- ItemCard: () => null-}));-vi.mock("./components/BatchItemCard", () => ({- BatchItemCard: () => null-}));-vi.mock("./components/JobCard", () => ({- JobCard: () => null-}));--const settings = {- showCustomer: false,- showDescription: false,- showDueDate: false,- showDuration: false,- showEmployee: false,- showProgress: false,- showQuantity: false,- showStatus: false,- showSalesOrder: false,- showThumbnail: false-};--const operationColumns: Column[] = [- { id: "wc-1", title: "Work Center 1", type: ["Process"] },- { id: "wc-2", title: "Work Center 2", type: ["Process"] }-];--const operationItems = [- {- id: "operation-a",- columnId: "wc-1",- columnType: "Process",- priority: 0,- title: "Operation A"- },- {- id: "operation-b",- columnId: "wc-1",- columnType: "Process",- priority: 10,- title: "Operation B"- },- {- id: "operation-c",- columnId: "wc-2",- columnType: "Process",- priority: 20,- title: "Operation C"- }-] as DragItem[];--// A live batch collapses to one draggable card in its work-center column.-// Dragging it to another column reassigns the whole batch's work center-// (intent "update" → priorityBatchingUpdate), while a within-column drop is a-// no-op (member priorities own the card's position).-const batchItem = {- id: "batch:BAT1",- columnId: "wc-1",- columnType: "Process",- priority: 5,- title: "Batch BAT0001",- batchId: "BAT1",- batchReadableId: "BAT0001",- batchStatus: "Active",- members: []-} as DragItem;--const dateColumns: Column[] = [- { id: "2026-08-08", title: "Aug 8", type: ["Job"] },- { id: "2026-08-15", title: "Aug 15", type: ["Job"] }-];--const dateItems = [- {- id: "job-a",- columnId: "2026-08-08",- columnType: "Job",- priority: 0,- dueDate: "2026-08-09T15:30:00.000Z",- title: "Job A"- },- {- id: "job-b",- columnId: "2026-08-08",- columnType: "Job",- priority: 10,- dueDate: "2026-08-10T15:30:00.000Z",- title: "Job B"- },- {- id: "job-c",- columnId: "2026-08-15",- columnType: "Job",- priority: 20,- dueDate: "2026-08-16T15:30:00.000Z",- title: "Job C"- }-] as JobItem[];--function itemActive(item: DragItem): DragActive {- return {- id: item.id,- data: { current: { type: "item" as const, item } }- };-}--function itemOver(item: DragItem): DragOver {- return { ...itemActive(item), disabled: false };-}--function columnActive(column: Column): DragActive {- return {- id: column.id,- data: { current: { type: "column" as const, column } }- };-}--function columnOver(column: Column): DragOver {- return { ...columnActive(column), disabled: false };-}--function captureBoard(- Board: (props: any) => ReactElement,- props: Record<string, unknown>-): DndProps {- capturedDndProps.current = null;- renderToStaticMarkup(createElement(Board, props));- if (!capturedDndProps.current) {- throw new Error("DndContext was not rendered");- }- return capturedDndProps.current;-}--function captureOperationsBoard(- items: DragItem[] = operationItems,- columns: Column[] = operationColumns-) {- return captureBoard(Kanban, {- ...settings,- columns,- items,- progressByItemId: {},- tags: []- });-}--function captureDatesBoard(- items: JobItem[] = dateItems,- columns: Column[] = dateColumns-) {- return captureBoard(DateKanban, {- ...settings,- columns,- items,- locationId: "location-1",- progressByItemId: {},- tags: []- });-}--function pendingDateFetcher({- id = "job-a",- locationId = "location-1",- priority = "5",- columnId,- optimisticColumnId = columnId-}: {- id?: string;- locationId?: string;- priority?: string;- columnId?: string;- optimisticColumnId?: string;-}): TestFetcher {- const formData = new FormData();- formData.set("id", id);- formData.set("locationId", locationId);- formData.set("priority", priority);- if (columnId !== undefined) {- formData.set("columnId", columnId);- }- if (optimisticColumnId !== undefined) {- formData.set("optimisticColumnId", optimisticColumnId);- }- return {- formAction: "/x/priority/dates/update",- formData,- key: `job:${id}`,- state: "loading"- };-}--function startItemDrag(board: DndProps, item: DragItem) {- board.onDragStart({ active: itemActive(item) });-}--beforeEach(() => {- submit.mockClear();- arrayMove.mockClear();- fetchers.current = [];- capturedDndProps.current = null;- Object.defineProperty(globalThis, "localStorage", {- configurable: true,- value: {- getItem: () => null,- setItem: vi.fn()- }- });-});--describe("Dates board drag lifecycle", () => {- it("submits once on the final changed drop, never during circuitous hover, and preserves the exact date", () => {- const board = captureDatesBoard();- const active = dateItems[0];-- startItemDrag(board, active);- board.onDragOver({- active: itemActive(active),- over: itemOver(dateItems[2])- });- board.onDragOver({- active: itemActive(active),- over: columnOver(dateColumns[1])- });- board.onDragOver({- active: itemActive(active),- over: itemOver(dateItems[1])- });-- expect(submit).not.toHaveBeenCalled();-- board.onDragEnd({- active: itemActive(active),- over: itemOver(dateItems[1])- });-- expect(submit).toHaveBeenCalledTimes(1);- expect(submit).toHaveBeenCalledWith(- {- id: "job-a",- locationId: "location-1",- columnId: "2026-08-09",- optimisticColumnId: "2026-08-08",- priority: 11- },- expect.objectContaining({ action: "/x/priority/dates/update" })- );- });-- it("uses the pending exact persisted date for a chained same-bucket reorder", () => {- const active = {- ...dateItems[0],- columnId: "2026-08-15",- dueDate: "2026-08-16T15:30:00.000Z"- };- const target = {- ...dateItems[2],- id: "job-exact-target",- columnId: "2026-08-08"- };- fetchers.current = [- pendingDateFetcher({- columnId: "2026-08-09",- optimisticColumnId: "2026-08-08"- })- ];- const board = captureDatesBoard([active, target]);-- startItemDrag(board, active);- board.onDragOver({ active: itemActive(active), over: itemOver(target) });- expect(submit).not.toHaveBeenCalled();-- board.onDragEnd({ active: itemActive(active), over: itemOver(target) });-- expect(submit).toHaveBeenCalledWith(- {- id: "job-a",- locationId: "location-1",- columnId: "2026-08-09",- optimisticColumnId: "2026-08-08",- priority: 21- },- expect.objectContaining({ action: "/x/priority/dates/update" })- );- expect(submit).not.toHaveBeenCalledWith(- expect.objectContaining({ columnId: "2026-08-16" }),- expect.anything()- );- });-- it("ignores pending date data from another location", () => {- fetchers.current = [- pendingDateFetcher({- locationId: "location-2",- columnId: "2026-08-16",- optimisticColumnId: "2026-08-15"- })- ];- const board = captureDatesBoard();- const active = dateItems[0];-- startItemDrag(board, active);- board.onDragEnd({- active: itemActive(active),- over: itemOver(dateItems[2])- });-- expect(submit).toHaveBeenCalledWith(- expect.objectContaining({- locationId: "location-1",- columnId: "2026-08-15"- }),- expect.objectContaining({ action: "/x/priority/dates/update" })- );- expect(submit).not.toHaveBeenCalledWith(- expect.objectContaining({ columnId: "2026-08-16" }),- expect.anything()- );- });-- it("ignores a Dates fetcher without form data and preserves the next drag origin", () => {- fetchers.current = [- {- formAction: "/x/priority/dates/update",- formData: undefined,- key: "job:job-a",- state: "loading"- }- ];- const board = captureDatesBoard();- const active = dateItems[0];-- startItemDrag(board, active);- board.onDragEnd({- active: itemActive(active),- over: itemOver(dateItems[1])- });-- expect(submit).toHaveBeenCalledTimes(1);- expect(submit).toHaveBeenCalledWith(- {- id: "job-a",- locationId: "location-1",- columnId: "2026-08-09",- optimisticColumnId: "2026-08-08",- priority: 11- },- expect.objectContaining({ action: "/x/priority/dates/update" })- );- });-- it.each([- ["missing", undefined],- ["invalid", "2026-02-29"]- ] as const)(- "does not submit an unknown pending persisted date (%s)",- (_kind, columnId) => {- const active = {- ...dateItems[0],- columnId: "2026-08-15",- dueDate: "2026-08-16T15:30:00.000Z"- };- const target = {- ...dateItems[2],- id: "job-exact-target",- columnId: "2026-08-08"- };- fetchers.current = [- pendingDateFetcher({- columnId,- optimisticColumnId: "2026-08-08"- })- ];- const board = captureDatesBoard([active, target]);-- startItemDrag(board, active);- board.onDragOver({ active: itemActive(active), over: itemOver(target) });- expect(submit).not.toHaveBeenCalled();-- board.onDragEnd({ active: itemActive(active), over: itemOver(target) });-- expect(submit).toHaveBeenCalledTimes(0);- expect(submit).not.toHaveBeenCalledWith(- expect.objectContaining({ columnId: "2026-08-16" }),- expect.anything()- );- for (const unsafeColumnId of [- "2026-08-08",- "unscheduled",- "next-week",- "next-month"- ]) {- expect(submit).not.toHaveBeenCalledWith(- expect.objectContaining({ columnId: unsafeColumnId }),- expect.anything()- );- }- }- );-- it("uses null for a pending sentinel during a chained same-bucket reorder", () => {- const sentinelTarget = {- ...dateItems[2],- id: "job-null-target",- columnId: "next-week",- dueDate: undefined- } as JobItem;- const columns = [- ...dateColumns,- { id: "next-week", title: "Next Week", type: ["Job"] }- ];- fetchers.current = [- pendingDateFetcher({- columnId: "next-week",- optimisticColumnId: "next-week"- })- ];- const board = captureDatesBoard([dateItems[0], sentinelTarget], columns);- const active = dateItems[0];-- startItemDrag(board, active);- board.onDragOver({- active: itemActive(active),- over: itemOver(sentinelTarget)- });- expect(submit).not.toHaveBeenCalled();-- board.onDragEnd({- active: itemActive(active),- over: itemOver(sentinelTarget)- });-- expect(submit).toHaveBeenCalledWith(- {- id: "job-a",- locationId: "location-1",- columnId: "next-week",- optimisticColumnId: "next-week",- priority: 21- },- expect.objectContaining({ action: "/x/priority/dates/update" })- );- expect(submit).not.toHaveBeenCalledWith(- expect.objectContaining({ columnId: "2026-08-09" }),- expect.anything()- );- });-- it.each([- ["outside", null],- ["self-target", itemOver(dateItems[0])]- ])("submits zero times for a %s drag end", (_name, over) => {- const board = captureDatesBoard();- const active = dateItems[0];-- startItemDrag(board, active);- board.onDragEnd({ active: itemActive(active), over });-- expect(submit).not.toHaveBeenCalled();- });-- it("does not commit a cached hover when ending back on the source card", () => {- const board = captureDatesBoard();- const active = dateItems[0];-- startItemDrag(board, active);- board.onDragOver({- active: itemActive(active),- over: itemOver(dateItems[1])- });- board.onDragEnd({ active: itemActive(active), over: itemOver(active) });-- expect(submit).not.toHaveBeenCalled();- });-- it("clears cancellation, permits a fresh drag, and submits only once", () => {- const board = captureDatesBoard();- const active = dateItems[0];-- startItemDrag(board, active);- board.onDragOver({- active: itemActive(active),- over: itemOver(dateItems[1])- });- board.onDragCancel();- board.onDragEnd({- active: itemActive(active),- over: itemOver(dateItems[1])- });- expect(submit).not.toHaveBeenCalled();-- startItemDrag(board, active);- board.onDragEnd({- active: itemActive(active),- over: itemOver(dateItems[1])- });- expect(submit).toHaveBeenCalledTimes(1);- });-- it("does not submit when an end callback repeats after success", () => {- const board = captureDatesBoard();- const active = dateItems[0];- const over = itemOver(dateItems[1]);-- startItemDrag(board, active);- board.onDragEnd({ active: itemActive(active), over });- board.onDragEnd({ active: itemActive(active), over });-- expect(submit).toHaveBeenCalledTimes(1);- });-});--describe("Operations board drag lifecycle", () => {- it("submits once on the final changed drop and never during circuitous hover", () => {- const board = captureOperationsBoard();- const active = operationItems[0];-- startItemDrag(board, active);- board.onDragOver({- active: itemActive(active),- over: itemOver(operationItems[1])- });- board.onDragOver({- active: itemActive(active),- over: columnOver(operationColumns[1])- });- board.onDragOver({- active: itemActive(active),- over: itemOver(operationItems[2])- });-- expect(submit).not.toHaveBeenCalled();-- board.onDragEnd({- active: itemActive(active),- over: itemOver(operationItems[2])- });-- expect(submit).toHaveBeenCalledTimes(1);- expect(submit).toHaveBeenCalledWith(- { id: "operation-a", columnId: "wc-2", priority: 19 },- expect.objectContaining({ action: "/x/priority/operations/update" })- );- });-- it.each([- ["outside", null],- ["self-target", itemOver(operationItems[0])]- ])("submits zero times for a %s drag end", (_name, over) => {- const board = captureOperationsBoard();- const active = operationItems[0];-- startItemDrag(board, active);- board.onDragEnd({ active: itemActive(active), over });-- expect(submit).not.toHaveBeenCalled();- });-- it("does not commit a cached hover when ending back on the source card", () => {- const board = captureOperationsBoard();- const active = operationItems[0];-- startItemDrag(board, active);- board.onDragOver({- active: itemActive(active),- over: itemOver(operationItems[2])- });- board.onDragEnd({ active: itemActive(active), over: itemOver(active) });-- expect(submit).not.toHaveBeenCalled();- });-- it("clears item cancellation, permits a fresh drag, and submits only once", () => {- const board = captureOperationsBoard();- const active = operationItems[0];- const over = itemOver(operationItems[2]);-- startItemDrag(board, active);- board.onDragOver({ active: itemActive(active), over });- board.onDragCancel();- board.onDragEnd({ active: itemActive(active), over });- expect(submit).not.toHaveBeenCalled();-- startItemDrag(board, active);- board.onDragEnd({ active: itemActive(active), over });- expect(submit).toHaveBeenCalledTimes(1);- });-- it("does not submit when an end callback repeats after success", () => {- const board = captureOperationsBoard();- const active = operationItems[0];- const over = itemOver(operationItems[2]);-- startItemDrag(board, active);- board.onDragEnd({ active: itemActive(active), over });- board.onDragEnd({ active: itemActive(active), over });-- expect(submit).toHaveBeenCalledTimes(1);- });-- it("rejects an incompatible process/work-centre drop without submitting", () => {- const incompatibleColumn = {- id: "wc-2",- title: "Assembly Center",- type: ["Assembly"]- };- const board = captureOperationsBoard(operationItems, [- operationColumns[0],- incompatibleColumn- ]);- const active = operationItems[0];-- startItemDrag(board, active);- board.onDragEnd({- active: itemActive(active),- over: columnOver(incompatibleColumn)- });-- expect(submit).not.toHaveBeenCalled();- });-- it("reorders columns locally without submitting an item update", () => {- const board = captureOperationsBoard();-- board.onDragStart({ active: columnActive(operationColumns[0]) });- board.onDragEnd({- active: columnActive(operationColumns[0]),- over: columnOver(operationColumns[1])- });-- expect(arrayMove).toHaveBeenCalledWith(["wc-1", "wc-2"], 0, 1);- expect(submit).not.toHaveBeenCalled();- });-- it("clears a cancelled column gesture without reordering or submitting", () => {- const board = captureOperationsBoard();-- board.onDragStart({ active: columnActive(operationColumns[0]) });- board.onDragCancel();- board.onDragEnd({- active: columnActive(operationColumns[0]),- over: columnOver(operationColumns[1])- });-- expect(arrayMove).not.toHaveBeenCalled();- expect(submit).not.toHaveBeenCalled();- });-- it("reassigns a batch's work center when dropped on another column", () => {- const board = captureOperationsBoard([...operationItems, batchItem]);-- startItemDrag(board, batchItem);- board.onDragEnd({- active: itemActive(batchItem),- over: columnOver(operationColumns[1])- });-- expect(submit).toHaveBeenCalledTimes(1);- expect(submit).toHaveBeenCalledWith(- { intent: "update", batchId: "BAT1", workCenterId: "wc-2" },- expect.objectContaining({ action: "/x/priority/batching/update" })- );- });-- it("does not reassign a batch dropped within its own column", () => {- const board = captureOperationsBoard([...operationItems, batchItem]);-- startItemDrag(board, batchItem);- board.onDragEnd({- active: itemActive(batchItem),- over: itemOver(operationItems[0])- });-- // A within-column drop is a REORDER, so it legitimately writes the batch's- // new priority through the batching endpoint. What it must never do is- // reassign the work center — that is the `intent: "update"` payload the- // cross-column case sends. Asserting `submit` was never called at all would- // contradict the reorder the drop actually performed.- expect(submit).not.toHaveBeenCalledWith(- expect.objectContaining({ intent: "update" }),- expect.anything()- );- for (const [payload] of submit.mock.calls) {- expect(payload).not.toHaveProperty("workCenterId");- }- });-});diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.ts b/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.tsnew file mode 100644index 0000000000..947430ef5e--- /dev/null+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.ts@@ -0,0 +1,733 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// The drag state machines behind the Operations and Dates boards. A board+// keeps the state in a ref (dnd-kit can fire the next event before React+// re-renders) and applies the effect a reducer returns.++import type { Active, Over } from "@dnd-kit/core";+import { arrayMove } from "@dnd-kit/sortable";+import { getDateOnly, getPendingDueDate } from "./date-utils";+import {+ calculateFractionalPriority,+ createDragOrigin,+ type DragOrigin,+ type DragPlacement,+ type DragPreview,+ getColumnPlacement,+ getInsertionIndex,+ getItemPlacement,+ getItemsInColumn,+ getLogicalSlot,+ isSamePlacement,+ isSamePreview,+ planColumnReorder+} from "./placement";+import type { Column, Item, JobItem } from "./types";+import { isBatchItem } from "./types";+import { hasDraggableData } from "./utils";++export type BoardDragEvent =+ | { type: "start"; active: Active }+ | { type: "over"; active: Active; over: Over | null }+ | { type: "end"; active: Active; over: Over | null }+ | { type: "cancel" };++function isOriginItemDrag(active: Active, origin: DragOrigin<Item>) {+ return (+ hasDraggableData(active) &&+ active.data.current?.type === "item" &&+ String(active.id) === origin.item.id+ );+}++// ---------------------------------------------------------------------------+// Operations board+// ---------------------------------------------------------------------------++export type OperationDragOrigin = DragOrigin<Item>;++export type OperationItemDrag = {+ type: "item";+ origin: OperationDragOrigin;+ preview: DragPreview | null;+};++export type OperationsDragState = OperationItemDrag | { type: "column" } | null;++export type OperationsBoard = {+ items: readonly Item[];+ itemsById: ReadonlyMap<string, Item>;+ columnsById: ReadonlyMap<string, Column>;+ columnOrder: string[];+};++export type DragCommit = {+ columnId: string;+ updates: { id: string; priority: number }[];+};++export type OperationsDragEffect =+ | { type: "reorderColumns"; columnOrder: string[] }+ | { type: "commit"; origin: OperationDragOrigin; commit: DragCommit };++/**+ * Hover only moves the preview; only the end event writes, and it resolves the+ * drop from its own `over`, never from the last hover. Every end and cancel+ * leaves no live drag, so a repeated end callback writes nothing.+ */+export function reduceOperationsDrag(+ state: OperationsDragState,+ event: BoardDragEvent,+ board: OperationsBoard+): { state: OperationsDragState; effect: OperationsDragEffect | null } {+ switch (event.type) {+ case "start": {+ if (!hasDraggableData(event.active)) return { state: null, effect: null };+ const data = event.active.data.current;+ if (data?.type === "column") {+ return { state: { type: "column" }, effect: null };+ }+ const activeItem = board.itemsById.get(String(event.active.id));+ const origin = activeItem+ ? createDragOrigin(board.items, activeItem)+ : null;+ return {+ state: origin ? { type: "item", origin, preview: null } : null,+ effect: null+ };+ }+ case "over": {+ if (+ state?.type !== "item" ||+ !isOriginItemDrag(event.active, state.origin)+ ) {+ return { state, effect: null };+ }+ const placement = resolveOperationPlacement(+ state.origin,+ event.over,+ board+ );+ const preview =+ placement && !isSamePlacement(state.origin.placement, placement)+ ? placement+ : null;+ return {+ state: isSamePreview(state.preview, preview)+ ? state+ : { ...state, preview },+ effect: null+ };+ }+ case "end": {+ const { active, over } = event;+ if (+ !state ||+ !hasDraggableData(active) ||+ !over ||+ !hasDraggableData(over)+ ) {+ return { state: null, effect: null };+ }+ const activeData = active.data.current;+ if (+ state.type === "column" &&+ activeData?.type === "column" &&+ over.data.current?.type === "column"+ ) {+ const from = board.columnOrder.findIndex((id) => id === active.id);+ const to = board.columnOrder.findIndex((id) => id === over.id);+ return {+ state: null,+ effect:+ active.id !== over.id && from >= 0 && to >= 0+ ? {+ type: "reorderColumns",+ columnOrder: arrayMove(board.columnOrder, from, to)+ }+ : null+ };+ }+ if (+ state.type === "item" &&+ activeData?.type === "item" &&+ isOriginItemDrag(active, state.origin)+ ) {+ const commit = resolveOperationCommit(state.origin, over, board);+ if (commit) {+ return {+ state: null,+ effect: { type: "commit", origin: state.origin, commit }+ };+ }+ }+ return { state: null, effect: null };+ }+ case "cancel":+ return { state: null, effect: null };+ }+}++function resolveOperationPlacement(+ origin: OperationDragOrigin,+ over: Over | null,+ { items, itemsById, columnsById }: OperationsBoard+): DragPreview | null {+ if (+ !over ||+ over.disabled ||+ !hasDraggableData(over) ||+ !itemsById.has(origin.item.id)+ ) {+ return null;+ }++ const overId = String(over.id);+ if (overId === origin.item.id) {+ return { ...origin.placement, targetType: "item" };+ }++ const overData = over.data.current;+ if (overData?.type === "item") {+ const overItem = itemsById.get(overId);+ if (+ !overItem ||+ overData.item.id !== overId ||+ overData.item.columnId !== overItem.columnId ||+ !columnsById.has(overItem.columnId)+ ) {+ return null;+ }++ const destinationColumn = columnsById.get(overItem.columnId);+ if (!destinationColumn?.type.includes(origin.item.columnType)) {+ return null;+ }++ // Compute the slot directly rather than via getItemPlacement so the+ // insertion marker still renders when the two neighbors share a priority+ // (no fractional gap) — the drop renumbers the column, so the preview must+ // not disappear just because the fast-path priority is unavailable.+ const destinationColumnId = overItem.columnId;+ const destinationItems = getItemsInColumn(+ items,+ destinationColumnId,+ origin.item.id+ );+ const sameColumn = origin.placement.columnId === destinationColumnId;+ const insertionIndex = getInsertionIndex(+ destinationItems,+ overItem.id,+ sameColumn,+ origin.placement.slot.index+ );+ if (insertionIndex === null) return null;++ const fractionalPriority = calculateFractionalPriority(+ destinationItems[insertionIndex - 1]?.priority,+ destinationItems[insertionIndex]?.priority+ );+ // The marker only needs the slot; the priority just has to be stable per+ // slot so isSamePreview can dedupe. Fall back to the previous neighbor's+ // priority (or the drag-start priority at the top of the column).+ const priority =+ fractionalPriority ??+ destinationItems[insertionIndex - 1]?.priority ??+ origin.placement.priority;++ return {+ columnId: destinationColumnId,+ priority,+ slot: getLogicalSlot(destinationItems, insertionIndex),+ targetType: "item"+ };+ }++ if (overData?.type === "column") {+ if (+ overData.column.id !== overId ||+ !columnsById.has(overId) ||+ overId === origin.placement.columnId+ ) {+ return null;+ }++ const destinationColumn = columnsById.get(overId);+ if (!destinationColumn?.type.includes(origin.item.columnType)) {+ return null;+ }++ const placement = getColumnPlacement(origin, items, overId);+ return placement ? { ...placement, targetType: "column" } : null;+ }++ return null;+}++/**+ * Resolves the priority writes a drop should persist. Unlike the hover+ * preview (which gives up when the two neighbors have no numeric gap), this+ * never abandons a valid drop over a priority collision: it falls back to+ * renumbering the destination column so a fully equal-priority column — every+ * op still at the default `1` because the scheduler has not sequenced them —+ * can still be reordered. A no-op drop (dropped back in place,+ * invalid/incompatible target) returns null.+ */+function resolveOperationCommit(+ origin: OperationDragOrigin,+ over: Over | null,+ { items, itemsById, columnsById }: OperationsBoard+): DragCommit | null {+ if (+ !over ||+ over.disabled ||+ !hasDraggableData(over) ||+ !itemsById.has(origin.item.id)+ ) {+ return null;+ }++ const overId = String(over.id);+ if (overId === origin.item.id) return null;++ const overData = over.data.current;+ if (overData?.type === "item") {+ const overItem = itemsById.get(overId);+ if (+ !overItem ||+ overData.item.id !== overId ||+ overData.item.columnId !== overItem.columnId ||+ !columnsById.has(overItem.columnId)+ ) {+ return null;+ }++ const destinationColumn = columnsById.get(overItem.columnId);+ if (!destinationColumn?.type.includes(origin.item.columnType)) {+ return null;+ }++ const destinationColumnId = overItem.columnId;+ const destinationItems = getItemsInColumn(+ items,+ destinationColumnId,+ origin.item.id+ );+ const sameColumn = origin.placement.columnId === destinationColumnId;+ const insertionIndex = getInsertionIndex(+ destinationItems,+ overItem.id,+ sameColumn,+ origin.placement.slot.index+ );+ if (insertionIndex === null) return null;++ const slot = getLogicalSlot(destinationItems, insertionIndex);+ if (+ isSamePlacement(origin.placement, {+ columnId: destinationColumnId,+ priority: origin.placement.priority,+ slot+ })+ ) {+ return null;+ }++ const fractionalPriority = calculateFractionalPriority(+ destinationItems[insertionIndex - 1]?.priority,+ destinationItems[insertionIndex]?.priority+ );+ const updates =+ fractionalPriority === null+ ? planColumnReorder(origin, items, destinationColumnId, insertionIndex)+ : [{ id: origin.item.id, priority: fractionalPriority }];++ return updates.length ? { columnId: destinationColumnId, updates } : null;+ }++ if (overData?.type === "column") {+ if (overData.column.id !== overId) return null;+ return resolveColumnCommit(origin, items, columnsById, overId);+ }++ return null;+}++/**+ * The priority writes for dropping a card on a column's background (it lands+ * at the column's end). Shared by the drop and by the phone "Move to" menu.+ */+export function resolveColumnCommit(+ origin: OperationDragOrigin,+ items: readonly Item[],+ columnsById: ReadonlyMap<string, Column>,+ columnId: string+): DragCommit | null {+ if (!columnsById.has(columnId) || columnId === origin.placement.columnId) {+ return null;+ }++ const destinationColumn = columnsById.get(columnId);+ if (!destinationColumn?.type.includes(origin.item.columnType)) {+ return null;+ }++ const placement = getColumnPlacement(origin, items, columnId);+ if (placement) {+ return {+ columnId,+ updates: [{ id: origin.item.id, priority: placement.priority }]+ };+ }++ // A background/empty-column drop whose origin priority collides with an+ // existing card — renumber, appending the dragged op to the column's end.+ const destinationItems = getItemsInColumn(items, columnId, origin.item.id);+ const updates = planColumnReorder(+ origin,+ items,+ columnId,+ destinationItems.length+ );+ return updates.length ? { columnId, updates } : null;+}++export type CommitSubmission = {+ action: "operation" | "batching";+ payload: Record<string, string | number>;+ fetcherKey: string;+ flushSync: boolean;+};++/** The requests that persist a resolved move, in the order they are sent. */+export function planCommitSubmissions(+ origin: OperationDragOrigin,+ commit: DragCommit,+ itemsById: ReadonlyMap<string, Item>+): CommitSubmission[] {+ if (+ isBatchItem(origin.item) &&+ commit.columnId !== origin.placement.columnId+ ) {+ // A batch dropped on a DIFFERENT work center reassigns the whole batch+ // (the server fn writes the work center to every member) and reschedules;+ // the priority renumber is left to the resulting replan wave.+ return [+ {+ action: "batching",+ payload: {+ intent: "update",+ batchId: origin.item.batchId,+ workCenterId: commit.columnId+ },+ fetcherKey: `item:${origin.item.id}`,+ flushSync: true+ }+ ];+ }++ // Within-column reorder (or a non-batch cross-column move). Each renumbered+ // card writes through its own endpoint: an operation writes its priority+ // (+ work center), a batch card writes every member's priority so+ // min(member) lands at the batch's new dispatch slot.+ const flushSync = commit.updates.length === 1;+ const isBatchCard = (id: string) => {+ const target = itemsById.get(id);+ return !!target && isBatchItem(target);+ };+ const submissions: CommitSubmission[] = [];+ // Several operations renumbered by one drop go in ONE request. One request+ // per card meant one page reload per card, and the board stuttered for+ // seconds after the drop.+ const operationUpdates = commit.updates.filter(+ (update) => !isBatchCard(update.id)+ );+ if (operationUpdates.length > 1) {+ submissions.push({+ action: "operation",+ payload: {+ columnId: commit.columnId,+ updates: JSON.stringify(operationUpdates)+ },+ // Not the card's own key: a later move of that card would replace this+ // fetcher and drop the other cards' pending order.+ fetcherKey: `reorder:${commit.columnId}`,+ flushSync: false+ });+ }+ for (const update of commit.updates) {+ const target = itemsById.get(update.id);+ if (operationUpdates.length > 1 && !isBatchCard(update.id)) continue;+ if (target && isBatchItem(target)) {+ submissions.push({+ action: "batching",+ payload: {+ intent: "reprioritize",+ batchId: target.batchId,+ priority: update.priority+ },+ fetcherKey: `item:${update.id}`,+ flushSync+ });+ } else {+ submissions.push({+ action: "operation",+ payload: {+ id: update.id,+ columnId: commit.columnId,+ priority: update.priority+ },+ fetcherKey: `item:${update.id}`,+ flushSync+ });+ }+ }+ return submissions;+}++// ---------------------------------------------------------------------------+// Dates board+// ---------------------------------------------------------------------------++export type DateDragOrigin = DragOrigin<JobItem> & {+ dueDate: string | null | undefined;+};++export type DatesDragState = {+ origin: DateDragOrigin;+ preview: DragPreview | null;+} | null;++export type DatesBoard = {+ items: readonly JobItem[];+ itemsById: ReadonlyMap<string, JobItem>;+ columnsById: ReadonlyMap<string, Column>;+ locationId: string;+};++export type DateSubmission = {+ id: string;+ locationId: string;+ columnId: string;+ optimisticColumnId: string;+ priority: number;+};++/** Same lifecycle as the Operations board, writing one job's due date. */+export function reduceDatesDrag(+ state: DatesDragState,+ event: BoardDragEvent,+ board: DatesBoard+): { state: DatesDragState; submission: DateSubmission | null } {+ switch (event.type) {+ case "start": {+ if (+ !hasDraggableData(event.active) ||+ event.active.data.current?.type !== "item"+ ) {+ return { state: null, submission: null };+ }+ const activeItem = board.itemsById.get(String(event.active.id));+ if (!activeItem || !board.columnsById.has(activeItem.columnId)) {+ return { state: null, submission: null };+ }+ const origin = createDateDragOrigin(board.items, activeItem);+ return {+ state: origin ? { origin, preview: null } : null,+ submission: null+ };+ }+ case "over": {+ if (!state) return { state, submission: null };+ const placement = isOriginItemDrag(event.active, state.origin)+ ? resolveDatePlacement(state.origin, event.over, board)+ : null;+ const preview =+ placement && !isSamePlacement(state.origin.placement, placement)+ ? placement+ : null;+ return {+ state: isSamePreview(state.preview, preview)+ ? state+ : { ...state, preview },+ submission: null+ };+ }+ case "end": {+ const placement =+ state && isOriginItemDrag(event.active, state.origin)+ ? resolveDatePlacement(state.origin, event.over, board)+ : null;+ return {+ state: null,+ submission:+ state && placement+ ? datePlacementSubmission(state.origin, placement, board.locationId)+ : null+ };+ }+ case "cancel":+ return { state: null, submission: null };+ }+}++export function createDateDragOrigin(+ items: readonly JobItem[],+ activeItem: JobItem+): DateDragOrigin | null {+ const placementOrigin = createDragOrigin(items, activeItem);+ if (!placementOrigin) return null;+ return {+ ...placementOrigin,+ dueDate:+ activeItem.dueDate === undefined+ ? undefined+ : getDateOnly(activeItem.dueDate)+ };+}++/**+ * A reorder inside the same display bucket keeps the job's exact persisted+ * date (a week column stands for seven dates); a move to another bucket takes+ * that bucket's date. A job whose date is unknown is never written.+ */+export function datePlacementSubmission(+ origin: DateDragOrigin,+ placement: DragPlacement,+ locationId: string+): DateSubmission | null {+ if (+ origin.dueDate === undefined ||+ isSamePlacement(origin.placement, placement)+ ) {+ return null;+ }+ const isSameDisplayBucket = placement.columnId === origin.placement.columnId;+ return {+ id: origin.item.id,+ locationId,+ columnId: isSameDisplayBucket+ ? (origin.dueDate ?? origin.placement.columnId)+ : placement.columnId,+ optimisticColumnId: placement.columnId,+ priority: placement.priority+ };+}++function resolveDatePlacement(+ origin: DateDragOrigin,+ over: Over | null,+ { items, itemsById, columnsById }: DatesBoard+): DragPreview | null {+ if (+ !over ||+ over.disabled ||+ !hasDraggableData(over) ||+ !itemsById.has(origin.item.id)+ ) {+ return null;+ }++ const overId = String(over.id);+ if (overId === origin.item.id) {+ return { ...origin.placement, targetType: "item" };+ }++ const overData = over.data.current;+ if (overData?.type === "item") {+ const overItem = itemsById.get(overId);+ if (+ !overItem ||+ overData.item.id !== overId ||+ overData.item.columnId !== overItem.columnId ||+ !columnsById.has(overItem.columnId)+ ) {+ return null;+ }++ const placement = getItemPlacement(+ origin,+ items,+ overItem.columnId,+ overItem.id+ );+ return placement ? { ...placement, targetType: "item" } : null;+ }++ if (overData?.type === "column") {+ if (+ overData.column.id !== overId ||+ !columnsById.has(overId) ||+ overId === origin.placement.columnId+ ) {+ return null;+ }++ const placement = getColumnPlacement(origin, items, overId);+ return placement ? { ...placement, targetType: "column" } : null;+ }++ return null;+}++export type PendingDateMove = {+ id: string;+ priority: number;+ columnId: string;+ dueDate: string | null | undefined;+};++/**+ * In-flight due-date writes for this board's location, as the item fields they+ * will produce: the card shows in its optimistic column and carries the date+ * the server will persist.+ */+export function pendingDateMoves(+ fetchers: readonly { formAction?: string; formData?: FormData }[],+ { action, locationId }: { action: string; locationId: string }+): PendingDateMove[] {+ return fetchers.flatMap((fetcher) => {+ const formData = fetcher.formData;+ if (+ fetcher.formAction !== action ||+ !formData ||+ formData.get("locationId") !== locationId+ ) {+ return [];+ }+ const persistenceColumnId = formData.get("columnId");+ const optimisticColumnId = formData.get("optimisticColumnId");+ const columnId =+ typeof optimisticColumnId === "string" && optimisticColumnId.length > 0+ ? optimisticColumnId+ : typeof persistenceColumnId === "string"+ ? persistenceColumnId+ : "";+ const id = formData.get("id");+ return [+ {+ id: typeof id === "string" ? id : "",+ priority: Number(formData.get("priority")),+ columnId,+ dueDate:+ typeof persistenceColumnId === "string"+ ? getPendingDueDate(persistenceColumnId)+ : undefined+ }+ ];+ });+}++export function mergePendingDateMoves(+ items: readonly JobItem[],+ pending: readonly PendingDateMove[]+): Map<string, JobItem> {+ const itemsById = new Map(items.map((item) => [item.id, item]));+ for (const move of pending) {+ const item = itemsById.get(move.id);+ if (item) itemsById.set(move.id, { ...item, ...move });+ }+ return itemsById;+}diff --git a/apps/erp/app/modules/purchasing/purchasing.models.test.ts b/apps/erp/app/modules/purchasing/purchasing.models.test.tsindex efb362e931..8ab3083d14 100644--- a/apps/erp/app/modules/purchasing/purchasing.models.test.ts+++ b/apps/erp/app/modules/purchasing/purchasing.models.test.ts@@ -2,28 +2,11 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { describe, expect, it, vi } from "vitest";--// @carbon/content/glossary's terms.ts evaluates Lingui `msg` macros at module load,-// which vitest doesn't transform. Nothing under test touches the glossary-// (it's pulled in via the ../shared barrel), so stub the whole package.-vi.mock("@carbon/content/glossary", () => ({- getDefinitionText: () => "",- getEntry: () => undefined,- getTermText: () => "",- glossaryEntries: () => [],- hasEntry: () => false,- listEntries: () => [],- lookupEntry: () => undefined,- termSlug: (t: string) => t,- terms: {}-}));--import * as purchasingModels from "./purchasing.models";+import { describe, expect, it } from "vitest";+import {canCreatePurchaseOrderRevision,isPurchaseOrderLocked,- leaseClassificationValidator,leaseDetailsValidator,leaseDurationOf,leaseEndDate,@@ -76,31 +59,19 @@ describe("canCreatePurchaseOrderRevision", () => {{ currentStatus: "To Receive", orderDate: null, expected: false }];- it.each(reopenMatrix)(- "reopen from $currentStatus (orderDate: $orderDate) → eligible: $expected",- ({ currentStatus, orderDate, expected }) => {+ it.each(+ (["Draft", "Planned"] as const).flatMap((newStatus) =>+ reopenMatrix.map((row) => ({ ...row, newStatus }))+ )+ )(+ "reopen to $newStatus from $currentStatus (orderDate: $orderDate) → eligible: $expected",+ ({ newStatus, currentStatus, orderDate, expected }) => {expect(- canCreatePurchaseOrderRevision({- newStatus: "Draft",- currentStatus,- orderDate- })+ canCreatePurchaseOrderRevision({ newStatus, currentStatus, orderDate })).toBe(expected);});- it("follows the same matrix when reopening to Planned", () => {- for (const { currentStatus, orderDate, expected } of reopenMatrix) {- expect(- canCreatePurchaseOrderRevision({- newStatus: "Planned",- currentStatus,- orderDate- })- ).toBe(expected);- }- });-it("is never eligible for a target status that is not a reopen", () => {for (const newStatus of purchaseOrderStatusType) {if (newStatus === "Draft" || newStatus === "Planned") continue;@@ -116,22 +87,18 @@ describe("canCreatePurchaseOrderRevision", () => {}});- it("is not eligible for an unknown or missing current status", () => {- expect(- canCreatePurchaseOrderRevision({- newStatus: "Draft",- currentStatus: null,- orderDate: ORDER_DATE- })- ).toBe(false);- expect(- canCreatePurchaseOrderRevision({- newStatus: "Draft",- currentStatus: undefined,- orderDate: ORDER_DATE- })- ).toBe(false);- });+ it.each([null, undefined])(+ "is not eligible for a current status of %s",+ (currentStatus) => {+ expect(+ canCreatePurchaseOrderRevision({+ newStatus: "Draft",+ currentStatus,+ orderDate: ORDER_DATE+ })+ ).toBe(false);+ }+ );it("locked statuses stay consistent with the reopen matrix", () => {const bumpingStatuses = reopenMatrix@@ -145,25 +112,10 @@ describe("canCreatePurchaseOrderRevision", () => {});});-describe("the document validators carry no contact requirement (D-2)", () => {- /**- * The requirement is on the SUPPLIER RECORD, checked once at the release- * boundary by `checkPartyContactRequirement` — not on the document. The- * `make*Validator` factories that made `supplierContactId` /- * `supplierLocationId` required were absent from every create action (so the- * API, MCP and curl wrote a null contact anyway) and refused to save an- * EXISTING draft whose optional location was null, which blocked editing- * unrelated fields such as `supplierReference`.- */- it("offers no strict variant to build a document-level rule from", () => {- const exported = Object.keys(purchasingModels);- expect(exported).not.toContain("makePurchaseOrderValidator");- expect(exported).not.toContain("makeSupplierQuoteValidator");- });-- it("saves a draft whose optional supplier location is null", () => {- // The concrete regression: a Draft PO with no location could no longer have- // its supplier reference changed.+// The contact requirement lives on the supplier record, checked at release,+// so a draft with no supplier location must still save.+describe("document validators", () => {+ it("save a draft whose optional supplier location is null", () => {expect(purchaseOrderValidator.safeParse({id: "po_1",@@ -172,7 +124,6 @@ describe("the document validators carry no contact requirement (D-2)", () => {supplierReference: "PO-4417"}).success).toBe(true);-expect(supplierQuoteValidator.safeParse({id: "sq_1",@@ -184,36 +135,36 @@ describe("the document validators carry no contact requirement (D-2)", () => {});});-describe("leaseValidator", () => {- const base = {- supplierId: "supplier-1",- commencementDate: "2027-01-01",- endDate: "2029-12-31",- paymentFrequency: "Monthly",- paymentTiming: "Arrears",- discountRate: "6",- currencyCode: "USD"- };- const parse = (overrides: Record<string, string>) =>- leaseValidator.safeParse({ ...base, ...overrides });+const leaseTerms = {+ supplierId: "supplier-1",+ commencementDate: "2027-01-01",+ endDate: "2029-12-31",+ paymentFrequency: "Monthly",+ paymentTiming: "Arrears",+ discountRate: "6",+ currencyCode: "USD"+};+const parseLease = (overrides: Record<string, string>) =>+ leaseValidator.safeParse({ ...leaseTerms, ...overrides });+describe("leaseValidator", () => {it("accepts a lease with only the required terms", () => {- const result = parse({});+ const result = parseLease({});expect(result.success).toBe(true);expect(result.data?.annualEscalationPercent).toBe(0);});it("refuses an end date before the commencement date", () => {- expect(parse({ endDate: "2026-12-31" }).success).toBe(false);+ expect(parseLease({ endDate: "2026-12-31" }).success).toBe(false);});it("refuses a notice date after the end date", () => {- expect(parse({ noticeDate: "2030-01-31" }).success).toBe(false);- expect(parse({ noticeDate: "2029-09-30" }).success).toBe(true);+ expect(parseLease({ noticeDate: "2030-01-31" }).success).toBe(false);+ expect(parseLease({ noticeDate: "2029-09-30" }).success).toBe(true);});it("refuses invoicing that starts before commencement", () => {- expect(parse({ invoiceFromDate: "2026-12-01" }).success).toBe(false);+ expect(parseLease({ invoiceFromDate: "2026-12-01" }).success).toBe(false);});});@@ -238,12 +189,8 @@ describe("lease durations", () => {it("needs an end date only for a custom duration", () => {const parse = (overrides: Record<string, string>) =>leaseValidator.safeParse({- supplierId: "supplier-1",- commencementDate: "2027-01-01",- paymentFrequency: "Monthly",- paymentTiming: "Arrears",- discountRate: "6",- currencyCode: "USD",+ ...leaseTerms,+ endDate: undefined,...overrides});expect(parse({ duration: "open" }).success).toBe(true);@@ -273,10 +220,6 @@ describe("leaseLineValidator", () => {expect(result.data?.ownershipTransfers).toBe(false);});- it("needs a description", () => {- expect(parse({ description: " " }).success).toBe(false);- });-it("needs an amount for a reasonably certain purchase option", () => {expect(parse({ purchaseOptionReasonablyCertain: "on" }).success).toBe(false@@ -314,14 +257,6 @@ describe("leaseModifyValidator", () => {paymentFrequency: "Monthly"};- it("takes a payment for each asset", () => {- const result = leaseModifyValidator.safeParse(terms);- expect(result.success).toBe(true);- expect(result.data?.lines).toEqual([- { leaseLineId: "line-1", paymentAmount: 10000 }- ]);- });-it("refuses an end date before the effective date", () => {expect(leaseModifyValidator.safeParse({ ...terms, endDate: "2027-12-31" })@@ -331,34 +266,18 @@ describe("leaseModifyValidator", () => {});describe("lease dates", () => {- const base = {- supplierId: "supplier-1",- commencementDate: "2027-01-01",- endDate: "2029-12-31",- paymentFrequency: "Monthly",- paymentTiming: "Arrears",- discountRate: "6",- currencyCode: "USD"- };-- it("refuses a lease date that is not a YYYY-MM-DD calendar date", () => {- for (const field of [- "commencementDate",- "endDate",- "noticeDate",- "invoiceFromDate"- ]) {- for (const value of ["2027-02-30", "01/02/2027", "soon"]) {- const result = leaseValidator.safeParse({ ...base, [field]: value });- expect(result.success, `${field} = ${value}`).toBe(false);- }- }+ it.each(+ ["commencementDate", "endDate", "noticeDate", "invoiceFromDate"].flatMap(+ (field) =>+ ["2027-02-30", "01/02/2027", "soon"].map((value) => [field, value])+ )+ )("refuses %s = %s", (field, value) => {+ expect(parseLease({ [field]: value }).success).toBe(false);});it("reports a bad commencement date instead of throwing from the notice refine", () => {expect(() =>- leaseValidator.safeParse({- ...base,+ parseLease({commencementDate: "not-a-date",duration: "36",noticeDate: "2029-06-30"@@ -492,63 +411,32 @@ describe("leaseDetailsValidator", () => {});describe("lease action validators", () => {- it("terminate: a date, and a penalty that defaults to 0 and is never negative", () => {- const ok = leaseTerminateValidator.safeParse({- terminationDate: "2028-06-30"- });- expect(ok.success).toBe(true);- expect(ok.data?.penaltyAmount).toBe(0);+ it("terminate defaults the penalty to 0", () => {expect(+ leaseTerminateValidator.safeParse({ terminationDate: "2028-06-30" }).data+ ?.penaltyAmount+ ).toBe(0);+ });++ it.each([+ [+ "a negative termination penalty",leaseTerminateValidator.safeParse({terminationDate: "2028-06-30",penaltyAmount: "-1"- }).success- ).toBe(false);- expect(- leaseTerminateValidator.safeParse({ terminationDate: "" }).success- ).toBe(false);- });-- it("purchase: a price of 0 or more, a fixed asset class and a name", () => {- const terms = {- exerciseDate: "2029-12-31",- purchasePrice: "0",- fixedAssetClassId: "class-1",- name: "Forklift FL-12"- };- expect(leasePurchaseValidator.safeParse(terms).success).toBe(true);- expect(- leasePurchaseValidator.safeParse({ ...terms, purchasePrice: "-5" })- .success- ).toBe(false);- expect(- leasePurchaseValidator.safeParse({ ...terms, fixedAssetClassId: "" })- .success- ).toBe(false);- expect(- leasePurchaseValidator.safeParse({ ...terms, name: " " }).success- ).toBe(false);- });-- it("classification: Operating or Finance, with a reason", () => {- expect(- leaseClassificationValidator.safeParse({- classification: "Finance",- reason: "Specialized tooling"- }).success- ).toBe(true);- expect(- leaseClassificationValidator.safeParse({- classification: "Short-Term",- reason: "Under a year"- }).success- ).toBe(false);- expect(- leaseClassificationValidator.safeParse({- classification: "Operating",- reason: " "- }).success- ).toBe(false);+ })+ ],+ [+ "a negative purchase price",+ leasePurchaseValidator.safeParse({+ exerciseDate: "2029-12-31",+ purchasePrice: "-5",+ fixedAssetClassId: "class-1",+ name: "Forklift FL-12"+ })+ ]+ ])("refuses %s", (_, result) => {+ expect(result.success).toBe(false);});});diff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.tsindex 9e3d1e0512..6af196e9ff 100644--- a/apps/erp/app/modules/purchasing/purchasing.models.ts+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts@@ -8,7 +8,10 @@ import {addMonths,bicMatchesCountry,getBankFieldConfig,+ getCompletionAfterQuantityChange,isValidSwiftBic,+ RoundingMode,+ round,type TaxPair,taxableBase,taxPairFromAmount,@@ -810,6 +813,85 @@ export function taxPairForQuantity();}+/** A purchase order line as a planning Increase / Decrease reads it. */+export type PlanningQuantityLine = {+ supplierUnitPrice: number | null;+ supplierShippingCost: number | null;+ purchaseQuantity: number | null;+ quantityReceived: number | null;+ quantityInvoiced: number | null;+ receivedComplete: boolean | null;+ taxPercent: number | null;+ supplierTaxAmount: number | null;+ conversionFactor: number | null;+ currencyCode: string | null;+ baseCurrencyCode: string | null;+};++/** A PO with no currency is in the company's base currency, as the PO line+ * form reads it. */+export function planningLineCurrencyCode(line: {+ currencyCode: string | null;+ baseCurrencyCode: string | null;+}): string | null {+ return line.currencyCode ?? line.baseCurrencyCode;+}++/**+ * The write a planning Increase / Decrease makes on its PO line, or why it+ * cannot. `suggestedQuantity` is in INVENTORY units and is what the line+ * should still BRING (MRP reads a line's `quantityToReceive`): it is+ * converted by the line's own `conversionFactor`, rounded up to a whole+ * purchase unit, and what was already received is added back.+ */+export function planningQuantityChange(+ line: PlanningQuantityLine | undefined,+ decimalsByCode: Map<string, number>,+ suggestedQuantity: number+):+ | {+ ok: true;+ quantity: number;+ percent: number;+ amount: number;+ receivedComplete: boolean;+ invoicedComplete: boolean;+ }+ | { ok: false; message: string } {+ const currencyCode = line ? planningLineCurrencyCode(line) : null;+ const decimals = currencyCode ? decimalsByCode.get(currencyCode) : undefined;+ if (!line || decimals === undefined) {+ return {+ ok: false,+ message: line+ ? `Currency ${currencyCode ?? "(none)"} has no precision`+ : "Purchase order line not found"+ };+ }+ const conversionFactor = Number(line.conversionFactor) || 1;+ // MRP suggests a whole number of purchase units already+ // (`quantityAfterApply`, @carbon/planning); the inner round strips float+ // noise (1.1 / 0.1 = 11.000000000000002) that would otherwise ceil it a+ // whole purchase unit up.+ const toReceive =+ conversionFactor > 0+ ? round(+ round(Number(suggestedQuantity) / conversionFactor),+ 0,+ RoundingMode.Up+ )+ : Number(suggestedQuantity);+ const quantity = round((Number(line.quantityReceived) || 0) + toReceive);+ const pair = taxPairForQuantity(line, quantity, decimals);+ return {+ ok: true,+ quantity,+ percent: pair.percent,+ amount: pair.amount,+ ...getCompletionAfterQuantityChange(line, quantity)+ };+}+/*** The week a planned PO line is ordered in, as the date that week starts.* Planning raises one PO per supplier per week, so each PO can be finalizeddiff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex 8471353591..5acaff3989 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -93,7 +93,6 @@ import {normalizeLesseeLegs,openEndedLeaseHorizon,paymentMonthIndex,- RoundingMode,remeasureLease,round,searchFilter@@ -182,6 +181,8 @@ import {PLANNING_EDITABLE_PURCHASE_ORDER_STATUSES,PURCHASE_ORDER_LOCKED_STATUSES,type PURCHASE_ORDER_REOPEN_STATUSES,+ planningLineCurrencyCode,+ planningQuantityChange,taxPairForQuantity} from "./purchasing.models";import { renderPurchaseOrderPdf } from "./purchasing.pdf";@@ -2427,41 +2428,36 @@ export async function applyPurchasingPlanningActions();if (quantities.length > 0) {const lineIds = [...new Set(quantities.map((a) => a.lineId))];- // A PO with no currency is in the company's base currency, as the PO- // line form reads it; refusing it failed every Increase / Decrease on- // such a PO with "Currency (none) has no precision".- const lines = (- await trx- .selectFrom("purchaseOrderLine as pol")- .innerJoin("purchaseOrder as po", "po.id", "pol.purchaseOrderId")- .innerJoin("company as c", "c.id", "po.companyId")- .select([- "pol.id",- "pol.supplierUnitPrice",- "pol.supplierShippingCost",- "pol.purchaseQuantity",- "pol.quantityReceived",- "pol.quantityInvoiced",- "pol.receivedComplete",- "pol.taxPercent",- "pol.supplierTaxAmount",- "pol.conversionFactor",- "po.currencyCode",- "c.baseCurrencyCode"- ])- .where("pol.id", "in", lineIds)- .where("pol.companyId", "=", companyId)- // the completion flags below are derived from these rows- .forUpdate("pol")- .execute()- ).map(({ baseCurrencyCode, ...line }) => ({- ...line,- currencyCode: line.currencyCode ?? baseCurrencyCode- }));+ const lines = await trx+ .selectFrom("purchaseOrderLine as pol")+ .innerJoin("purchaseOrder as po", "po.id", "pol.purchaseOrderId")+ .innerJoin("company as c", "c.id", "po.companyId")+ .select([+ "pol.id",+ "pol.supplierUnitPrice",+ "pol.supplierShippingCost",+ "pol.purchaseQuantity",+ "pol.quantityReceived",+ "pol.quantityInvoiced",+ "pol.receivedComplete",+ "pol.taxPercent",+ "pol.supplierTaxAmount",+ "pol.conversionFactor",+ "po.currencyCode",+ "c.baseCurrencyCode"+ ])+ .where("pol.id", "in", lineIds)+ .where("pol.companyId", "=", companyId)+ // the completion flags below are derived from these rows+ .forUpdate("pol")+ .execute();const lineById = new Map(lines.map((line) => [line.id, line]));const codes = [...new Set(- lines.flatMap((l) => (l.currencyCode ? [l.currencyCode] : []))+ lines.flatMap((l) => {+ const code = planningLineCurrencyCode(l);+ return code ? [code] : [];+ }))];const currencies =@@ -2489,44 +2485,21 @@ export async function applyPurchasingPlanningActions(}[] = [];const unheld: string[] = [];for (const action of quantities) {- const line = lineById.get(action.lineId);- const decimals = line?.currencyCode- ? decimalsByCode.get(line.currencyCode)- : undefined;- if (!line || decimals === undefined) {+ const change = planningQuantityChange(+ lineById.get(action.lineId),+ decimalsByCode,+ Number(action.suggestedQuantity)+ );+ if (!change.ok) {result.failed.push({id: action.planningActionId,- message: line- ? `Currency ${line.currencyCode ?? "(none)"} has no precision`- : "Purchase order line not found"+ message: change.message});unheld.push(action.planningActionId);continue;}- const conversionFactor = Number(line.conversionFactor) || 1;- // MRP suggests a whole number of purchase units already- // (`quantityAfterApply`, @carbon/planning); the inner round strips- // float noise (1.1 / 0.1 = 11.000000000000002) that would otherwise- // ceil it a whole purchase unit up.- const toReceive =- conversionFactor > 0- ? round(- round(Number(action.suggestedQuantity) / conversionFactor),- 0,- RoundingMode.Up- )- : Number(action.suggestedQuantity);- const quantity = round(- (Number(line.quantityReceived) || 0) + toReceive- );- const pair = taxPairForQuantity(line, quantity, decimals);- values.push({- lineId: action.lineId,- quantity,- percent: pair.percent,- amount: pair.amount,- ...getCompletionAfterQuantityChange(line, quantity)- });+ const { ok: _, ...value } = change;+ values.push({ lineId: action.lineId, ...value });}// a failed computation never holds its claimfor (const id of unheld) claimed.delete(id);@@ -3071,8 +3044,8 @@ export async function getPurchasingRFQSuppliers(client: SupabaseClient<Database>,purchasingRfqId: string): Promise<PostgrestResponse<PurchasingRfqSupplierWithSupplier>> {- // 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.+ // TypeScript's limit; the cliff shifts as unrelated modules join the+ // program. ts-ignore, not ts-expect-error, since the error comes and goes.return client.from("purchasingRfqSupplier").select("*, supplier(id, name)")diff --git a/apps/erp/app/modules/resources/resources.models.test.ts b/apps/erp/app/modules/resources/resources.models.test.tsindex 436db617e4..e5eada020e 100644--- a/apps/erp/app/modules/resources/resources.models.test.ts+++ b/apps/erp/app/modules/resources/resources.models.test.ts@@ -2,55 +2,17 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { describe, expect, it, vi } from "vitest";--// resources.models' module graph transitively builds Lingui `msg` descriptors at-// module load. The macro isn't transformed under plain vitest, so raw `msg`-// throws. Stub it to a plain string builder; the validator under test is-// untouched.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray | string, ...values: unknown[]) =>- Array.isArray(strings)- ? strings.reduce(- (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),- ""- )- : String(strings)-}));--const { abilityValidator } = await import("./resources.models");--// An ability is a process's qualification: it is created ONLY by picking a-// process, and it does not carry its own name (the name derives from the linked-// process). So the validator must require `processId` and must not accept a-// free-form `name`.-describe("abilityValidator", () => {- it("accepts a processId (recertifyEveryDays optional)", () => {- const parsed = abilityValidator.safeParse({ processId: "proc_1" });- expect(parsed.success).toBe(true);- });-- it("requires a processId", () => {- const parsed = abilityValidator.safeParse({ recertifyEveryDays: 30 });- expect(parsed.success).toBe(false);- });-- it("does not carry a free-form name", () => {- const parsed = abilityValidator.safeParse({- processId: "proc_1",- name: "Welding"- });- expect(parsed.success).toBe(true);- if (parsed.success) {- expect("name" in parsed.data).toBe(false);- }- });-});--describe("isValidTrainingGuideKey", async () => {- const { isValidTrainingGuideKey, trainingGuideKeyPrefix } = await import(- "./resources.models"- );+import { describe, expect, it } from "vitest";+import {+ getYouTubeVideoId,+ isValidTrainingGuideKey,+ TRAINING_CERTIFICATE_MAX_BYTES,+ trainingAssignmentValidator,+ trainingGuideKeyPrefix,+ validateTrainingCertificate+} from "./resources.models";++describe("isValidTrainingGuideKey", () => {const prefix = trainingGuideKeyPrefix("c1", "t1");it("accepts one upload folder and one file", () => {@@ -59,69 +21,47 @@ describe("isValidTrainingGuideKey", async () => {).toBe(true);});- it("refuses another company's or training's key", () => {- expect(- isValidTrainingGuideKey("c2/training/t1/abc/guide.pdf", prefix)- ).toBe(false);- expect(- isValidTrainingGuideKey("c1/training/t2/abc/guide.pdf", prefix)- ).toBe(false);- });-- it("refuses a file with no upload folder, or a deeper path", () => {- expect(isValidTrainingGuideKey("c1/training/t1/guide.pdf", prefix)).toBe(- false- );- expect(- isValidTrainingGuideKey("c1/training/t1/abc/d/guide.pdf", prefix)- ).toBe(false);- });-- it("refuses dot segments and empty segments", () => {- expect(isValidTrainingGuideKey("c1/training/t1/../x.pdf", prefix)).toBe(- false- );- expect(isValidTrainingGuideKey("c1/training/t1/abc/", prefix)).toBe(false);+ it.each([+ "c2/training/t1/abc/guide.pdf",+ "c1/training/t2/abc/guide.pdf",+ "c1/training/t1/guide.pdf",+ "c1/training/t1/abc/d/guide.pdf",+ "c1/training/t1/../x.pdf",+ "c1/training/t1/abc/"+ ])("refuses %s", (key) => {+ expect(isValidTrainingGuideKey(key, prefix)).toBe(false);});});-describe("getYouTubeVideoId", async () => {- const { getYouTubeVideoId } = await import("./resources.models");-- it("reads the id from every YouTube link form", () => {- for (const url of [- "https://www.youtube.com/watch?v=dQw4w9WgXcQ",- "https://youtube.com/watch?v=dQw4w9WgXcQ&t=42s",- "https://m.youtube.com/watch?v=dQw4w9WgXcQ",- "https://youtu.be/dQw4w9WgXcQ?si=abc",- "https://www.youtube.com/shorts/dQw4w9WgXcQ",- "https://www.youtube.com/live/dQw4w9WgXcQ",- "https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ",- " https://www.youtube.com/watch?v=dQw4w9WgXcQ "- ]) {- expect(getYouTubeVideoId(url)).toBe("dQw4w9WgXcQ");- }- });-- it("refuses links that are not a YouTube video", () => {- for (const url of [- "",- "not a url",- "https://vimeo.com/123456789",- "https://www.youtube.com/",- "https://www.youtube.com/watch?v=short",- "https://evil.com/watch?v=dQw4w9WgXcQ",- "https://youtube.com.evil.com/watch?v=dQw4w9WgXcQ",- "javascript:alert(1)//youtu.be/dQw4w9WgXcQ"- ]) {- expect(getYouTubeVideoId(url)).toBeNull();- }+describe("getYouTubeVideoId", () => {+ it.each([+ "https://www.youtube.com/watch?v=dQw4w9WgXcQ",+ "https://youtube.com/watch?v=dQw4w9WgXcQ&t=42s",+ "https://m.youtube.com/watch?v=dQw4w9WgXcQ",+ "https://youtu.be/dQw4w9WgXcQ?si=abc",+ "https://www.youtube.com/shorts/dQw4w9WgXcQ",+ "https://www.youtube.com/live/dQw4w9WgXcQ",+ "https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ",+ " https://www.youtube.com/watch?v=dQw4w9WgXcQ "+ ])("reads the id from %s", (url) => {+ expect(getYouTubeVideoId(url)).toBe("dQw4w9WgXcQ");+ });++ it.each([+ "",+ "not a url",+ "https://vimeo.com/123456789",+ "https://www.youtube.com/",+ "https://www.youtube.com/watch?v=short",+ "https://evil.com/watch?v=dQw4w9WgXcQ",+ "https://youtube.com.evil.com/watch?v=dQw4w9WgXcQ",+ "javascript:alert(1)//youtu.be/dQw4w9WgXcQ"+ ])("refuses %s", (url) => {+ expect(getYouTubeVideoId(url)).toBeNull();});});-describe("validateTrainingCertificate", async () => {- const { TRAINING_CERTIFICATE_MAX_BYTES, validateTrainingCertificate } =- await import("./resources.models");+describe("validateTrainingCertificate", () => {const PDF = [0x25, 0x50, 0x44, 0x46, 0x2d];const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];const JPG = [0xff, 0xd8, 0xff];@@ -131,93 +71,44 @@ describe("validateTrainingCertificate", async () => {return new File([bytes], name);};- it("accepts a PDF, PNG or JPG and returns its extension", async () => {- expect(- (await validateTrainingCertificate(file("cert.PDF", PDF))).extension- ).toBe("pdf");+ it.each([+ ["cert.PDF", PDF, "pdf"],+ ["photo.jpeg", JPG, "jpeg"],+ ["scan.png", PNG, "png"]+ ])("accepts %s by its leading bytes", async (name, head, extension) => {expect(- (await validateTrainingCertificate(file("photo.jpeg", JPG))).extension- ).toBe("jpeg");- expect(- (await validateTrainingCertificate(file("scan.png", PNG))).error- ).toBeNull();- });-- it("refuses a missing or empty file", async () => {- expect((await validateTrainingCertificate(null)).error).toBe(- "Upload a certificate file"- );- expect(- (await validateTrainingCertificate(file("cert.pdf", [], 0))).error- ).toBe("Upload a certificate file");- });-- it("refuses another type", async () => {- expect((await validateTrainingCertificate(file("notes.txt"))).error).toBe(- "The certificate must be a PDF, PNG or JPG"- );- expect((await validateTrainingCertificate(file("photo.heic"))).error).toBe(- "The certificate must be a PDF, PNG or JPG"- );- });-- it("refuses a file whose bytes do not match its extension", async () => {- expect(- (await validateTrainingCertificate(file("cert.pdf", PNG))).error- ).toBe("The certificate must be a PDF, PNG or JPG");- expect((await validateTrainingCertificate(file("scan.png"))).error).toBe(- "The certificate must be a PDF, PNG or JPG"- );- });-- it("refuses a file over the size limit", async () => {- expect(- (- await validateTrainingCertificate(- file("cert.pdf", PDF, TRAINING_CERTIFICATE_MAX_BYTES + 1)- )- ).error- ).toBe("The certificate must be 10 MB or smaller");+ (await validateTrainingCertificate(file(name, head))).extension+ ).toBe(extension);+ });++ it.each([+ ["no file", null],+ ["an empty file", file("cert.pdf", [], 0)],+ ["another type", file("notes.txt")],+ ["a HEIC photo", file("photo.heic")],+ ["PNG bytes named .pdf", file("cert.pdf", PNG)],+ ["a .png with no signature", file("scan.png")],+ [+ "a file over the size limit",+ file("cert.pdf", PDF, TRAINING_CERTIFICATE_MAX_BYTES + 1)+ ]+ ])("refuses %s", async (_, input) => {+ expect((await validateTrainingCertificate(input)).file).toBeNull();});});// An external assignment has a name and no training; an internal one has a// training. Each must refuse the other's missing field.-describe("trainingAssignmentValidator", async () => {- const { trainingAssignmentValidator } = await import("./resources.models");-- it("accepts an internal assignment with a training", () => {- const parsed = trainingAssignmentValidator.safeParse({- isExternal: false,- trainingId: "trn_1",- groupIds: ["grp_1"]- });- expect(parsed.success).toBe(true);- });-- it("refuses an internal assignment without a training", () => {- const parsed = trainingAssignmentValidator.safeParse({- isExternal: false,- groupIds: ["grp_1"]- });- expect(parsed.success).toBe(false);- });-- it("accepts an external assignment with a name", () => {- const parsed = trainingAssignmentValidator.safeParse({- isExternal: true,- name: "Forklift Safety",- groupIds: ["grp_1"]- });- expect(parsed.success).toBe(true);- });-- it("refuses an external assignment without a name", () => {- const parsed = trainingAssignmentValidator.safeParse({- isExternal: true,- name: " ",- groupIds: ["grp_1"]- });- expect(parsed.success).toBe(false);+describe("trainingAssignmentValidator", () => {+ it.each([+ [{ isExternal: false, trainingId: "trn_1" }, true],+ [{ isExternal: false }, false],+ [{ isExternal: true, name: "Forklift Safety" }, true],+ [{ isExternal: true, name: " " }, false]+ ])("%o parses: %s", (input, success) => {+ expect(+ trainingAssignmentValidator.safeParse({ ...input, groupIds: ["grp_1"] })+ .success+ ).toBe(success);});});diff --git a/apps/erp/app/modules/sales/sales.invoice-summary.test.ts b/apps/erp/app/modules/sales/sales.invoice-summary.test.tsnew file mode 100644index 0000000000..eff8d043cb--- /dev/null+++ b/apps/erp/app/modules/sales/sales.invoice-summary.test.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { summarizeSalesOrderInvoices } from "./sales.utils";++function invoice(+ overrides: Partial<Parameters<typeof summarizeSalesOrderInvoices>[1][number]>+) {+ return {+ id: "inv-1",+ invoiceTotal: 100,+ status: "Posted",+ currencyCode: "USD",+ exchangeRate: 1,+ ...overrides+ };+}++describe("summarizeSalesOrderInvoices", () => {+ it("adds up every applied settlement against an invoice", () => {+ expect(+ summarizeSalesOrderInvoices(+ "USD",+ [invoice({})],+ [+ { targetSalesInvoiceId: "inv-1", appliedAmount: 50 },+ { targetSalesInvoiceId: "inv-1", appliedAmount: 25 },+ { targetSalesInvoiceId: null, appliedAmount: 999 }+ ]+ )+ ).toEqual({+ invoicedAmount: 100,+ paidAmount: 75,+ currencyMismatchCount: 0+ });+ });++ it("converts base totals into the order currency at the invoice's rate", () => {+ // 100 base × 0.8 EUR per base = 80 EUR invoiced; 50 base paid = 40 EUR.+ expect(+ summarizeSalesOrderInvoices(+ "EUR",+ [invoice({ currencyCode: "EUR", exchangeRate: 0.8 })],+ [{ targetSalesInvoiceId: "inv-1", appliedAmount: 50 }]+ )+ ).toEqual({ invoicedAmount: 80, paidAmount: 40, currencyMismatchCount: 0 });+ });++ it("ignores a voided invoice and the payments applied to it", () => {+ expect(+ summarizeSalesOrderInvoices(+ "USD",+ [invoice({}), invoice({ id: "inv-2", status: "Voided" })],+ [+ { targetSalesInvoiceId: "inv-1", appliedAmount: 10 },+ { targetSalesInvoiceId: "inv-2", appliedAmount: 100 }+ ]+ )+ ).toEqual({+ invoicedAmount: 100,+ paidAmount: 10,+ currencyMismatchCount: 0+ });+ });++ it("counts an invoice in another currency instead of mixing it into the totals", () => {+ expect(+ summarizeSalesOrderInvoices(+ "USD",+ [invoice({}), invoice({ id: "inv-2", currencyCode: "EUR" })],+ [{ targetSalesInvoiceId: "inv-2", appliedAmount: 100 }]+ )+ ).toEqual({ invoicedAmount: 100, paidAmount: 0, currencyMismatchCount: 1 });+ });+});diff --git a/apps/erp/app/modules/sales/sales.utils.ts b/apps/erp/app/modules/sales/sales.utils.tsindex e7abe07557..c70c7058c8 100644--- a/apps/erp/app/modules/sales/sales.utils.ts+++ b/apps/erp/app/modules/sales/sales.utils.ts@@ -431,6 +431,64 @@ export function leaseCommencementPreview(};}+export type SalesOrderInvoiceSummary = {+ invoicedAmount: number;+ paidAmount: number;+ currencyMismatchCount: number;+};++/** Invoiced and paid totals in the order's currency. Invoice totals and+ * applied payments are base amounts; the invoice's rate turns them into its+ * document currency. Voided invoices count for nothing, and an invoice in+ * another currency is counted as a mismatch rather than mixed in. */+export function summarizeSalesOrderInvoices(+ orderCurrency: string | null | undefined,+ invoices: {+ id: string | null;+ invoiceTotal: number | null;+ status: string | null;+ currencyCode: string | null;+ exchangeRate: number | null;+ }[],+ settlements: { targetSalesInvoiceId: string | null; appliedAmount: number }[]+): SalesOrderInvoiceSummary {+ const paidBaseByInvoiceId = new Map<string, number>();+ for (const settlement of settlements) {+ if (!settlement.targetSalesInvoiceId) continue;+ paidBaseByInvoiceId.set(+ settlement.targetSalesInvoiceId,+ (paidBaseByInvoiceId.get(settlement.targetSalesInvoiceId) ?? 0) ++ settlement.appliedAmount+ );+ }++ let invoicedAmount = 0;+ let paidAmount = 0;+ let currencyMismatchCount = 0;++ for (const invoice of invoices) {+ if (invoice.status === "Voided") continue;++ if (+ orderCurrency &&+ invoice.currencyCode &&+ invoice.currencyCode !== orderCurrency+ ) {+ currencyMismatchCount += 1;+ continue;+ }++ invoicedAmount += (invoice.invoiceTotal ?? 0) * (invoice.exchangeRate ?? 1);+ if (invoice.id) {+ paidAmount +=+ (paidBaseByInvoiceId.get(invoice.id) ?? 0) *+ (invoice.exchangeRate ?? 1);+ }+ }++ return { invoicedAmount, paidAmount, currencyMismatchCount };+}+export type RentalEquipmentStatus =| "To Deliver"| "Partially Delivered"diff --git a/apps/erp/app/modules/settings/api-key-cache-bust.test.ts b/apps/erp/app/modules/settings/api-key-cache-bust.test.tsdeleted file mode 100644index 897c2a7c37..0000000000--- a/apps/erp/app/modules/settings/api-key-cache-bust.test.ts+++ /dev/null@@ -1,64 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { describe, expect, it, vi } from "vitest";--// The operations in settings.server.ts reach the glossary, whose `msg` macro-// only runs compiled.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));--const bustApiKeyCache = vi.hoisted(() => vi.fn());-const getCarbonServiceRole = vi.hoisted(() => vi.fn());--// settings.server.ts drags @carbon/ee and the integration hooks in at module load;-// none of that is under test here.-vi.mock("@carbon/auth/auth.server", () => ({ bustApiKeyCache }));-vi.mock("@carbon/auth/client.server", () => ({ getCarbonServiceRole }));-vi.mock("@carbon/ee", async (importOriginal) => ({- ...(await importOriginal<typeof import("@carbon/ee")>()),- getIntegrationConfigById: vi.fn(),- resolveIntegrationSecrets: vi.fn(),- splitSecrets: vi.fn()-}));-vi.mock("@carbon/ee/hooks.server", () => ({- getIntegrationServerHooks: vi.fn()-}));--import { invalidateApiKeyCache } from "./settings.service";--/** Records the `.eq()` filters so the companyId scoping can be asserted. */-function stubServiceRole(row: { keyHash: string } | null) {- const eq = vi.fn();- const chain: Record<string, unknown> = {};- chain.from = vi.fn(() => chain);- chain.select = vi.fn(() => chain);- chain.eq = vi.fn((column: string, value: string) => {- eq(column, value);- return chain;- });- chain.maybeSingle = vi.fn(async () => ({ data: row, error: null }));- getCarbonServiceRole.mockReturnValue(chain);- return eq;-}--describe("invalidateApiKeyCache", () => {- it("busts the cache with the row's keyHash and returns it for a post-delete re-bust", async () => {- bustApiKeyCache.mockClear();- stubServiceRole({ keyHash: "hash-1" });- const hash = await invalidateApiKeyCache("key-1", "company-1");- expect(hash).toBe("hash-1");- expect(bustApiKeyCache).toHaveBeenCalledTimes(1);- expect(bustApiKeyCache).toHaveBeenCalledWith("hash-1");- });-- it("does nothing and returns null when the row is missing", async () => {- bustApiKeyCache.mockClear();- stubServiceRole(null);- const hash = await invalidateApiKeyCache("key-gone", "company-1");- expect(hash).toBeNull();- expect(bustApiKeyCache).not.toHaveBeenCalled();- });-});diff --git a/apps/erp/app/modules/settings/integration-errors.test.ts b/apps/erp/app/modules/settings/integration-errors.test.tsdeleted file mode 100644index 3886eb2446..0000000000--- a/apps/erp/app/modules/settings/integration-errors.test.ts+++ /dev/null@@ -1,49 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { describe, expect, it, vi } from "vitest";--vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray, ...values: unknown[]) =>- strings.reduce(- (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),- ""- )-}));--import {- getIntegrationError,- integrationErrorSearch-} from "./integration-errors";--describe("integration error copy", () => {- it("resolves every code the Onshape callback can send for the panel", () => {- for (const code of [- "write-permission",- "denied",- "invalid-state",- "invalid-response",- "not-configured",- "token-exchange",- "save-failed",- "unexpected"- ] as const) {- expect(getIntegrationError("onshape-v2", code)).toBeDefined();- expect(integrationErrorSearch("onshape-v2", code)).toBe(- `?integration=onshape-v2&error=${code}`- );- }- });-- it("gives the panel the public app's copy", () => {- expect(getIntegrationError("onshape-v2", "not-configured")).toBe(- getIntegrationError("onshape", "not-configured")- );- });-- it("resolves nothing for an unknown integration or code", () => {- expect(getIntegrationError("onshape-v3", "denied")).toBeUndefined();- expect(getIntegrationError("onshape-v2", "no-such-code")).toBeUndefined();- });-});diff --git a/apps/erp/app/modules/settings/settings.integration-patch.test.ts b/apps/erp/app/modules/settings/settings.integration-patch.test.tsdeleted file mode 100644index 68a2dad35b..0000000000--- a/apps/erp/app/modules/settings/settings.integration-patch.test.ts+++ /dev/null@@ -1,81 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { beforeEach, describe, expect, it, vi } from "vitest";--// The operations in settings.server.ts reach the glossary, whose `msg` macro-// only runs compiled.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));--const getCarbonServiceRole = vi.hoisted(() => vi.fn());-const patchRampSettings = vi.hoisted(() => vi.fn());--vi.mock("@carbon/auth/auth.server", () => ({ bustApiKeyCache: vi.fn() }));-vi.mock("@carbon/auth/client.server", () => ({ getCarbonServiceRole }));-vi.mock("@carbon/ee", async (importOriginal) => ({- ...(await importOriginal<typeof import("@carbon/ee")>()),- getIntegrationConfigById: vi.fn(),- resolveIntegrationSecrets: vi.fn(),- splitSecrets: vi.fn(() => ({ config: {}, secrets: {} }))-}));-vi.mock("@carbon/ee/hooks.server", () => ({- getIntegrationServerHooks: vi.fn()-}));-vi.mock("@carbon/ee/ramp.server", () => ({ patchRampSettings }));-vi.mock("@carbon/kv", () => ({- redis: {- del: vi.fn(),- keys: vi.fn(() => Promise.resolve([])),- pipeline: vi.fn()- }-}));--import { upsertCompanyIntegration } from "./settings.service";--describe("Ramp settings persistence", () => {- beforeEach(() => {- vi.clearAllMocks();- getCarbonServiceRole.mockReturnValue({ role: "service" });- patchRampSettings.mockResolvedValue({ id: "ramp", metadata: {} });- });-- it("routes Ramp settings through the atomic key-owned patch", async () => {- const awaitableSingle = Promise.resolve({- data: { id: "ramp", metadata: {} },- error: null- });- const from = vi.fn(() => ({- upsert: vi.fn(() => ({- select: vi.fn(() => ({ single: vi.fn(() => awaitableSingle) }))- }))- }));- const userClient = {- from- };-- const result = await upsertCompanyIntegration(userClient as never, {- id: "ramp",- active: true,- companyId: "company-1",- updatedBy: "user-1",- metadata: {- cardLiabilityAccountId: "account-card",- connectionId: "stale-connection"- }- });-- expect(patchRampSettings).toHaveBeenCalledWith(- { role: "service" },- "company-1",- expect.objectContaining({- active: true,- updatedBy: "user-1"- })- );- expect(from).not.toHaveBeenCalled();- expect(result.error).toBeNull();- });-});diff --git a/apps/erp/app/modules/settings/settings.shipping-default.test.ts b/apps/erp/app/modules/settings/settings.shipping-default.test.tsindex e3a8bbaecf..50fadaa194 100644--- a/apps/erp/app/modules/settings/settings.shipping-default.test.ts+++ b/apps/erp/app/modules/settings/settings.shipping-default.test.ts@@ -29,7 +29,10 @@ const shipping = {parentId: parent.id};const resolve = (- accounts = [parent, shipping],+ accounts: Parameters<typeof resolveShippingDefault>[0]["accounts"] = [+ parent,+ shipping+ ],parentDefaultId: string | null = null) =>resolveShippingDefault({@@ -38,28 +41,18 @@ const resolve = (companyGroupId: "group"});-it("new company seeds a separate Shipping Revenue account under Revenue", () => {- // 4050, not 4040: 4040 is "Customer Payment Discounts" (#1600), which the- // 20260909014032 migration renumbers 7030 into. Claiming 4040 here would- // silently suppress that guarded renumber for every company.- const account = seedAccounts.find(- (a) => String(a.name) === "Shipping Revenue"- );- expect(account).toEqual({- key: "4050",- number: "4050",+it("seeds the shipping default as its own Revenue leaf with an unused number", () => {+ // Sharing a number (4040 is Customer Payment Discounts) would merge two defaults.+ const numbers = seedAccounts.flatMap((a) => (a.number ? [a.number] : []));+ expect(new Set(numbers).size).toBe(numbers.length);+ const key = (accountDefaults as Record<string, string>)+ .salesShippingRevenueAccount;+ expect(seedAccounts.find((a) => a.key === key)).toMatchObject({name: "Shipping Revenue",isGroup: false,parentKey: "revenue",- accountType: "Income",- incomeBalance: "Income Statement",- class: "Revenue",- consolidatedRate: "Average",- createdBy: "system"+ class: "Revenue"});- expect(- (accountDefaults as Record<string, string>).salesShippingRevenueAccount- ).toEqual("4050");});it("existing company group resolves a semantic leaf without assuming number4040", () => {@@ -86,23 +79,17 @@ it("ambiguous or missing semantic defaults fail rather than choosing Sales or nu).toThrow("Shipping Revenue");});-it("inactive, group, cross-group, and incompatible semantic leaves are rejected", () => {- for (const invalid of [- { active: false },- { isGroup: true },- { companyGroupId: "other" },- { class: "Expense" as const },- { incomeBalance: "Balance Sheet" as const },- { accountType: "Other Income" as const },- { consolidatedRate: "Current" as const },- { parentId: "missing" }- ]) {- expect(() =>- resolveShippingDefault({- accounts: [parent, { ...shipping, ...invalid }],- parentDefaultId: null,- companyGroupId: "group"- })- ).toThrow("Shipping Revenue");- }+it.each([+ { active: false },+ { isGroup: true },+ { companyGroupId: "other" },+ { class: "Expense" as const },+ { incomeBalance: "Balance Sheet" as const },+ { accountType: "Other Income" as const },+ { consolidatedRate: "Current" as const },+ { parentId: "missing" }+])("rejects a Shipping Revenue leaf that differs by %o", (invalid) => {+ expect(() => resolve([parent, { ...shipping, ...invalid }])).toThrow(+ "Shipping Revenue"+ );});diff --git a/apps/erp/app/modules/settings/ui/Integrations/InstallModeDialog.test.tsx b/apps/erp/app/modules/settings/ui/Integrations/InstallModeDialog.test.tsxdeleted file mode 100644index 8482cfd492..0000000000--- a/apps/erp/app/modules/settings/ui/Integrations/InstallModeDialog.test.tsx+++ /dev/null@@ -1,94 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import type { ReactNode } from "react";-import { createElement } from "react";-import { renderToStaticMarkup } from "react-dom/server";-import { describe, expect, it, vi } from "vitest";--// `@carbon/content/glossary`'s terms.ts evaluates Lingui `msg` macros at module load,-// which vitest does not transform, and the `@carbon/react` barrel pulls it in.-vi.mock("@carbon/content/glossary", () => ({- getDefinitionText: () => "",- getEntry: () => undefined,- getTermText: () => "",- glossaryEntries: () => [],- hasEntry: () => false,- listEntries: () => [],- lookupEntry: () => undefined,- termSlug: (term: string) => term,- terms: {}-}));--// Only the Modal shell is stubbed — `RadioGroup` / `RadioGroupButton` are the-// REAL components, since what is under test is the markup they produce.-vi.mock("@carbon/react", async (importOriginal) => {- const actual = await importOriginal<typeof import("@carbon/react")>();- const Box = ({ children }: { children?: ReactNode }) =>- createElement("div", null, children);- return {- ...actual,- Button: Box,- Modal: Box,- ModalBody: Box,- ModalContent: Box,- ModalDescription: Box,- ModalFooter: Box,- ModalHeader: Box,- ModalTitle: Box- };-});-vi.mock("@lingui/react/macro", () => ({- Trans: ({ children }: { children: ReactNode }) => children,- useLingui: () => ({- t: (parts: TemplateStringsArray) => parts.join("")- })-}));--import { InstallModeDialog } from "./InstallModeDialog";--const modes = [- { id: "provider", label: "Carbon is my accounting system", description: "…" },- { id: "push-only", label: "Another system posts my ledger", description: "…" }-];--function render() {- return renderToStaticMarkup(- createElement(InstallModeDialog, {- integrationName: "Ramp",- modes,- onClose: () => undefined,- onChoose: () => undefined- })- );-}--describe("InstallModeDialog options", () => {- /**- * These were `<button aria-pressed>` per option: N tab stops, no arrow-key- * navigation, and a screen reader announcing two independent toggle buttons- * rather than one mutually-exclusive choice — on a screen whose whole point is- * that the choice cannot be changed later.- */- it("is one radio group, not a row of toggle buttons", () => {- const html = render();- expect(html).toContain('role="radiogroup"');- expect((html.match(/role="radio"/g) ?? []).length).toBe(modes.length);- expect(html).not.toContain("aria-pressed");- });-- it("marks exactly one option checked", () => {- const html = render();- expect((html.match(/aria-checked="true"/g) ?? []).length).toBe(1);- expect((html.match(/aria-checked="false"/g) ?? []).length).toBe(- modes.length - 1- );- expect((html.match(/data-state="checked"/g) ?? []).length).toBe(1);- });-- it("still renders each mode's label and description", () => {- const html = render();- for (const mode of modes) expect(html).toContain(mode.label);- });-});diff --git a/apps/erp/app/modules/shared/app-shell.server.test.ts b/apps/erp/app/modules/shared/app-shell.server.test.tsdeleted file mode 100644index ac1a449c2a..0000000000--- a/apps/erp/app/modules/shared/app-shell.server.test.ts+++ /dev/null@@ -1,83 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { describe, expect, it, vi } from "vitest";--// shared.server.ts also holds the sales-order/return PDF and email helpers;-// stub their imports so this test loads only what it exercises.-// Its operations' imports reach the glossary, whose `msg` macro only runs compiled.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("@carbon/documents/email", () => ({}));-vi.mock("@carbon/jobs", () => ({}));-vi.mock("~/modules/accounting/accounting.service", () => ({}));-vi.mock("~/modules/sales/sales.service", () => ({}));--vi.mock("~/routes/file+/purchase-return-order+/$id[.]pdf", () => ({}));-vi.mock("~/routes/file+/sales-return-order+/$id[.]pdf", () => ({}));-vi.mock("../documents/documents.service", () => ({}));-vi.mock("@carbon/onboarding/server", () => ({}));-vi.mock("~/modules/settings/settings.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- withLogoUrls: (company: { logoLight: string | null }) => ({- ...company,- logoLight: company.logoLight ? `cdn/${company.logoLight}` : null- })-}));--const { getAppShell } = await import("./shared.service");--type Client = Parameters<typeof getAppShell>[0];-const clientReturning = (result: unknown) => {- const rpc = vi.fn(async () => result);- return { client: { rpc } as unknown as Client, rpc };-};--describe("getAppShell", () => {- it("asks for the caller's company and user, and resolves company logos", async () => {- const { client, rpc } = clientReturning({- data: {- companies: [{ id: "c1", logoLight: "logo.png" }],- groups: ["g1"],- user: { id: "u1" }- },- error: null- });- const shell = await getAppShell(client, "c1", "u1");- expect(rpc).toHaveBeenCalledWith("get_app_shell", {- company_id: "c1",- user_id: "u1"- });- expect(shell.error).toBeNull();- expect(shell.data?.companies).toEqual([- { id: "c1", logoLight: "cdn/logo.png" }- ]);- expect(shell.data?.groups).toEqual(["g1"]);- });-- it("asks with a null company for a user who has none yet", async () => {- const { client, rpc } = clientReturning({- data: { companies: [], groups: [], user: { id: "u1" } },- error: null- });- const shell = await getAppShell(client, undefined, "u1");- // The key must be present: dropped, the API finds no such function.- expect(rpc).toHaveBeenCalledWith("get_app_shell", {- company_id: null,- user_id: "u1"- });- expect(shell.error).toBeNull();- expect(shell.data?.user).toEqual({ id: "u1" });- });-- it("returns the error and no data when the read fails", async () => {- const error = { message: "boom" };- const { client } = clientReturning({ data: null, error });- expect(await getAppShell(client, "c1", "u1")).toEqual({- data: null,- error- });- });-});diff --git a/apps/erp/app/modules/shared/implementation-signals.server.test.ts b/apps/erp/app/modules/shared/implementation-signals.server.test.tsindex 85bb71005e..02b8cf3664 100644--- a/apps/erp/app/modules/shared/implementation-signals.server.test.ts+++ b/apps/erp/app/modules/shared/implementation-signals.server.test.ts@@ -13,38 +13,40 @@ const redis = {};vi.mock("@carbon/kv", () => ({ redis }));-const detect = vi.fn();-vi.mock("@carbon/onboarding/server", () => ({- detectImplementationSignals: detect-}));--// shared.server.ts also holds the sales-order/return PDF and email helpers;-// stub their imports so this test loads only what it exercises.-// Its operations' imports reach the glossary, whose `msg` macro only runs compiled.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("@carbon/documents/email", () => ({}));-vi.mock("@carbon/jobs", () => ({}));-vi.mock("~/modules/accounting/accounting.service", () => ({}));-vi.mock("~/modules/sales/sales.service", () => ({}));+const { getImplementationSignals } = await import("./shared.service");-vi.mock("~/routes/file+/purchase-return-order+/$id[.]pdf", () => ({}));-vi.mock("~/routes/file+/sales-return-order+/$id[.]pdf", () => ({}));-vi.mock("../documents/documents.service", () => ({}));-vi.mock("~/modules/settings/settings.service", () => ({}));+type Client = Parameters<typeof getImplementationSignals>[0];-const { getImplementationSignals } = await import("./shared.service");+// In-memory tables keyed by companyId; records which tables were probed.+function fakeClient(rows: Record<string, string[]>) {+ const probed: string[] = [];+ const client = {+ from: (table: string) => ({+ select: () => ({+ eq: (_column: string, companyId: string) => ({+ limit: async () => {+ probed.push(table);+ return {+ data: (rows[table] ?? [])+ .filter((owner) => owner === companyId)+ .map((_, i) => ({ id: `${table}-${i}` }))+ };+ }+ })+ })+ })+ } as unknown as Client;+ return { client, probed };+}-const client = {} as Parameters<typeof getImplementationSignals>[0];-const signals = (overrides: Record<string, boolean>) => ({+const none = {hasItems: false,hasMakeMethod: false,hasJob: false,hasSalesOrder: false,- hasTrackedEntity: false,- ...overrides-});+ hasTrackedEntity: false+};+const allTables = ["item", "makeMethod", "job", "salesOrder", "trackedEntity"];beforeEach(() => {store.clear();@@ -52,37 +54,42 @@ beforeEach(() => {});describe("getImplementationSignals", () => {- it("remembers the signals seen true and passes them as known next time", async () => {- detect.mockResolvedValueOnce(signals({ hasItems: true, hasJob: true }));- await getImplementationSignals(client, "c1");- expect(detect).toHaveBeenLastCalledWith(client, "c1", {});+ it("skips the probe for a signal already seen true", async () => {+ const first = fakeClient({ item: ["c1"], job: ["c1"] });+ await expect(getImplementationSignals(first.client, "c1")).resolves.toEqual(+ { ...none, hasItems: true, hasJob: true }+ );+ expect(first.probed.sort()).toEqual([...allTables].sort());- detect.mockResolvedValueOnce(signals({ hasItems: true, hasJob: true }));- await getImplementationSignals(client, "c1");- expect(detect).toHaveBeenLastCalledWith(client, "c1", {- hasItems: true,- hasJob: true- });- // Nothing new was seen the second time, so nothing is rewritten.- expect(redis.set).toHaveBeenCalledTimes(1);+ const second = fakeClient({ item: ["c1"], job: ["c1"] });+ await expect(+ getImplementationSignals(second.client, "c1")+ ).resolves.toEqual({ ...none, hasItems: true, hasJob: true });+ expect(second.probed.sort()).toEqual(+ ["makeMethod", "salesOrder", "trackedEntity"].sort()+ );});it("keeps one company's signals away from another's", async () => {- detect.mockResolvedValueOnce(signals({ hasItems: true }));- await getImplementationSignals(client, "c1");+ const data = { item: ["c1"] };+ await getImplementationSignals(fakeClient(data).client, "c1");- detect.mockResolvedValueOnce(signals({}));- await getImplementationSignals(client, "c2");- expect(detect).toHaveBeenLastCalledWith(client, "c2", {});+ const other = fakeClient(data);+ await expect(getImplementationSignals(other.client, "c2")).resolves.toEqual(+ none+ );+ expect(other.probed).toContain("item");});it("probes everything when Redis is unavailable", async () => {redis.get.mockRejectedValueOnce(new Error("down"));redis.set.mockRejectedValueOnce(new Error("down"));- detect.mockResolvedValueOnce(signals({ hasItems: true }));- await expect(getImplementationSignals(client, "c1")).resolves.toEqual(- signals({ hasItems: true })- );- expect(detect).toHaveBeenLastCalledWith(client, "c1", {});+ const { client, probed } = fakeClient({ item: ["c1"] });++ await expect(getImplementationSignals(client, "c1")).resolves.toEqual({+ ...none,+ hasItems: true+ });+ expect(probed).toHaveLength(allTables.length);});});diff --git a/apps/erp/app/modules/shared/sort-order.test.ts b/apps/erp/app/modules/shared/sort-order.test.tsindex 55d4e61351..d1346d61c8 100644--- a/apps/erp/app/modules/shared/sort-order.test.ts+++ b/apps/erp/app/modules/shared/sort-order.test.ts@@ -2,183 +2,33 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import type { Kysely, KyselyDatabase } from "@carbon/database/client";-import {- type CompiledQuery,- type DatabaseConnection,- DummyDriver,- Kysely as KyselyClient,- PostgresAdapter,- PostgresIntrospector,- PostgresQueryCompiler,- type QueryResult-} from "kysely";import { describe, expect, it } from "vitest";-import {- buildSortOrderUpdate,- parseSortOrderUpdates,- updateSortOrder-} from "./sort-order";--// The boundary here is the Postgres wire: a driver that records what Kysely-// sends and answers with the rows the database would have returned. Everything-// above it — SQL building, the transaction, the row-count check — runs real.-class RecordingDriver extends DummyDriver {- readonly sent: string[] = [];- constructor(private readonly returnedIds: string[]) {- super();- }- override async acquireConnection(): Promise<DatabaseConnection> {- return {- executeQuery: async <R>(- query: CompiledQuery- ): Promise<QueryResult<R>> => {- this.sent.push(query.sql);- return { rows: this.returnedIds.map((id) => ({ id })) as R[] };- },- // biome-ignore lint/correctness/useYield: never streamed- streamQuery: async function* () {- throw new Error("not streamed");- }- };- }- override async beginTransaction() {- this.sent.push("BEGIN");- }- override async commitTransaction() {- this.sent.push("COMMIT");- }- override async rollbackTransaction() {- this.sent.push("ROLLBACK");- }-}--function database(returnedIds: string[] = []) {- const driver = new RecordingDriver(returnedIds);- const db = new KyselyClient<KyselyDatabase>({- dialect: {- createAdapter: () => new PostgresAdapter(),- createDriver: () => driver,- createIntrospector: (k) => new PostgresIntrospector(k),- createQueryCompiler: () => new PostgresQueryCompiler()- }- }) as unknown as Kysely<KyselyDatabase>;- return { db, driver };-}--const updates = [- { id: "ql1", sortOrder: 2 },- { id: "ql2", sortOrder: 1 }-];--describe("buildSortOrderUpdate", () => {- it("scopes one UPDATE … FROM (VALUES …) to the company and the parent document", () => {- const { db } = database();- const compiled = buildSortOrderUpdate({- table: "quoteLine",- column: "sortOrder",- companyId: "c1",- userId: "u1",- parent: { column: "quoteId", id: "q1" },- updates,- updatedAt: "2026-09-26T00:00:00.000Z"- }).compile(db);-- expect(compiled.sql).toBe(- 'UPDATE "quoteLine" AS t SET "sortOrder" = v."sortOrder", "updatedBy" = $1, "updatedAt" = $2 FROM (VALUES ($3::text, $4::numeric), ($5::text, $6::numeric)) AS v("id", "sortOrder") WHERE t."id" = v."id" AND t."companyId" = $7 AND "t"."quoteId" = $8 RETURNING t."id"'- );- expect(compiled.parameters).toEqual([- "u1",- "2026-09-26T00:00:00.000Z",- "ql1",- 2,- "ql2",- 1,- "c1",- "q1"- ]);- });-- it("writes an `order` sort column and scopes a one-hop parent through its table", () => {- const { db } = database();- const compiled = buildSortOrderUpdate({- table: "assemblyInstructionStepMaterial",- column: "sortOrder",- companyId: "c1",- userId: "u1",- parent: {- column: "stepId",- via: {- table: "assemblyInstructionStep",- column: "assemblyInstructionId",- id: "ai1"- }- },- updates: [{ id: "m1", sortOrder: 1 }],- updatedAt: "2026-09-26T00:00:00.000Z"- }).compile(db);-- expect(compiled.sql).toContain(- 'AND "t"."stepId" IN (SELECT p."id" FROM "assemblyInstructionStep" AS p WHERE "p"."assemblyInstructionId" = $6 AND p."companyId" = $7)'- );- // The subquery is tenant-scoped too, with the same companyId.- expect(compiled.parameters.slice(4)).toEqual(["c1", "ai1", "c1"]);-- const rfq = buildSortOrderUpdate({- table: "salesRfqLine",- column: "order",- companyId: "c1",- userId: "u1",- parent: { column: "salesRfqId", id: "rfq1" },- updates: [{ id: "l1", sortOrder: 1 }],- updatedAt: "2026-09-26T00:00:00.000Z"- }).compile(db);- expect(rfq.sql).toContain('UPDATE "salesRfqLine" AS t SET "order" = ');- expect(rfq.sql).toContain('AND "t"."salesRfqId" = $6');- });-});+import { parseSortOrderUpdates, updateSortOrder } from "./sort-order";describe("updateSortOrder", () => {- const args = {+ // Both guards return before any statement, so no database is needed.+ const base = {table: "quoteLine" as const,column: "sortOrder" as const,companyId: "c1",userId: "u1",parent: { column: "quoteId" as const, id: "q1" },- updates+ updates: [{ id: "ql1", sortOrder: 1 }]};- it("issues exactly one statement and commits when every row is on the document", async () => {- const { db, driver } = database(["ql1", "ql2"]);- await updateSortOrder(db, args);- expect(driver.sent).toHaveLength(3);- expect(driver.sent[0]).toBe("BEGIN");- expect(driver.sent[1]).toMatch(/^UPDATE "quoteLine" AS t /);- expect(driver.sent[2]).toBe("COMMIT");- });-- it("rolls the whole reorder back when a row is outside the company or document", async () => {- // Postgres matched only one of the two ids — the other belongs to another- // quote (or company), so the predicates filtered it out.- const { db, driver } = database(["ql1"]);- await expect(updateSortOrder(db, args)).rejects.toThrow(- "quoteLine: 1 of 2 rows are not on this document"- );- expect(driver.sent).toEqual(["BEGIN", expect.any(String), "ROLLBACK"]);- });-- it("refuses an empty parent id instead of issuing an unscoped update", async () => {- const { db, driver } = database(["ql1", "ql2"]);+ it("refuses an empty parent id instead of issuing an update scoped to no document", async () => {await expect(- updateSortOrder(db, { ...args, parent: { column: "quoteId", id: "" } })+ updateSortOrder(null as never, {+ ...base,+ parent: { column: "quoteId", id: "" }+ })).rejects.toThrow("quoteLine: missing parent id");- expect(driver.sent).toEqual([]);});- it("sends nothing for an empty reorder", async () => {- const { db, driver } = database();- await updateSortOrder(db, { ...args, updates: [] });- expect(driver.sent).toEqual([]);+ it("does nothing for an empty reorder", async () => {+ await expect(+ updateSortOrder(null as never, { ...base, updates: [] })+ ).resolves.toBeUndefined();});});diff --git a/apps/erp/app/modules/shared/sort-order.ts b/apps/erp/app/modules/shared/sort-order.tsindex c13307bb9b..615bcefd9c 100644--- a/apps/erp/app/modules/shared/sort-order.ts+++ b/apps/erp/app/modules/shared/sort-order.ts@@ -84,11 +84,8 @@ export type UpdateSortOrderArgs<afterUpdate?: (trx: Transaction<KyselyDatabase>) => Promise<void>;};-/**- * The single statement behind `updateSortOrder`, exported so its SQL can be- * pinned by compiling it (no database needed).- */-export function buildSortOrderUpdate<+/** The single statement behind `updateSortOrder`. */+function buildSortOrderUpdate<T extends SortableTable,P extends TenantTable = TenantTable>(args: UpdateSortOrderArgs<T, P> & { updatedAt: string }) {diff --git a/apps/erp/app/modules/users/users.server.test.ts b/apps/erp/app/modules/users/users.server.test.tsindex feb944350b..72185e8ef6 100644--- a/apps/erp/app/modules/users/users.server.test.ts+++ b/apps/erp/app/modules/users/users.server.test.ts@@ -2,581 +2,63 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import type { CompiledQuery, DatabaseConnection, Driver } from "kysely";+import { createServiceContext } from "@carbon/api/service-fn.server";+import { describe, expect, it } from "vitest";import {- Kysely,- PostgresAdapter,- PostgresIntrospector,- PostgresQueryCompiler-} from "kysely";-import { beforeEach, describe, expect, it, vi } from "vitest";--// users.server pulls in auth, SSO, Redis and two module barrels at import-// time. Everything createEmployeeAccount and acceptInvite do not exercise is-// stubbed; the parts they do are recorded so each test can assert on which-// writes ran and through which client.-const mocks = vi.hoisted(() => ({- deactivateEmployee: vi.fn(),- deactivateUser: vi.fn(),- setEmployeePin: vi.fn(),- deleteAuthAccount: vi.fn(),- getUserClaims: vi.fn(),- insertEmployeeJob: vi.fn(),- mergeInvitePermissions: vi.fn(() => ({})),- serviceRoleWrites: [] as { table: string; op: string; payload: unknown }[]-}));--// hasPermission stays real: the re-add path's permission check is under test.-// It is read from its source file because the package root pulls in Lingui-// macros that only run inside the app build.-vi.mock("@carbon/auth", async () => ({- ...(await vi.importActual<object>("@carbon/auth")),- CarbonEdition: "test",- CONTROLLED_ENVIRONMENT: false,- error: vi.fn(),- success: vi.fn(),- hasPermission: (- await vi.importActual<- typeof import("../../../../../packages/auth/src/services/users")- >("../../../../../packages/auth/src/services/users")- ).hasPermission-}));--vi.mock("@carbon/auth/auth.server", () => ({- deleteAuthAccount: mocks.deleteAuthAccount-}));--vi.mock("@carbon/auth/auth-events.server", () => ({- logPermissionChange: vi.fn()-}));--vi.mock("@carbon/auth/client.server", () => ({- getCarbonServiceRole: () => ({- from: (table: string) => {- const chain: Record<string, unknown> = {- select: () => chain,- eq: () => chain,- single: () =>- Promise.resolve(- table === "user"- ? { data: { id: USER, email: EMAIL }, error: null }- : { data: null, error: null }- ),- // The employee type and location ownership checks: both belong to- // the company in every test here.- maybeSingle: () =>- Promise.resolve(- table === "employeeType" || table === "location"- ? { data: { id: table }, error: null }- : { data: null, error: null }- ),- upsert: (payload: unknown) => {- mocks.serviceRoleWrites.push({ table, op: "upsert", payload });- return chain;- }- };- return chain;- },- auth: {- admin: { getUserById: () => Promise.resolve({ error: null }) }- }- })-}));--vi.mock("@carbon/auth/session.server", () => ({- flash: vi.fn(),- requireAuthSession: vi.fn()-}));--vi.mock("@carbon/auth/users.server", () => ({- deactivateCustomer: vi.fn(),- deactivateEmployee: mocks.deactivateEmployee,- deactivateSupplier: vi.fn(),- deactivateUser: mocks.deactivateUser,- getUserClaims: mocks.getUserClaims-}));--vi.mock("@carbon/ee/console.server", () => ({- generateConsolePin: () => "4321",- setEmployeePin: mocks.setEmployeePin-}));--vi.mock("@carbon/kv", () => ({- redis: { del: vi.fn(), get: vi.fn(), set: vi.fn() }-}));--vi.mock("@carbon/ee/sso.server", () => ({- emailDomain: vi.fn(),- getSsoConnection: vi.fn(),- getSsoConnectionByDomain: vi.fn(),- isSsoEnabled: () => false,- mergeInvitePermissions: mocks.mergeInvitePermissions,- seedSsoIdentityForUser: vi.fn(),- uncoveredSsoDomainError: vi.fn()-}));--vi.mock("@carbon/logger", () => ({- getLogger: () => ({- debug: vi.fn(),- error: vi.fn(),- info: vi.fn(),- warn: vi.fn()- })-}));--vi.mock("~/modules/purchasing/purchasing.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- getSupplierContact: vi.fn()-}));-vi.mock("~/modules/sales/sales.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- getCustomerContact: vi.fn()-}));-vi.mock("~/utils/path", () => ({ path: { to: {} } }));-vi.mock("../people/people.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- insertEmployeeJob: mocks.insertEmployeeJob-}));--const { certifyItarEntity, deactivateUsers, resetConsoleOperatorPin } =- await import("./users.server");-const { acceptInvite, createEmployeeAccount } = await import("./users.service");-const { createServiceContext } = await import("@carbon/api/service-fn.server");+ certifyItarEntity,+ deactivateUsers,+ resetConsoleOperatorPin+} from "./users.server";+import {+ canReAddDeactivatedEmployee,+ makePermissionsFromEmployeeType+} from "./users.service";-const USER = "usr_1";const COMPANY = "cmp_1";-const EMAIL = "[email protected]";-const NEW_TYPE = "et_new";--const ACCOUNT = {- email: EMAIL,- firstName: "Pat",- lastName: "Doe",- employeeType: NEW_TYPE,- locationId: "loc_1",- companyId: COMPANY,- createdBy: "usr_admin"-};--type Statement = { sql: string; parameters: readonly unknown[] };--/**- * Drives Kysely's real Postgres compiler through a fake driver, so the tests- * see the SQL the transaction would send and whether it committed or rolled- * back. `respond` answers each statement, or throws to simulate a failed write.- * Nothing reaches a database: a rollback here proves Kysely issued one and- * stopped executing, not what Postgres did with it.- */-function makeDb(respond: (statement: Statement) => unknown[]) {- const statements: Statement[] = [];- const transactions = { begin: 0, commit: 0, rollback: 0 };- const connection: DatabaseConnection = {- async executeQuery(query: CompiledQuery) {- const statement = { sql: query.sql, parameters: query.parameters };- statements.push(statement);- return { rows: respond(statement) } as never;- },- async *streamQuery() {}- };- const driver: Driver = {- async init() {},- async acquireConnection() {- return connection;- },- async beginTransaction() {- transactions.begin++;- },- async commitTransaction() {- transactions.commit++;- },- async rollbackTransaction() {- transactions.rollback++;- },- async releaseConnection() {},- async destroy() {}- };- const db = new Kysely<Record<string, never>>({- dialect: {- createAdapter: () => new PostgresAdapter(),- createDriver: () => driver,- createIntrospector: (kysely) => new PostgresIntrospector(kysely),- createQueryCompiler: () => new PostgresQueryCompiler()- }- });- return { db, statements, transactions };-}--/** The caller's RLS client: answers the pre-read and records inserts. */-function makeClient(- existingEmployee: { id: string; active: boolean } | null,- readError: { message: string } | null = null-) {- const writes: { table: string; op: string; payload: unknown }[] = [];- const permissionReads: string[] = [];- const client = {- from: (table: string) => {- const chain: Record<string, unknown> = {- select: () => chain,- // An employee type's permissions: the one read that ends at `.eq`.- eq: (_column: string, value: string) => {- if (table !== "employeeTypePermission") return chain;- permissionReads.push(value);- return Promise.resolve({- data: EMPLOYEE_TYPE_PERMISSIONS,- error: null- });- },- maybeSingle: () =>- Promise.resolve(- readError- ? { data: null, error: readError }- : { data: existingEmployee, error: null }- ),- single: () => Promise.resolve({ data: {}, error: null }),- insert: (payload: unknown) => {- writes.push({ table, op: "insert", payload });- return chain;- }- };- return chain;- }- };- return { client: client as never, writes, permissionReads };-}--const deactivated = { id: USER, active: false };--function answer(lockedRow: { active: boolean } | null) {- return ({ sql }: Statement) =>- sql.startsWith('select "active" from "employee"') && lockedRow- ? [lockedRow]- : [];-}--const EMPLOYEE_TYPE_PERMISSIONS = [- {- module: "Sales",- view: [COMPANY],- create: [COMPANY],- update: [],- delete: []- }-];--beforeEach(() => {- vi.clearAllMocks();- mocks.serviceRoleWrites.length = 0;- mocks.insertEmployeeJob.mockResolvedValue({ data: {}, error: null });- // The inviter may do everything a first-time add needs.- mocks.getUserClaims.mockResolvedValue({- role: "employee",- permissions: {- users: { view: [], create: [COMPANY], update: [COMPANY], delete: [] },- people: { view: [], create: [COMPANY], update: [], delete: [] }- }- });-});--describe("createEmployeeAccount — re-adding a deactivated employee", () => {- it("writes the employee type, placement and invite in one committed transaction", async () => {- const { db, statements, transactions } = makeDb(answer(deactivated));- const { client, writes, permissionReads } = makeClient(deactivated);-- const result = await createEmployeeAccount(client, db as never, ACCOUNT);-- expect(result).toMatchObject({ success: true, userId: USER });- if (!result.success) throw new Error(result.message);- expect(transactions).toEqual({ begin: 1, commit: 1, rollback: 0 });-- const [lock, employee, job, invite] = statements;- expect(statements).toHaveLength(4);- expect(lock.sql).toMatch(/from "employee" .* for update$/);- expect(lock.parameters).toEqual([USER, COMPANY]);- expect(employee.sql).toMatch(/^update "employee" set "employeeTypeId" =/);- expect(employee.parameters).toEqual([NEW_TYPE, USER, COMPANY]);- expect(job.sql).toMatch(- /^insert into "employeeJob" .* on conflict \("id", "companyId"\) do update set "locationId" =/- );- expect(invite.sql).toMatch(- /^insert into "invite" .* on conflict \("email", "companyId"\) do update set/- );- expect(invite.sql).toMatch(/"acceptedAt" = \$\d+, "revokedAt" = \$\d+$/);-- // The invite carries the permissions of the SAME type written to the- // employee row, under the code returned to the caller.- const permissions = JSON.parse(invite.parameters[1] as string);- expect(permissions).toEqual({- sales_view: [COMPANY],- sales_create: [COMPANY],- sales_update: [],- sales_delete: []- });- expect(invite.parameters).toContain(result.code);- expect(permissionReads).toEqual([NEW_TYPE]);-- // Nothing went through the non-transactional clients.- expect(writes).toEqual([]);- expect(mocks.serviceRoleWrites).toEqual([]);- expect(mocks.insertEmployeeJob).not.toHaveBeenCalled();- });-- it("rolls back and writes nothing further when the employee write fails", async () => {- const { db, statements, transactions } = makeDb((statement) => {- if (statement.sql.startsWith('update "employee"')) {- throw new Error("employee write failed");- }- return answer(deactivated)(statement);- });- const { client } = makeClient(deactivated);-- const result = await createEmployeeAccount(client, db as never, ACCOUNT);-- expect(result).toEqual({- success: false,- message: "employee write failed"- });- expect(transactions).toEqual({ begin: 1, commit: 0, rollback: 1 });- // No placement or invite statement ran after the failure, so no- // redeemable invite can outlive it.- expect(statements.map((s) => s.sql.split(" ")[0])).toEqual([- "select",- "update"- ]);- expect(mocks.serviceRoleWrites).toEqual([]);- // A rollback needs no compensation, and deactivating here would strip- // whatever this person still holds in the company.- expect(mocks.deactivateEmployee).not.toHaveBeenCalled();- expect(mocks.deleteAuthAccount).not.toHaveBeenCalled();- });-- it("rolls back the employee and placement writes when the invite write fails", async () => {- const { db, statements, transactions } = makeDb((statement) => {- if (statement.sql.startsWith('insert into "invite"')) {- throw new Error("invite write failed");- }- return answer(deactivated)(statement);- });- const { client } = makeClient(deactivated);-- const result = await createEmployeeAccount(client, db as never, ACCOUNT);-- expect(result).toEqual({ success: false, message: "invite write failed" });- expect(statements).toHaveLength(4);- expect(transactions).toEqual({ begin: 1, commit: 0, rollback: 1 });- expect(mocks.deactivateEmployee).not.toHaveBeenCalled();- expect(mocks.deleteAuthAccount).not.toHaveBeenCalled();- });- it("refuses under the lock when the employee was activated since the pre-read", async () => {- const { db, statements, transactions } = makeDb(answer({ active: true }));- const { client } = makeClient(deactivated);-- const result = await createEmployeeAccount(client, db as never, ACCOUNT);-- expect(result).toEqual({- success: false,- message: "This user is already an employee in this company"- });- expect(statements).toHaveLength(1);- expect(transactions).toEqual({ begin: 1, commit: 0, rollback: 1 });- });-- it("refuses rather than inserting when the row disappeared since the pre-read", async () => {- const { db, statements, transactions } = makeDb(answer(null));- const { client } = makeClient(deactivated);-- const result = await createEmployeeAccount(client, db as never, ACCOUNT);-- expect(result.success).toBe(false);- // Only the lock ran: a first-time employee insert never happens outside- // the caller's RLS client.- expect(statements).toHaveLength(1);- expect(transactions.rollback).toBe(1);+describe("canReAddDeactivatedEmployee", () => {+ const grant = (users: string[], people: string[]) => ({+ users: { view: [], create: [COMPANY], update: users, delete: [] },+ people: { view: [], create: people, update: [], delete: [] }});-});--describe("createEmployeeAccount — re-add guards", () => {- it("restarts the reused invite's createdAt, which the controlled-environment expiry counts from", async () => {- const { db, statements } = makeDb(answer(deactivated));- const { client } = makeClient(deactivated);-- const result = await createEmployeeAccount(client, db as never, ACCOUNT);-- expect(result.success).toBe(true);- const invite = statements.find((s) =>- s.sql.startsWith('insert into "invite"')- );- const onConflict = invite?.sql.split(" do update set ")[1] ?? "";- // The reused row is the original invite, usually long since accepted.- expect(onConflict).toMatch(/"createdAt" = \$\d+/);- expect(onConflict).toMatch(/"updatedBy" = \$\d+/);- });-- it("refuses an inviter who could not add the person the first time", async () => {- // users_create only: a first-time add's RLS inserts need users_update and- // people_create, so the RLS-bypassing re-add must not succeed either.- mocks.getUserClaims.mockResolvedValue({- role: "employee",- permissions: {- users: { view: [], create: [COMPANY], update: [], delete: [] },- people: { view: [], create: [COMPANY], update: [], delete: [] }- }- });- const { db, transactions } = makeDb(answer(deactivated));- const { client, writes } = makeClient(deactivated);- const result = await createEmployeeAccount(client, db as never, ACCOUNT);-- expect(result).toEqual({- success: false,- message:- "Re-adding a deactivated employee requires the Users update and People create permissions"- });- expect(mocks.getUserClaims).toHaveBeenCalledWith(- ACCOUNT.createdBy,- COMPANY- );- expect(transactions.begin).toBe(0);- expect(writes).toEqual([]);- expect(mocks.serviceRoleWrites).toEqual([]);+ it("allows an inviter with users update and people create", () => {+ expect(+ canReAddDeactivatedEmployee(grant([COMPANY], [COMPANY]), COMPANY)+ ).toBe(true);});-});-describe("createEmployeeAccount — the existing-employee read fails", () => {- it("returns the error before any write path starts", async () => {- const { db, transactions } = makeDb(() => []);- const { client, writes } = makeClient(null, { message: "read failed" });-- const result = await createEmployeeAccount(client, db as never, ACCOUNT);-- expect(result).toEqual({ success: false, message: "read failed" });- // Neither the re-invite transaction nor the first-time writes ran, so no- // redeemable invite was written beside a failed employee insert.- expect(transactions.begin).toBe(0);- expect(writes).toEqual([]);- expect(mocks.serviceRoleWrites).toEqual([]);- expect(mocks.insertEmployeeJob).not.toHaveBeenCalled();+ it.each([+ ["users create alone", grant([], [])],+ ["no people create", grant([COMPANY], [])],+ ["no users update", grant([], [COMPANY])],+ ["both, for another company", grant(["cmp_2"], ["cmp_2"])],+ ["unreadable claims", null]+ ])("refuses an inviter with %s", (_label, permissions) => {+ expect(canReAddDeactivatedEmployee(permissions, COMPANY)).toBe(false);});});-describe("createEmployeeAccount — first time in the company", () => {- it("keeps writing through the caller's RLS client, outside any transaction", async () => {- const { db, transactions } = makeDb(() => []);- const { client, writes } = makeClient(null);-- const result = await createEmployeeAccount(client, db as never, ACCOUNT);-- expect(result).toMatchObject({ success: true, userId: USER });- expect(transactions.begin).toBe(0);- expect(writes).toEqual([- {- table: "employee",- op: "insert",- payload: [+describe("makePermissionsFromEmployeeType", () => {+ it("keys each module's grants by module_action", () => {+ expect(+ makePermissionsFromEmployeeType({+ data: [{- id: USER,- employeeTypeId: NEW_TYPE,- active: false,- companyId: COMPANY+ module: "Sales",+ view: [COMPANY],+ create: [COMPANY],+ update: [],+ delete: []}]- }- ]);- expect(mocks.insertEmployeeJob).toHaveBeenCalledWith(client, {- id: USER,- companyId: COMPANY,- locationId: "loc_1"- });- expect(mocks.serviceRoleWrites).toMatchObject([- { table: "invite", op: "upsert" }- ]);- });-});--describe("acceptInvite", () => {- const INVITE = {- id: "inv_1",- code: "code_1",- email: EMAIL,- companyId: COMPANY,- role: "employee",- permissions: {},- createdAt: "2026-10-01T00:00:00Z",- acceptedAt: null,- revokedAt: null- };-- /** The service-role client acceptInvite looks the invite up with. */- function makeInviteLookup() {- const chain: Record<string, unknown> = {- select: () => chain,- eq: () => chain,- is: () => chain,- single: () => Promise.resolve({ data: INVITE, error: null })- };- return { from: () => chain } as never;- }-- /** `acceptedRow` is what the guarded invite update returns: none = lost. */- function answerAccept(acceptedRow: typeof INVITE | null) {- return ({ sql }: Statement) => {- if (sql.startsWith('select "id", "employeeTypeId" from "employee"')) {- return [{ id: USER, employeeTypeId: "et_1" }];- }- if (sql.startsWith('select "id" from "user"')) return [{ id: USER }];- if (sql.startsWith('update "invite"')) {- return acceptedRow ? [acceptedRow] : [];- }- return [];- };- }-- it("locks the user row before reading the permissions it merges into", async () => {- const { db, statements, transactions } = makeDb(answerAccept(INVITE));-- const result = await acceptInvite(- makeInviteLookup(),- db as never,- INVITE.code,- );-- expect(result.error).toBeNull();- expect(transactions).toEqual({ begin: 1, commit: 1, rollback: 0 });- const lock = statements.findIndex((s) =>- /^select "id" from "user" where "id" = \$1 for no key update$/.test(s.sql)- );- const read = statements.findIndex((s) =>- s.sql.startsWith('select "permissions" from "userPermission"')- );- expect(lock).toBeGreaterThanOrEqual(0);- expect(statements[lock].parameters).toEqual([USER]);- expect(lock).toBeLessThan(read);- });-- it("does not accept an invite revoked after it was looked up", async () => {- const { db, statements, transactions } = makeDb(answerAccept(null));-- const result = await acceptInvite(- makeInviteLookup(),- db as never,- INVITE.code,- );-- expect(result).toEqual({- data: null,- error: {- message: "This invite has already been accepted or was revoked."- }+ })+ ).toEqual({+ sales_view: [COMPANY],+ sales_create: [COMPANY],+ sales_update: [],+ sales_delete: []});- // The activation, membership and permission writes before the guard are- // rolled back with it.- expect(transactions).toEqual({ begin: 1, commit: 0, rollback: 1 });- const update = statements.find((s) => s.sql.startsWith('update "invite"'));- expect(update?.sql).toMatch(- /"companyId" = \$\d+ and "acceptedAt" is null and "revokedAt" is null/- );});});@@ -584,87 +66,51 @@ const unreachable = () => {throw new Error("must not be reached");};-/** An operation's context for a user holding `permissions` in COMPANY. */-function operationContext(+/** A user in COMPANY holding `permissions`; the caller client returns `user`. */+function userContext(permissions: Record<string, Record<string, string[]>>,- { user = null as Record<string, unknown> | null } = {}+ user: Record<string, unknown> | null = null) {- const caller = {- from: () => {- const chain: Record<string, unknown> = {- select: () => chain,- eq: () => chain,- single: async () =>- user ? { data: user, error: null } : { data: null, error: {} }- };- return chain;- }+ const chain: Record<string, unknown> = {+ select: () => chain,+ eq: () => chain,+ single: async () =>+ user ? { data: user, error: null } : { data: null, error: {} }};return createServiceContext({actor: { type: "user", userId: "usr_admin", permissions },company: { id: COMPANY, groupId: "grp_1" },- caller: caller as never,+ caller: { from: () => chain } as never,system: unreachable as never,- pg: (() => ({})) as never,+ pg: unreachable as never,kv: unreachable as never});}-describe("resetConsoleOperatorPin", () => {- beforeEach(() => mocks.setEmployeePin.mockReset());-- const usersUpdate = { users: { update: [COMPANY] } };-- it("resets a console operator's PIN with users update alone", async () => {- const result = await resetConsoleOperatorPin(- operationContext(usersUpdate, {- user: { id: USER, isConsoleOperator: true }- }),- { operatorId: USER }- );- expect(result.data).toEqual({ pin: "4321" });- expect(mocks.setEmployeePin).toHaveBeenCalledOnce();- });-- // A PIN pins in as that person anywhere on the floor: for anyone who is- // not a console operator, it takes settings update too.- it("refuses another person's PIN without settings update", async () => {+describe("operation guards", () => {+ // A PIN signs in as that person anywhere on the floor, so anyone but a+ // console operator needs settings update as well.+ it("refuses resetting a non-operator's PIN with users update alone", async () => {const result = await resetConsoleOperatorPin(- operationContext(usersUpdate, {- user: { id: USER, isConsoleOperator: false }- }),- { operatorId: USER }- );- expect(result.error?.category).toBe("forbidden");- expect(mocks.setEmployeePin).not.toHaveBeenCalled();- });-- it("resets another person's PIN with settings update", async () => {- const result = await resetConsoleOperatorPin(- operationContext(- { ...usersUpdate, settings: { update: [COMPANY] } },- { user: { id: USER, isConsoleOperator: false } }+ userContext(+ { users: { update: [COMPANY] } },+ { id: "usr_1", isConsoleOperator: false }),- { operatorId: USER }+ { operatorId: "usr_1" });- expect(result.data).toEqual({ pin: "4321" });+ expect(result.error?.category).toBe("forbidden");});-});-describe("deactivateUsers", () => {- it("refuses the caller's own account", async () => {+ it("refuses deactivating the caller's own account", async () => {const result = await deactivateUsers(- operationContext({ users: { delete: [COMPANY] } }),- { userIds: [USER, "usr_admin"] }+ userContext({ users: { delete: [COMPANY] } }),+ { userIds: ["usr_1", "usr_admin"] });expect(result.error?.category).toBe("rule");- expect(mocks.deactivateUser).not.toHaveBeenCalled();});-});-describe("certifyItarEntity", () => {// An API key authenticates as the key, not a person: there is no signer.- it("refuses an API key", async () => {+ it("refuses an API key signing the ITAR Rider", async () => {const ctx = createServiceContext({actor: {type: "apiKey",diff --git a/apps/erp/app/modules/users/users.service.ts b/apps/erp/app/modules/users/users.service.tsindex da818b2ed4..5c17f7bf53 100644--- a/apps/erp/app/modules/users/users.service.ts+++ b/apps/erp/app/modules/users/users.service.ts@@ -1363,10 +1363,7 @@ export async function createEmployeeAccount(return null;});- if (- !hasPermission(claims?.permissions, "users", "update", companyId) ||- !hasPermission(claims?.permissions, "people", "create", companyId)- ) {+ if (!canReAddDeactivatedEmployee(claims?.permissions, companyId)) {logger.error("Re-adding a deactivated employee was refused", {companyId,userId,@@ -2163,7 +2160,21 @@ export async function convertConsoleOperatorToUser(return { success: true };}-function makePermissionsFromEmployeeType({+/** Re-adding a deactivated employee writes outside RLS, so the inviter needs+ * what a first-time add's RLS inserts need: users update and people create. */+export function canReAddDeactivatedEmployee(+ permissions: Parameters<typeof hasPermission>[0],+ companyId: string+): boolean {+ return (+ hasPermission(permissions, "users", "update", companyId) &&+ hasPermission(permissions, "people", "create", companyId)+ );+}++/** An employee type's permission rows as invite permissions, keyed+ * `module_action`. */+export function makePermissionsFromEmployeeType({data}: {data: {diff --git a/apps/erp/app/modules/workflows/ui/Builder/store.test.ts b/apps/erp/app/modules/workflows/ui/Builder/store.test.tsdeleted file mode 100644index d97291b06b..0000000000--- a/apps/erp/app/modules/workflows/ui/Builder/store.test.ts+++ /dev/null@@ -1,48 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { describe, expect, it } from "vitest";-import type { BuilderNode } from "../../types";-import { createNode } from "./graph";-import { createBuilderStore, snapshot } from "./store";--const store = () =>- createBuilderStore({- nodes: [createNode("trigger", { x: 0, y: 0 })] as unknown as BuilderNode[],- edges: [],- isVersionLocked: false,- canEdit: true,- isOwner: true- });--describe("rebaseline", () => {- it("keeps edits made while a save was in flight dirty", () => {- const api = store();-- // Edit A, then the autosave submits its snapshot.- api.getState().addNode("action", { x: 0, y: 260 });- const submitted = snapshot(api.getState().nodes, api.getState().edges);-- // Edit B lands before A's response comes back.- api.getState().addNode("action", { x: 0, y: 520 });- const current = snapshot(api.getState().nodes, api.getState().edges);-- api.getState().rebaseline(submitted);-- expect(api.getState().baseline).toBe(submitted);- expect(api.getState().baseline).not.toBe(current);- });-- it("marks the graph clean when nothing changed during the save", () => {- const api = store();-- api.getState().addNode("action", { x: 0, y: 260 });- const submitted = snapshot(api.getState().nodes, api.getState().edges);- api.getState().rebaseline(submitted);-- expect(api.getState().baseline).toBe(- snapshot(api.getState().nodes, api.getState().edges)- );- });-});diff --git a/apps/erp/app/routes/api+/integrations.$id.connect.test.ts b/apps/erp/app/routes/api+/integrations.$id.connect.test.tsindex 5e45d5a878..77eeda2151 100644--- a/apps/erp/app/routes/api+/integrations.$id.connect.test.ts+++ b/apps/erp/app/routes/api+/integrations.$id.connect.test.ts@@ -2,16 +2,11 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";const requirePermissions = vi.hoisted(() => vi.fn());-// The rule itself is pinned by `isIntegrationComingSoon`'s tests in-// `@carbon/ee`; here only the route's answer to a withheld install is.-const isIntegrationInstallWithheld = vi.hoisted(() => vi.fn(async () => false));-// Role-aware, because the guard compares the incumbent row against the ids of-// that ROLE. "brex" stands in for a second spend provider: with only Ramp-// registered today a spend role conflict is unreachable, so the guard would-// otherwise be untestable — and silently so.+// "brex" stands in for a second spend provider: with only Ramp registered, a+// spend role conflict would otherwise be unreachable.const getIntegrationIdsByRole = vi.hoisted(() =>vi.fn((role: string) =>role === "spend" ? ["ramp", "brex"] : ["rillet", "xero", "quickbooks"]@@ -21,6 +16,7 @@ const getIntegrationIdsByRole = vi.hoisted(() =>const RAMP = vi.hoisted(() => ({id: "ramp",providerRole: "spend",+ internalOnly: false,oauth: {authUrl: "https://app.ramp.com/v1/authorize",clientId: "client-1",@@ -30,130 +26,134 @@ const RAMP = vi.hoisted(() => ({modes: [{id: "provider",- label: "Carbon is my accounting system",- description: "…",scopes: ["accounting:read", "accounting:write", "offline_access"]},{id: "push-only",- label: "Another system posts my ledger",- description: "…",scopes: ["accounting:read", "bills:write", "offline_access"]}]}));-vi.mock("@carbon/auth", () => ({- CARBON_API_URL: "https://api.example.com",- SUPABASE_URL: "http://localhost",- getAppUrl: () => "https://erp.example.com",- getMESUrl: () => "https://mes.example.com"+vi.mock("@carbon/auth", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ CarbonEdition: "cloud",+ getAppUrl: () => "https://erp.example.com"}));vi.mock("@carbon/auth/auth.server", () => ({ requirePermissions }));-vi.mock("@carbon/ee", () => ({+vi.mock("@carbon/ee", async (importOriginal) => ({+ ...(await importOriginal<object>()),integrations: [RAMP],getIntegrationIdsByRole}));-vi.mock("~/modules/settings/settings.service", () => ({- isIntegrationInstallWithheld-}));import { loader } from "./integrations.$id.connect";-function activeRows(rows: Array<{ id: string }>) {- return {- from: () => ({- select: () => ({- eq: () => ({ eq: () => Promise.resolve({ data: rows, error: null }) })- })- })+type Row = { id: string; companyId: string; active: boolean };++// In-memory companyIntegration table that applies the eq filters it is given.+function integrationTable(rows: Row[]) {+ const query = (filters: [string, unknown][]) => {+ const matched = () =>+ rows.filter((row) =>+ filters.every(([column, value]) => row[column as keyof Row] === value)+ );+ return {+ eq: (column: string, value: unknown) =>+ query([...filters, [column, value]]),+ maybeSingle: async () => ({ data: matched()[0] ?? null, error: null }),+ then: (resolve: (value: unknown) => void) =>+ resolve({ data: matched(), error: null })+ };};+ return { from: () => ({ select: () => query([]) }) };}-async function connect(mode: string | null, rows: Array<{ id: string }> = []) {+async function connect(mode: string | null, rows: Row[] = []) {requirePermissions.mockResolvedValue({userId: "user-1",companyId: "company-1",email: "[email protected]",- client: activeRows(rows)+ client: integrationTable(rows)});const url = new URL("https://erp.example.com/api/integrations/ramp/connect");if (mode !== null) url.searchParams.set("mode", mode);- return (await loader({+ const response = (await loader({request: new Request(url),params: { id: "ramp" }} as never)) as Response;+ return {+ location: new URL(response.headers.get("Location") ?? ""),+ cookie: response.headers.get("Set-Cookie") ?? ""+ };}-describe("integration connect route", () => {- it("builds the authorize URL from the CHOSEN mode's scopes", async () => {- const response = await connect("push-only");- const location = new URL(response.headers.get("Location") ?? "");-- // The security property: the scope list comes from the descriptor's mode,- // server-side. `accounting:write` is what takes Ramp's single accounting- // seat, so a push-only connect must never ask for it.- const scopes = (location.searchParams.get("scope") ?? "").split(" ");- expect(scopes).toContain("bills:write");- expect(scopes).not.toContain("accounting:write");- expect(location.origin + location.pathname).toBe(- "https://app.ramp.com/v1/authorize"- );- });-- it("requests the provider scopes for provider mode", async () => {- const response = await connect("provider");- const scopes = (- new URL(response.headers.get("Location") ?? "").searchParams.get(- "scope"- ) ?? ""- ).split(" ");-- expect(scopes).toContain("accounting:write");- });-- it("sets the signed state cookie", async () => {- const response = await connect("push-only");- expect(response.headers.get("Set-Cookie")).toContain("carbon-oauth-state=");- });-- it("refuses an unknown mode instead of defaulting", async () => {- // Silently defaulting would request `accounting:write` against a customer- // who chose push-only — the exact failure the mode exists to prevent.- const response = await connect("nonsense");+const active = (id: string): Row => ({+ id,+ companyId: "company-1",+ active: true+});- expect(response.headers.get("Location")).toContain("error=invalid-mode");- expect(response.headers.get("Location")).not.toContain("ramp.com");- });+afterEach(() => {+ RAMP.internalOnly = false;+});- it("refuses an ABSENT mode for an integration that declares modes", async () => {- const response = await connect(null);+describe("integration connect route", () => {+ it.each([+ ["push-only", "bills:write"],+ ["provider", "accounting:write"]+ ])(+ "requests the %s mode's scopes with a signed state cookie",+ async (mode, scope) => {+ const { location, cookie } = await connect(mode);++ expect(cookie).toContain("carbon-oauth-state=");+ expect(location.origin + location.pathname).toBe(+ "https://app.ramp.com/v1/authorize"+ );+ expect(location.searchParams.get("scope")?.split(" ")).toContain(scope);+ }+ );- expect(response.headers.get("Location")).toContain("error=invalid-mode");+ it("never asks a push-only connect for accounting:write", async () => {+ // accounting:write takes Ramp's single accounting seat.+ const { location } = await connect("push-only");+ expect(location.searchParams.get("scope")?.split(" ")).not.toContain(+ "accounting:write"+ );});- it("refuses before consent when the role slot is taken", async () => {- // Reaching the database's one-active-per-role refusal AFTER the customer has- // authorized leaves them with a live grant and no install.- const response = await connect("push-only", [{ id: "brex" }]);-- expect(response.headers.get("Location")).toContain("error=role-conflict");- expect(response.headers.get("Location")).not.toContain("ramp.com");+ it("allows reconnecting the integration that already holds the slot", async () => {+ const { location } = await connect("push-only", [active("ramp")]);+ expect(location.host).toBe("app.ramp.com");});- it("allows reconnecting the SAME integration that holds the slot", async () => {- const response = await connect("push-only", [{ id: "ramp" }]);-- expect(response.headers.get("Location")).toContain("ramp.com");- });+ it.each([+ { name: "an unknown mode", mode: "nonsense", error: "invalid-mode" },+ { name: "an absent mode", mode: null, error: "invalid-mode" },+ {+ name: "another spend integration holds the role",+ mode: "push-only",+ rows: [active("brex")],+ error: "role-conflict"+ },+ {+ name: "the install is withheld from this user",+ mode: "push-only",+ internalOnly: true,+ error: "coming-soon"+ }+ ])(+ "refuses before consent when $name",+ async ({ mode, rows, internalOnly, error }) => {+ RAMP.internalOnly = internalOnly ?? false;- it("refuses before consent when the install is withheld from this user", async () => {- isIntegrationInstallWithheld.mockResolvedValueOnce(true);- const response = await connect("push-only");+ const { location } = await connect(mode, rows);- expect(response.headers.get("Location")).toContain("error=coming-soon");- expect(response.headers.get("Location")).not.toContain("ramp.com");- });+ expect(location.host).toBe("erp.example.com");+ expect(location.searchParams.get("error")).toBe(error);+ }+ );});diff --git a/apps/erp/app/routes/api+/integrations.ramp.oauth.test.ts b/apps/erp/app/routes/api+/integrations.ramp.oauth.test.tsindex 6aefe0d676..67c5139fe2 100644--- a/apps/erp/app/routes/api+/integrations.ramp.oauth.test.ts+++ b/apps/erp/app/routes/api+/integrations.ramp.oauth.test.ts@@ -15,16 +15,9 @@ const buildRampClient = vi.hoisted(() =>vi.fn(() => ({ getAccountingConnections })));const patchRampOAuthCredentials = vi.hoisted(() => vi.fn());-// The route no longer decides which connection counts — it delegates to the pure-// `resolveConnectedProviderName`, whose status filtering (including the-// `unlinked` tombstone `DELETE` leaves behind) is pinned by its own real-fixture-// tests in `packages/ee/src/ramp/lib/connection-status.test.ts`. What is left to-// assert HERE is the wiring: the resolver sees Ramp's response, and whatever it-// returns is what gets stored.+// Status filtering is pinned in packages/ee/src/ramp/lib/connection-status.test.ts.const resolveConnectedProviderName = vi.hoisted(() => vi.fn());const rampOnInstall = vi.hoisted(() => vi.fn());-// Real predicate, not a stub: it is a two-line structural check and mocking it-// would make the test pass on a shape the production code rejects.const isRampSeatConflict = vi.hoisted(() => (error: unknown) =>(error as { code?: string })?.code === "RAMP_SEAT_CONFLICT"@@ -47,28 +40,11 @@ vi.mock("@carbon/ee/ramp.server", () => ({patchRampOAuthCredentials,resolveConnectedProviderName}));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn(), info: vi.fn(), warning: vi.fn() })-}));-vi.mock("~/modules/settings/integration-errors", () => ({- integrationErrorSearch: (integration: string, error: string) =>- `?integration=${integration}&error=${error}`-}));-vi.mock("~/modules/shared/shared.models", () => ({- oAuthCallbackSchema: {- safeParse(value: Record<string, unknown>) {- return typeof value.code === "string" && typeof value.state === "string"- ? {- success: true as const,- data: value as { code: string; state: string }- }- : { success: false as const };- }- }-}));import { loader } from "./integrations.ramp.oauth";+const INTEGRATIONS = "https://erp.example.com/x/settings/integrations";+const identity = {integrationId: "ramp",userId: "user-1",@@ -82,26 +58,26 @@ const credentials = {expiresAt: "2026-09-11T13:00:00.000Z"};+// The real state module, so the mode round-trips through the signed cookie.async function callbackRequest(- overrides: { state?: string; cookie?: string; mode?: string } = {}+ overrides: { state?: string; mode?: string } = {}) {- // The REAL state module, so the mode genuinely round-trips through the signed,- // HttpOnly cookie rather than through a stub.const issued = await issueOAuthState({ ...identity, mode: overrides.mode });const state = overrides.state ?? issued.state;- return {- issued,- request: new Request(- `https://erp.example.com/api/integrations/ramp/oauth?code=code-1&state=${encodeURIComponent(state)}`,- { headers: { Cookie: overrides.cookie ?? issued.cookie } }- )- };+ return new Request(+ `https://erp.example.com/api/integrations/ramp/oauth?code=code-1&state=${encodeURIComponent(state)}`,+ { headers: { Cookie: issued.cookie } }+ );}-async function run(request: Request) {+function run(request: Request) {return loader({ request, params: {} } as never) as Promise<Response>;}+function storedPatch() {+ return patchRampOAuthCredentials.mock.calls[0]?.[2];+}+describe("Ramp OAuth callback", () => {beforeEach(() => {vi.clearAllMocks();@@ -114,222 +90,139 @@ describe("Ramp OAuth callback", () => {credentials,grantedScopes: ["accounting:read", "bills:write"]});- patchRampOAuthCredentials.mockResolvedValue({- id: "ramp",- metadata: {}- });+ patchRampOAuthCredentials.mockResolvedValue({ id: "ramp", metadata: {} });rampOnInstall.mockResolvedValue(undefined);getAccountingConnections.mockResolvedValue({ connections: [] });resolveConnectedProviderName.mockReturnValue(undefined);});it("rejects a forged state before exchanging the authorization code", async () => {- const { request } = await callbackRequest({ state: "forged" });-- const response = await run(request);+ const response = await run(await callbackRequest({ state: "forged" }));- expect(response.status).toBe(302);expect(response.headers.get("Location")).toBe(- "https://erp.example.com/x/settings/integrations?integration=ramp&error=invalid-state"+ `${INTEGRATIONS}?integration=ramp&error=invalid-state`);expect(response.headers.get("Set-Cookie")).toContain("carbon-oauth-state=");expect(exchangeRampOAuthCode).not.toHaveBeenCalled();- expect(patchRampOAuthCredentials).not.toHaveBeenCalled();});- it("consumes a valid state so replay cannot exchange or write twice", async () => {- const { request } = await callbackRequest();+ it("consumes a valid state so a replay cannot exchange or write twice", async () => {+ const request = await callbackRequest();const first = await run(request);- const consumedCookie = first.headers.get("Set-Cookie") ?? "";- const replayUrl = new URL(request.url);const replay = await run(- new Request(replayUrl, { headers: { Cookie: consumedCookie } })+ new Request(request.url, {+ headers: { Cookie: first.headers.get("Set-Cookie") ?? "" }+ }));- expect(first.status).toBe(302);- expect(first.headers.get("Location")).toBe(- "https://erp.example.com/x/settings/integrations"- );+ expect(first.headers.get("Location")).toBe(INTEGRATIONS);expect(replay.headers.get("Location")).toContain("error=invalid-state");expect(exchangeRampOAuthCode).toHaveBeenCalledTimes(1);expect(patchRampOAuthCredentials).toHaveBeenCalledTimes(1);});- it("atomically patches only OAuth-owned credentials", async () => {- const { request } = await callbackRequest();-- await run(request);+ it("stores the granted scopes and leaves an unstamped mode and unknown owner empty", async () => {+ await run(await callbackRequest());- expect(patchRampOAuthCredentials).toHaveBeenCalledWith(- { role: "service" },- identity.companyId,- {- credentials,- // What the token response GRANTED, not what was requested — RFC 6749 §3.3- // permits a narrower grant, and recording the request would make the UI- // claim capabilities the token may not carry.- grantedScopes: ["accounting:read", "bills:write"],- // Absent here: the fixture's state carries no mode, and a missing mode- // must stay missing rather than defaulting — `resolveRampMode` is the one- // place that decides an unstamped install is `provider`.- syncMode: undefined,- accountingConnectionProvider: undefined,- updatedBy: identity.userId- }- );+ // Granted, not requested: RFC 6749 §3.3 allows a narrower grant.+ expect(storedPatch()).toEqual({+ credentials,+ grantedScopes: ["accounting:read", "bills:write"],+ syncMode: undefined,+ accountingConnectionProvider: undefined,+ updatedBy: identity.userId+ });});- it("stamps the mode from the SIGNED state, never a query parameter", async () => {- // A user-editable mode would let someone consent to push-only's narrow scopes- // and have Carbon record a provider-mode install, or the reverse. The mode is- // in the cookie here and NOT in the URL — the assertion only passes if the- // callback reads the signed payload.- const { request } = await callbackRequest({ mode: "push-only" });- expect(new URL(request.url).searchParams.get("mode")).toBeNull();-- await run(request);-- expect(patchRampOAuthCredentials).toHaveBeenCalledWith(- { role: "service" },- identity.companyId,- expect.objectContaining({ syncMode: "push-only" })- );+ it("stamps the mode from the signed state", async () => {+ await run(await callbackRequest({ mode: "push-only" }));+ expect(storedPatch()?.syncMode).toBe("push-only");});it("ignores a mode supplied in the query string", async () => {- // Belt-and-braces on the same property: a forged `?mode=` must not reach the- // stored install when the signed state says nothing.- const { request } = await callbackRequest();+ // A user-editable mode would let push-only's narrow consent record a provider install.+ const request = await callbackRequest();const forged = new URL(request.url);forged.searchParams.set("mode", "provider");await run(new Request(forged, { headers: request.headers }));- expect(patchRampOAuthCredentials).toHaveBeenCalledWith(- { role: "service" },- identity.companyId,- expect.objectContaining({ syncMode: undefined })- );+ expect(storedPatch()?.syncMode).toBeUndefined();});- it("records the peer connection owner when Ramp reports one", async () => {- const response = {+ it("stores the provider the resolver reads from Ramp's connections", async () => {+ const connections = {connections: [{ remote_provider_name: "Rillet", status: "linked" }]};- getAccountingConnections.mockResolvedValue(response);- resolveConnectedProviderName.mockReturnValue("Rillet");- const { request } = await callbackRequest();-- await run(request);-- // The resolver is handed Ramp's response verbatim — a route that pre-filtered- // or reshaped it would reintroduce the second, divergent reading this- // delegation removed.- expect(resolveConnectedProviderName).toHaveBeenCalledWith(response);- expect(patchRampOAuthCredentials).toHaveBeenCalledWith(- { role: "service" },- identity.companyId,- expect.objectContaining({ accountingConnectionProvider: "Rillet" })+ getAccountingConnections.mockResolvedValue(connections);+ resolveConnectedProviderName.mockImplementation((response) =>+ response === connections ? "Rillet" : undefined);- });- it("records UNKNOWN when no connection is live", async () => {- // The reachable case after a disconnect: Ramp still returns the old- // connection as an `unlinked` tombstone carrying its provider name, and the- // resolver filters it out. Storing a name here would claim a ledger holder- // for a business that has none.- getAccountingConnections.mockResolvedValue({- connections: [{ remote_provider_name: "Carbon", status: "unlinked" }]- });- resolveConnectedProviderName.mockReturnValue(undefined);- const { request } = await callbackRequest();+ await run(await callbackRequest());- await run(request);-- expect(patchRampOAuthCredentials).toHaveBeenCalledWith(- { role: "service" },- identity.companyId,- expect.objectContaining({ accountingConnectionProvider: undefined })- );+ expect(storedPatch()?.accountingConnectionProvider).toBe("Rillet");});- it("completes the install when the peer read FAILS", async () => {- // Whether a token lacking `accounting:write` may call all-connections is an- // OPEN QUESTION. A 403 must leave the owner UNKNOWN and still install — the- // grant is already valid at this point, and failing here would strand it.+ it("completes the install with an unknown owner when the peer read fails", async () => {+ // The grant is already valid here; failing on an informational read would strand it.getAccountingConnections.mockRejectedValue(new Error("403 DEVELOPER_7100"));- const { request } = await callbackRequest();- const response = await run(request);+ const response = await run(await callbackRequest());- expect(patchRampOAuthCredentials).toHaveBeenCalledWith(- { role: "service" },- identity.companyId,- expect.objectContaining({ accountingConnectionProvider: undefined })- );- expect(response.headers.get("Location")).toBe(- "https://erp.example.com/x/settings/integrations"- );+ expect(storedPatch()?.accountingConnectionProvider).toBeUndefined();+ expect(response.headers.get("Location")).toBe(INTEGRATIONS);});- it("redirects with a stable error when the atomic credential patch fails", async () => {- patchRampOAuthCredentials.mockRejectedValue(new Error("vault unavailable"));- const { request } = await callbackRequest();-- const response = await run(request);-- expect(response.headers.get("Location")).toBe(- "https://erp.example.com/x/settings/integrations?integration=ramp&error=save-failed"- );- expect(patchRampOAuthCredentials).toHaveBeenCalledTimes(1);- });-- it("redirects token-exchange failures with a stable code and no provider detail", async () => {- exchangeRampOAuthCode.mockRejectedValue(- new Error("provider-controlled secret detail")- );- const { request } = await callbackRequest();-- const response = await run(request);-- expect(response.status).toBe(302);- expect(response.headers.get("Location")).toBe(- "https://erp.example.com/x/settings/integrations?integration=ramp&error=token-exchange"- );- expect(response.headers.get("Location")).not.toContain(- "provider-controlled"- );- expect(patchRampOAuthCredentials).not.toHaveBeenCalled();- });-- it("names the seat conflict instead of a generic setup failure", async () => {- // Ramp permits ONE connected accounting system. "Try connecting again" is- // actively wrong here — a retry cannot succeed until the other system is- // disconnected or the customer picks push-only.- const conflict = Object.assign(- new Error("Ramp's accounting connection is held by Rillet."),- { code: "RAMP_SEAT_CONFLICT" }- );- rampOnInstall.mockRejectedValue(conflict);- const { request } = await callbackRequest();-- const response = await run(request);-- expect(response.headers.get("Location")).toBe(- "https://erp.example.com/x/settings/integrations?integration=ramp&error=seat-conflict"- );- // The provider-supplied holder name must not cross the URL.- expect(response.headers.get("Location")).not.toContain("Rillet");- });-- it("still reports an ordinary install failure generically", async () => {- rampOnInstall.mockRejectedValue(new Error("webhook exploded"));- const { request } = await callbackRequest();+ it.each([+ {+ failure: "the token exchange fails",+ arrange: () =>+ exchangeRampOAuthCode.mockRejectedValue(+ new Error("provider-controlled detail")+ ),+ error: "token-exchange"+ },+ {+ failure: "another spend integration holds the slot",+ arrange: () =>+ patchRampOAuthCredentials.mockRejectedValue({ code: "23505" }),+ error: "role-conflict"+ },+ {+ failure: "the credential patch fails",+ arrange: () =>+ patchRampOAuthCredentials.mockRejectedValue(+ new Error("vault unavailable")+ ),+ error: "save-failed"+ },+ {+ failure: "another system holds Ramp's accounting seat",+ arrange: () =>+ rampOnInstall.mockRejectedValue(+ Object.assign(new Error("held by Rillet"), {+ code: "RAMP_SEAT_CONFLICT"+ })+ ),+ error: "seat-conflict"+ },+ {+ failure: "the install converge fails",+ arrange: () => rampOnInstall.mockRejectedValue(new Error("webhook")),+ error: "install-failed"+ }+ ])(+ "redirects with error=$error when $failure",+ async ({ arrange, error }) => {+ arrange();- const response = await run(request);+ const response = await run(await callbackRequest());- expect(response.headers.get("Location")).toBe(- "https://erp.example.com/x/settings/integrations?integration=ramp&error=install-failed"- );- });+ // Only a stable code crosses the URL, never provider text.+ expect(response.headers.get("Location")).toBe(+ `${INTEGRATIONS}?integration=ramp&error=${error}`+ );+ }+ );});diff --git a/apps/erp/app/routes/api+/mcp+/lib/describe-format.test.ts b/apps/erp/app/routes/api+/mcp+/lib/describe-format.test.tsindex 5627013cd4..e298a27feb 100644--- a/apps/erp/app/routes/api+/mcp+/lib/describe-format.test.ts+++ b/apps/erp/app/routes/api+/mcp+/lib/describe-format.test.ts@@ -242,14 +242,12 @@ describe("searchLineDescription", () => {).toBe("Value an item's serial units on hand.");});- test("skips a description that restates the name", () => {- for (const [name, description] of [- ["sales_getCustomers", "get customers"],- ["inventory_getReceipt", "Get receipt."],- ["inventory_postReceipt", "Post a receipt."]- ]) {- expect(searchLineDescription({ name, description })).toBe(null);- }+ test.each([+ ["sales_getCustomers", "get customers"],+ ["inventory_getReceipt", "Get receipt."],+ ["inventory_postReceipt", "Post a receipt."]+ ])("skips %s's description that restates the name", (name, description) => {+ expect(searchLineDescription({ name, description })).toBe(null);});test("keeps a description that says more than the name", () => {@@ -282,25 +280,14 @@ describe("paginatingSibling", () => {});describe("getServerInstructions", () => {- const instructions = getServerInstructions(- "2026-09-11",- toolMetadata as unknown as Parameters<typeof getServerInstructions>[1]- );-- test("lists every module name", () => {+ test("lists every module in the manifest", () => {+ const instructions = getServerInstructions(+ "2026-09-11",+ toolMetadata as unknown as Parameters<typeof getServerInstructions>[1]+ );const modules = [...new Set(toolMetadata.tools.map((t) => t.module))];for (const module of modules) {expect(instructions).toContain(module);}});-- test("derives the default page size from the constant", () => {- expect(instructions).toContain(- `List reads default to ${MCP_DEFAULT_LIMIT} rows`- );- });-- test("documents describe_tool batching", () => {- expect(instructions).toContain('names: ["sales_getCustomers"');- });});diff --git a/apps/erp/app/routes/api+/mcp+/lib/manifest.test.ts b/apps/erp/app/routes/api+/mcp+/lib/manifest.test.tsindex 92dad11ced..69abbe4535 100644--- a/apps/erp/app/routes/api+/mcp+/lib/manifest.test.ts+++ b/apps/erp/app/routes/api+/mcp+/lib/manifest.test.ts@@ -3,7 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { describe, expect, it } from "vitest";-import { buildMcpManifest, MCP_META_KEY, MCP_SERVER_NAME } from "./manifest";+import { buildMcpManifest, MCP_META_KEY } from "./manifest";import toolMetadataJson from "./tool-metadata.json";const toolMetadata = toolMetadataJson as unknown as {@@ -11,90 +11,54 @@ const toolMetadata = toolMetadataJson as unknown as {tools: { module: string; classification: string }[];};-const ORIGIN = "https://app.carbon.ms";-const manifest = buildMcpManifest(ORIGIN);-const meta = manifest._meta[MCP_META_KEY];-describe("buildMcpManifest", () => {- it("declares the registry schema and a reverse-DNS name", () => {- expect(manifest.$schema).toMatch(/server\.schema\.json$/);- expect(manifest.name).toBe(MCP_SERVER_NAME);- expect(manifest.name).toMatch(/^[a-z0-9.-]+\/[a-z0-9-]+$/);- });-- it("advertises Streamable HTTP at this deployment's own endpoint", () => {- expect(manifest.remotes[0].type).toBe("streamable-http");- expect(manifest.remotes[0].url).toBe(`${ORIGIN}/api/mcp`);- expect(meta.transport).toBe("streamable-http");- expect(meta.endpoint).toBe(`${ORIGIN}/api/mcp`);- });-- it("follows the origin, so a self-hosted instance points at itself", () => {- // A manifest that hard-codes app.carbon.ms sends every self-hosted client- // to the wrong tenant's server.- const selfHosted = buildMcpManifest("https://erp.example.com");- const selfHostedMeta = selfHosted._meta[MCP_META_KEY];-- expect(selfHosted.remotes[0].url).toBe("https://erp.example.com/api/mcp");- expect(selfHostedMeta.authentication.protectedResourceMetadata).toBe(- "https://erp.example.com/.well-known/oauth-protected-resource"- );- expect(selfHostedMeta.clientConfig.mcpServers.carbon.url).toBe(- "https://erp.example.com/api/mcp"- );- });-- it("points at the OAuth metadata this app actually serves", () => {- // Both paths have routes in apps/erp/app/routes/.- expect(meta.authentication.protectedResourceMetadata).toBe(- `${ORIGIN}/.well-known/oauth-protected-resource`- );- expect(meta.authentication.authorizationServerMetadata).toBe(- `${ORIGIN}/.well-known/oauth-authorization-server`- );- expect(meta.authentication.schemes).toContain("bearer");+ it("points every URL at the deployment's own origin", () => {+ // A hard-coded app.carbon.ms would send self-hosted clients to the wrong server.+ const manifest = buildMcpManifest("https://erp.example.com");+ const meta = manifest._meta[MCP_META_KEY];++ expect({+ remote: manifest.remotes[0].url,+ endpoint: meta.endpoint,+ clientConfig: meta.clientConfig.mcpServers.carbon.url,+ protectedResource: meta.authentication.protectedResourceMetadata,+ authorizationServer: meta.authentication.authorizationServerMetadata+ }).toEqual({+ remote: "https://erp.example.com/api/mcp",+ endpoint: "https://erp.example.com/api/mcp",+ clientConfig: "https://erp.example.com/api/mcp",+ protectedResource:+ "https://erp.example.com/.well-known/oauth-protected-resource",+ authorizationServer:+ "https://erp.example.com/.well-known/oauth-authorization-server"+ });});- it("marks the credential required and secret", () => {- const header = manifest.remotes[0].headers[0];- expect(header.name).toBe("Authorization");- expect(header.isRequired).toBe(true);- expect(header.isSecret).toBe(true);- });+ const manifest = buildMcpManifest("https://app.carbon.ms");+ const meta = manifest._meta[MCP_META_KEY];- it("describes exactly the tools the server registers", () => {- expect(meta.tools.map((tool) => tool.name)).toEqual([- "search_tools",- "describe_tool",- "call_tool",- "call_destructive_tool"- ]);- for (const tool of meta.tools) {- expect(tool.description.length, tool.name).toBeGreaterThan(40);- }+ it("marks the Authorization header required and secret", () => {+ expect(manifest.remotes[0].headers[0]).toMatchObject({+ name: "Authorization",+ isRequired: true,+ isSecret: true+ });});- it("derives its counts from tool-metadata rather than restating them", () => {- // This is the anti-drift property: remove a module and the manifest stops- // advertising it without anyone remembering to edit this file.- const modules = [- ...new Set(toolMetadata.tools.map((t) => t.module))- ].sort();- const classifications = [- ...new Set(toolMetadata.tools.map((t) => t.classification))- ].sort();+ it("derives its counts from tool-metadata", () => {+ const sortedSet = (values: string[]) => [...new Set(values)].sort();- expect(meta.operations.total).toBe(toolMetadata.totalTools);- expect(meta.operations.modules).toEqual(modules);- expect(meta.operations.classifications).toEqual(classifications);- expect(modules.length).toBeGreaterThan(0);+ expect(meta.operations).toMatchObject({+ total: toolMetadata.totalTools,+ modules: sortedSet(toolMetadata.tools.map((t) => t.module)),+ classifications: sortedSet(+ toolMetadata.tools.map((t) => t.classification)+ )+ });});it("leaves the client-config credential as an unexpanded placeholder", () => {- // If someone turns this into a template literal it interpolates to- // "Bearer " and the published config hands out an empty credential.- // The `\{` escape keeps this an independent literal — no interpolation- // here, and no lint suppression needed to assert on a `${...}` placeholder.+ // As a template literal it would publish "Bearer " with an empty credential.expect(meta.clientConfig.mcpServers.carbon.headers.Authorization).toBe(`Bearer $\{CARBON_API_KEY}`);@@ -113,10 +77,6 @@ describe("buildMcpManifest", () => {"websiteUrl"]);});-- it("serializes to JSON without loss", () => {- expect(JSON.parse(JSON.stringify(manifest))).toEqual(manifest);- });});describe("/.well-known/mcp.json", () => {@@ -127,14 +87,10 @@ describe("/.well-known/mcp.json", () => {request: new Request("https://app.carbon.ms/.well-known/mcp.json")} as Parameters<typeof loader>[0]);- expect(response.status).toBe(200);expect(response.headers.get("Content-Type")).toBe("application/json");expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*");- expect(response.headers.get("Cache-Control")).toBe("public, max-age=3600");-- const body = await response.json();- expect(body.name).toBe(MCP_SERVER_NAME);- expect(body.remotes[0].type).toBe("streamable-http");- expect(body.remotes[0].url).toMatch(/\/api\/mcp$/);+ expect((await response.json()).remotes[0].url).toBe(+ "https://app.carbon.ms/api/mcp"+ );});});diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex 07c76ee7d3..3e58aa2c77 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -263,7 +263,7 @@{"name":"inventory_pickPickingListLineEntity","classification":"WRITE","schema":"5a008770ac64","response":"3797626bd17e","permission":"inventory:update","paginates":false},{"name":"inventory_pickStockTransferLine","classification":"WRITE","schema":"0d3ec0c22afe","response":"7ad8a3f49853","permission":"inventory:create","paginates":false},{"name":"inventory_pickStockTransferLineEntity","classification":"WRITE","schema":"d077ae617fd9","response":"7ad8a3f49853","permission":"inventory:update","paginates":false},- {"name":"inventory_postInventoryCount","classification":"WRITE","schema":"e354150046fe","response":"c65e556842f4","permission":"inventory:update","paginates":false},+ {"name":"inventory_postInventoryCount","classification":"WRITE","schema":"e354150046fe","response":"08fce539083e","permission":"inventory:update","paginates":false},{"name":"inventory_postReceipt","classification":"WRITE","schema":"748c476fdf2b","response":"727cf771e24b","permission":"inventory:update","paginates":false},{"name":"inventory_postShipment","classification":"WRITE","schema":"c5945bba6ca6","response":"d2fbdd9c8de9","permission":"inventory:update","paginates":false},{"name":"inventory_recostSerialUnit","classification":"WRITE","schema":"c3f4c85c02d3","response":"1791201245a6","permission":"accounting:update","paginates":false},diff --git a/apps/erp/app/routes/api+/traceability.expand.test.ts b/apps/erp/app/routes/api+/traceability.expand.test.tsindex f3c0e946b2..8f1ea8853b 100644--- a/apps/erp/app/routes/api+/traceability.expand.test.ts+++ b/apps/erp/app/routes/api+/traceability.expand.test.ts@@ -3,76 +3,52 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import { beforeEach, describe, expect, it, vi } from "vitest";-import { fetchLineageSubgraph } from "~/modules/inventory/inventory.service";-import { requireCompanyRecord } from "~/modules/shared/shared.service";+import { expect, it, vi } from "vitest";import { loader } from "./traceability.expand";-vi.mock("@carbon/auth/auth.server", () => ({- requirePermissions: vi.fn()-}));-vi.mock("~/modules/inventory/inventory.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- fetchLineageSubgraph: vi.fn(async () => ({ entities: [], activities: [] }))-}));-vi.mock("~/modules/shared/shared.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- requireCompanyRecord: vi.fn(async () => undefined)-}));--const client = { from: vi.fn(), rpc: vi.fn() };--function load(query: string) {- return loader({- request: new Request(`http://localhost/api/traceability/expand?${query}`)- } as any);+vi.mock("@carbon/auth/auth.server", () => ({ requirePermissions: vi.fn() }));++// The service-role client the route gets: tracked entities filtered by every+// `.match` and `.eq`. Anything past the ownership check is out of reach.+function serviceRole(entities: Record<string, unknown>[]) {+ return {+ from() {+ let rows = entities;+ const query = {+ select: () => query,+ match: (match: Record<string, unknown>) => {+ rows = rows.filter((row) =>+ Object.entries(match).every(([key, value]) => row[key] === value)+ );+ return query;+ },+ eq: (column: string, value: unknown) => {+ rows = rows.filter((row) => row[column] === value);+ return query;+ },+ maybeSingle: async () => ({ data: rows[0] ?? null, error: null })+ };+ return query;+ },+ rpc: () => {+ throw new Error("traversed past the ownership check");+ }+ };}-describe("traceability expand loader", () => {- beforeEach(() => {- vi.clearAllMocks();- vi.mocked(requirePermissions).mockResolvedValue({- client,- companyId: "company-1"- } as any);- });-- it("proves the entity is the caller's company's before traversing", async () => {- const response = await load("trackedEntityId=entity-1&depth=2");-- expect(response.status).toBe(200);- expect(requireCompanyRecord).toHaveBeenCalledWith(- client,- "trackedEntity",- "company-1",- { id: "entity-1" }- );- expect(fetchLineageSubgraph).toHaveBeenCalledWith(- client,- "entity-1",- "company-1",- 2,- "both"- );- });-- it("stops before any traversal when the entity is another company's", async () => {- vi.mocked(requireCompanyRecord).mockRejectedValueOnce(- new Response("Not found", { status: 404 })- );-- await expect(load("trackedEntityId=foreign-entity")).rejects.toMatchObject({- status: 404- });- expect(fetchLineageSubgraph).not.toHaveBeenCalled();- expect(client.rpc).not.toHaveBeenCalled();- });-- it("returns 400 without a trackedEntityId", async () => {- const response = await load("depth=1");-- expect(response.status).toBe(400);- expect(requireCompanyRecord).not.toHaveBeenCalled();- expect(fetchLineageSubgraph).not.toHaveBeenCalled();- });+it("refuses another company's tracked entity before traversing its lineage", async () => {+ vi.mocked(requirePermissions).mockResolvedValue({+ client: serviceRole([{ id: "entity-1", companyId: "company-2" }]),+ companyId: "company-1"+ } as unknown as Awaited<ReturnType<typeof requirePermissions>>);++ await expect(+ loader({+ request: new Request(+ "http://localhost/api/traceability/expand?trackedEntityId=entity-1"+ ),+ params: {},+ context: {}+ } as Parameters<typeof loader>[0])+ ).rejects.toMatchObject({ status: 404 });});diff --git a/apps/erp/app/routes/api+/traceability.search.test.ts b/apps/erp/app/routes/api+/traceability.search.test.tsdeleted file mode 100644index 493c1437cc..0000000000--- a/apps/erp/app/routes/api+/traceability.search.test.ts+++ /dev/null@@ -1,69 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { requirePermissions } from "@carbon/auth/auth.server";-import { describe, expect, it, vi } from "vitest";-import { loader } from "./traceability.search";--vi.mock("@carbon/auth/auth.server", () => ({- requirePermissions: vi.fn()-}));--describe("traceability search loader", () => {- it("returns tracked entity readableId without querying job readable ids", async () => {- const entityQuery = createQuery([- {- id: "tracked-entity-1",- readableId: "TRK-0001",- attributes: { Job: "job-uuid-1" }- }- ]);- const activityQuery = createQuery([]);- const from = vi.fn((table: string) => {- if (table === "trackedEntity") return entityQuery;- if (table === "trackedActivity") return activityQuery;- throw new Error(`Unexpected table query: ${table}`);- });-- vi.mocked(requirePermissions).mockResolvedValue({- client: { from },- companyId: "company-1"- } as any);-- const response = await loader({- request: new Request(- "http://localhost/api/traceability.search?q=TRK&kind=entity"- )- } as any);- const body = await response.json();-- expect(body.entities).toEqual([- {- id: "tracked-entity-1",- readableId: "TRK-0001",- attributes: { Job: "job-uuid-1" }- }- ]);- expect(body.entities[0]).not.toHaveProperty("jobId");- expect(body.entities[0]).not.toHaveProperty("jobReadableId");- expect(from).not.toHaveBeenCalledWith("job");- expect(entityQuery.or).toHaveBeenCalledWith(- 'id.ilike."%TRK%",sourceDocumentReadableId.ilike."%TRK%",readableId.ilike."%TRK%"'- );- });-});--function createQuery(data: unknown[]) {- const result = Promise.resolve({ data });- const query = {- select: vi.fn(() => query),- eq: vi.fn(() => query),- order: vi.fn(() => query),- limit: vi.fn(() => query),- or: vi.fn(() => result),- then: result.then.bind(result)- };-- return query;-}diff --git a/apps/erp/app/routes/api+/traceability.sidebar.test.ts b/apps/erp/app/routes/api+/traceability.sidebar.test.tsindex 629ceaf159..d021fa0c93 100644--- a/apps/erp/app/routes/api+/traceability.sidebar.test.ts+++ b/apps/erp/app/routes/api+/traceability.sidebar.test.ts@@ -3,114 +3,77 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import { beforeEach, describe, expect, it, vi } from "vitest";-import { fetchJobStepRecords } from "~/modules/inventory/inventory.service";+import { expect, it, vi } from "vitest";import { loader } from "./traceability.sidebar";-vi.mock("@carbon/auth/auth.server", () => ({- requirePermissions: vi.fn()-}));-vi.mock("~/modules/inventory/inventory.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- fetchJobStepRecords: vi.fn(async () => [{ id: "step-record-1" }])-}));--type Row = Record<string, unknown> | null;--function createQuery(data: Row) {- const query = {- select: vi.fn(() => query),- eq: vi.fn(() => query),- maybeSingle: vi.fn(async () => ({ data, error: null }))+vi.mock("@carbon/auth/auth.server", () => ({ requirePermissions: vi.fn() }));++type Row = Record<string, unknown>;++// The service-role client the route gets: rows filtered by every `.eq`, and a+// step-record RPC that answers for any job it is asked about.+function serviceRole(tables: Record<string, Row[]>) {+ return {+ from(table: string) {+ let rows = tables[table] ?? [];+ const query = {+ select: () => query,+ eq: (column: string, value: unknown) => {+ rows = rows.filter((row) => row[column] === value);+ return query;+ },+ maybeSingle: async () => ({ data: rows[0] ?? null, error: null })+ };+ return query;+ },+ rpc: async () => ({ data: [{ id: "step-record-1" }], error: null })};- return query;}-function setup({ activity, job }: { activity: Row; job: Row }) {- const activityQuery = createQuery(activity);- const jobQuery = createQuery(job);- const client = {- from: vi.fn((table: string) => {- if (table === "trackedActivity") return activityQuery;- if (table === "job") return jobQuery;- throw new Error(`Unexpected table query: ${table}`);- }),- rpc: vi.fn()- };+const tables = {+ trackedActivity: [+ { id: "act-own", companyId: "company-1", attributes: { Job: "job-own" } },+ {+ id: "act-foreign-job",+ companyId: "company-1",+ attributes: { Job: "job-foreign" }+ },+ {+ id: "act-foreign",+ companyId: "company-2",+ attributes: { Job: "job-foreign" }+ }+ ],+ job: [+ { id: "job-own", companyId: "company-1" },+ { id: "job-foreign", companyId: "company-2" }+ ]+};++async function stepRecordIds(activityId: string) {vi.mocked(requirePermissions).mockResolvedValue({- client,+ client: serviceRole(tables),companyId: "company-1"- } as any);- return { client, activityQuery, jobQuery };-}--async function load(query: string) {+ } as unknown as Awaited<ReturnType<typeof requirePermissions>>);const response = await loader({- request: new Request(`http://localhost/api/traceability/sidebar?${query}`)- } as any);- return { status: response.status, body: await response.json() };+ request: new Request(+ `http://localhost/api/traceability/sidebar?activityId=${activityId}`+ ),+ params: {},+ context: {}+ } as Parameters<typeof loader>[0]);+ const body = (await response.json()) as { stepRecords: { id: string }[] };+ return body.stepRecords.map((record) => record.id);}-describe("traceability sidebar loader", () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it("scopes the activity and its job to the caller's company", async () => {- const { client, activityQuery, jobQuery } = setup({- activity: { attributes: { Job: "job-1" } },- job: { id: "job-1" }- });-- const { status, body } = await load("activityId=activity-1");-- expect(status).toBe(200);- expect(body).toEqual({ stepRecords: [{ id: "step-record-1" }] });- expect(activityQuery.eq).toHaveBeenCalledWith("id", "activity-1");- expect(activityQuery.eq).toHaveBeenCalledWith("companyId", "company-1");- expect(jobQuery.eq).toHaveBeenCalledWith("id", "job-1");- expect(jobQuery.eq).toHaveBeenCalledWith("companyId", "company-1");- expect(fetchJobStepRecords).toHaveBeenCalledWith(- client,- "job-1",- "company-1"- );- });-- it("returns no step records for another company's activity", async () => {- const { client, jobQuery } = setup({ activity: null, job: null });-- const { status, body } = await load("activityId=foreign-activity");-- expect(status).toBe(200);- expect(body).toEqual({ stepRecords: [] });- expect(jobQuery.maybeSingle).not.toHaveBeenCalled();- expect(fetchJobStepRecords).not.toHaveBeenCalled();- expect(client.rpc).not.toHaveBeenCalled();- });-- it("returns no step records when the activity names another company's job", async () => {- const { client } = setup({- activity: { attributes: { Job: "foreign-job" } },- job: null- });-- const { status, body } = await load("activityId=activity-1");-- expect(status).toBe(200);- expect(body).toEqual({ stepRecords: [] });- expect(fetchJobStepRecords).not.toHaveBeenCalled();- expect(client.rpc).not.toHaveBeenCalled();- });-- it("returns no step records without an activityId", async () => {- const { client } = setup({ activity: null, job: null });-- const { status, body } = await load("");+it("returns the step records of the caller's own job", async () => {+ expect(await stepRecordIds("act-own")).toEqual(["step-record-1"]);+});- expect(status).toBe(200);- expect(body).toEqual({ stepRecords: [] });- expect(client.from).not.toHaveBeenCalled();- expect(fetchJobStepRecords).not.toHaveBeenCalled();- });+it.each([+ ["an activity of another company", "act-foreign"],+ ["an own activity naming another company's job", "act-foreign-job"],+ ["no activity", ""]+])("returns no step records for %s", async (_label, activityId) => {+ expect(await stepRecordIds(activityId)).toEqual([]);});diff --git a/apps/erp/app/routes/api+/v1+/lib/orpc-mechanics.test.ts b/apps/erp/app/routes/api+/v1+/lib/orpc-mechanics.test.tsindex ccd1d2b6cd..c9aea64dba 100644--- a/apps/erp/app/routes/api+/v1+/lib/orpc-mechanics.test.ts+++ b/apps/erp/app/routes/api+/v1+/lib/orpc-mechanics.test.ts@@ -2,25 +2,17 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-// Validates the oRPC wiring the Carbon API v1 surface depends on, without booting the-// app: a runtime-built router of procedures, the OpenAPIHandler matching a prefixed-// POST path, server-side call(), and the custom JSON-Schema converter feeding-// OpenAPIGenerator. Uses the REAL base/jsonSchema/converter with tiny inline-// handlers (so it never pulls the full service registry). The caller's permission-// is the service function's gate (`service-fn.server.test.ts`).+// The real base, converter and schema builders over one tiny inline procedure, so+// the spec can be generated without the full service registry.import type { ManifestEntry } from "@carbon/api";import { CarbonJsonSchemaConverter, jsonSchema } from "@carbon/api/schema";import { OpenAPIGenerator } from "@orpc/openapi";-import { OpenAPIHandler } from "@orpc/openapi/fetch";-import { call } from "@orpc/server";import { describe, expect, it } from "vitest";-import { type AuthedContext, base, scopesFromPermissions } from "./base.server";+import { base, scopesFromPermissions } from "./base.server";import { outputSchema, shapeHttpBody } from "./operations.server";import { specOptions, withErrorResponses } from "./spec-options.server";-const PREFIX = "/api/v1";-function meta(overrides: Partial<ManifestEntry>): ManifestEntry {return {name: "demo_ping",@@ -36,19 +28,12 @@ function meta(overrides: Partial<ManifestEntry>): ManifestEntry {}const ping = base- .route({- method: "POST",- path: "/demo/ping",- tags: ["demo"],- summary: "demo ping"- })+ .route({ method: "POST", path: "/demo/ping", tags: ["demo"] }).input(jsonSchema({ type: "object", properties: { name: { type: "string" } } })).output(jsonSchema(- // The REAL schema builder, with a list-shaped response — pins that the- // converter carries the current { results, count } envelope into the spec.outputSchema(meta({responseSchema: {@@ -62,59 +47,15 @@ const ping = base.handler(({ input }) => ({ data: input }));const router = { demo: { ping } };-const handler = new OpenAPIHandler(router);-function ctx(overrides: Partial<AuthedContext> = {}): AuthedContext {- return {- client: {} as AuthedContext["client"],- userId: "u1",- companyId: "c1",- companyGroupId: "g1",- authKind: "oauth",- scopes: {},- ...overrides- };-}--describe("oRPC mechanics for the Carbon API v1 surface", () => {- it("matches a prefixed POST path and returns the handler result over HTTP", async () => {- const request = new Request(`https://x.test${PREFIX}/demo/ping`, {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify({ name: "hello" })- });- const { matched, response } = await handler.handle(request, {- prefix: PREFIX,- context: ctx()- });- expect(matched).toBe(true);- expect(response?.status).toBe(200);- const body = (await response?.json()) as { data?: { name?: string } };- expect(body.data?.name).toBe("hello");- });-- it("does not match an unknown operation path", async () => {- const request = new Request(`https://x.test${PREFIX}/demo/nope`, {- method: "POST",- headers: { "content-type": "application/json" },- body: "{}"- });- const { matched } = await handler.handle(request, {- prefix: PREFIX,- context: ctx()- });- expect(matched).toBe(false);- });-- it("runs the middleware chain via server-side call()", async () => {- const result = await call(- router.demo.ping,- { name: "y" },- { context: ctx() }- );- expect(result).toEqual({ data: { name: "y" } });+async function generateSpec(): Promise<any> {+ const generator = new OpenAPIGenerator({+ schemaConverters: [new CarbonJsonSchemaConverter()]});+ return generator.generate(router, specOptions());+}+describe("Carbon API v1 spec and response shaping", () => {it("scopes an OAuth caller to the token's company only", () => {const none = { create: [], update: [], delete: [] };expect(@@ -128,29 +69,8 @@ describe("oRPC mechanics for the Carbon API v1 surface", () => {).toEqual({ parts_view: ["c1"] });});- it("emits the precomputed JSON Schema into the OpenAPI spec via the custom converter", async () => {- const generator = new OpenAPIGenerator({- schemaConverters: [new CarbonJsonSchemaConverter()]- });- const spec = (await generator.generate(router, {- info: { title: "Carbon API", version: "1.0.0" }- })) as {- paths?: Record<string, unknown>;- };- expect(Object.keys(spec.paths ?? {})).toContain("/demo/ping");- });-- it("emits the response schema into the spec's 200 body", async () => {- // Every procedure carries an `.output()`; for lists that is the- // `{ results, count }` envelope wrapping the schema reflected from the- // service's return type. Without the converter reaching the output side, the- // spec documents requests only — which is what it did before responses existed.- const generator = new OpenAPIGenerator({- schemaConverters: [new CarbonJsonSchemaConverter()]- });- const spec = (await generator.generate(router, {- info: { title: "Carbon API", version: "1.0.0" }- })) as any;+ it("emits a list's { results, count } envelope as the 200 body", async () => {+ const spec = await generateSpec();const body =spec.paths["/demo/ping"].post.responses["200"].content["application/json"]@@ -163,15 +83,9 @@ describe("oRPC mechanics for the Carbon API v1 surface", () => {});it("documents every refusal beside the 200 body", async () => {- const generator = new OpenAPIGenerator({- schemaConverters: [new CarbonJsonSchemaConverter()]- });- const spec = withErrorResponses(- (await generator.generate(router, {- info: { title: "Carbon API", version: "1.0.0" }- })) as any- ) as any;+ const spec = withErrorResponses(await generateSpec()) as any;const responses = spec.paths["/demo/ping"].post.responses;+expect(Object.keys(responses)).toEqual(expect.arrayContaining(["200",@@ -196,32 +110,24 @@ describe("oRPC mechanics for the Carbon API v1 surface", () => {});it("returns single results bare and lists in the { results, count } envelope", () => {- // Wrapping everything stacked our envelope under every generated client's own- // result wrapper (`res.data.data.field`). Single results are now the body- // itself; only lists carry the envelope, because `count` means something- // there. If either assertion fails, the published schema and the runtime- // shaping in buildProcedure's handler must change TOGETHER — both key off- // isListOperation.+ // Schema and runtime shaping both key off isListOperation; they must agree.const single = meta({responseSchema: { type: "object", properties: { id: { type: "string" } } }});+ const list = meta({+ responseSchema: { type: "array", items: { type: "object" } }+ });+expect(outputSchema(single)).toEqual({type: "object",properties: { id: { type: "string" } }});-- const list = meta({- responseSchema: { type: "array", items: { type: "object" } }- });const wrapped = outputSchema(list) as any;expect(wrapped.properties.results.type).toBe("array");expect(wrapped.properties.count.type).toEqual(["number", "null"]);expect(wrapped.required).toEqual(["results"]);-- // No reflected schema → bare and unconstrained, never a phantom envelope.expect(outputSchema(meta({ responseSchema: undefined }))).toEqual({});- // The runtime shaping keys off the SAME bit, so it cannot disagree.expect(shapeHttpBody(single, { data: { id: "x" } })).toEqual({ id: "x" });expect(shapeHttpBody(list, { data: [1], count: 7 })).toEqual({results: [1],@@ -233,23 +139,12 @@ describe("oRPC mechanics for the Carbon API v1 surface", () => {});});- it("declares exactly ONE auth scheme: Bearer", async () => {- // The server also accepts the internal `carbon-key` header as a compat alias- // (authenticate.server.ts), but the spec documents the ONE recommended way so- // every generated SDK has a single auth story. Adding a second scheme here- // would hand "either way" to every client generator — if that ever seems- // desirable again, it was tried and unified away on purpose.- const generator = new OpenAPIGenerator({- schemaConverters: [new CarbonJsonSchemaConverter()]- });- const spec = (await generator.generate(router, specOptions())) as any;+ it("declares Bearer as the only auth scheme", async () => {+ // The carbon-key header is a compat alias; generated SDKs get one auth story.+ const spec = await generateSpec();- expect(Object.keys(spec.components.securitySchemes)).toEqual([- "bearerAuth"- ]);- expect(spec.components.securitySchemes.bearerAuth).toMatchObject({- type: "http",- scheme: "bearer"+ expect(spec.components.securitySchemes).toEqual({+ bearerAuth: expect.objectContaining({ type: "http", scheme: "bearer" })});expect(spec.security).toEqual([{ bearerAuth: [] }]);});diff --git a/apps/erp/app/routes/api+/v1+/lib/service-fn.server.test.ts b/apps/erp/app/routes/api+/v1+/lib/service-fn.server.test.tsindex ab7037fb25..b836a81c47 100644--- a/apps/erp/app/routes/api+/v1+/lib/service-fn.server.test.ts+++ b/apps/erp/app/routes/api+/v1+/lib/service-fn.server.test.ts@@ -2,68 +2,37 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import type { ManifestEntry } from "@carbon/api";-import { describe, expect, it, vi } from "vitest";+import { defineServiceFn } from "@carbon/api/service-fn.server";+import { describe, expect, it } from "vitest";+import { z } from "zod";+import type { AuthedContext } from "./base.server";+import { callServiceFn } from "./service-fn.server";-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn(), warn: vi.fn() })-}));-vi.mock("@carbon/kv", () => ({ redis: {} }));-vi.mock("@carbon/auth/client.server", () => ({- getCarbonServiceRole: () => ({})-}));-vi.mock("~/services/database.server", () => ({- getDatabaseClient: () => ({})-}));-// A real service function stands in for the ERP router.-vi.mock("~/modules/router.server", async () => {- const { z } = await import("zod");- const { defineServiceFn } = await import("@carbon/api/service-fn.server");- return {- router: {- production: {- job: {- cancel: defineServiceFn({- input: z.object({ jobId: z.string() }),- permission: { update: "production" },- async run(ctx, { jobId }) {- if (jobId === "moved") {- return ctx.error("conflict", "The job's status changed");- }- return { jobId, actor: ctx.actor.type, by: ctx.auditUserId };- }- }),- // Records the filters an update on the caller's client carries.- touch: defineServiceFn({- input: z.object({ jobId: z.string() }),- permission: { update: "production" },- async run(ctx, { jobId }) {- const client = ctx.asCaller.supabase as unknown as {- from(table: string): {- update(row: object): { eq(c: string, v: string): unknown };- };- };- client.from("job").update({ name: "x" }).eq("id", jobId);- return { jobId };- }- })- }- }+const cancel = defineServiceFn({+ input: z.object({ jobId: z.string() }),+ permission: { update: "production" },+ async run(ctx, { jobId }) {+ if (jobId === "moved") {+ return ctx.error("conflict", "The job's status changed");}- };+ return { jobId, actor: ctx.actor.type, by: ctx.auditUserId };+ }});-import type { AuthedContext } from "./base.server";-import { runServiceFn } from "./service-fn.server";--const meta = {- name: "production_cancelJob",- serviceFn: { path: ["production", "job", "cancel"] }-} as ManifestEntry;+const list = defineServiceFn({+ input: z.object({}),+ permission: { view: "production" },+ async run(_ctx, _input) {+ return { rows: [{ id: "j1" }], count: 7 };+ }+});const caller = (authKind: AuthedContext["authKind"],- scopes: Record<string, string[]> = { production_update: ["c1"] }+ scopes: Record<string, string[]> = {+ production_update: ["c1"],+ production_view: ["c1"]+ }): AuthedContext => ({client: {} as AuthedContext["client"],userId: "u1",@@ -73,23 +42,33 @@ const caller = (scopes});-describe("runServiceFn", () => {- it("runs the function as the key, with its creator as the audit user", async () => {+const single = { paginates: false };++describe("callServiceFn", () => {+ it("runs an API key as the key, with its creator as the audit user", async () => {await expect(- runServiceFn(meta, caller("api-key"), { jobId: "j1" })+ callServiceFn(cancel, single, caller("api-key"), { jobId: "j1" })).resolves.toEqual({ data: { jobId: "j1", actor: "apiKey", by: "u1" } });});- it("runs an OAuth or workflow caller as its user", async () => {- const { data } = await runServiceFn(meta, caller("session"), {- jobId: "j1"- });- expect(data).toMatchObject({ actor: "user" });+ it.each(["oauth", "session"] as const)(+ "runs a %s caller as its user",+ async (kind) => {+ await expect(+ callServiceFn(cancel, single, caller(kind), { jobId: "j1" })+ ).resolves.toEqual({ data: { jobId: "j1", actor: "user", by: "u1" } });+ }+ );++ it("sends a list's rows as the data and its total beside them", async () => {+ await expect(+ callServiceFn(list, { paginates: true }, caller("api-key"), {})+ ).resolves.toEqual({ data: [{ id: "j1" }], count: 7 });});it("sends a refusal as its category's code and status", async () => {await expect(- runServiceFn(meta, caller("oauth"), { jobId: "moved" })+ callServiceFn(cancel, single, caller("oauth"), { jobId: "moved" })).rejects.toMatchObject({code: "CONFLICT",status: 409,@@ -98,28 +77,23 @@ describe("runServiceFn", () => {});});- it("refuses a caller whose scopes lack the function's permission", async () => {- await expect(- runServiceFn(meta, caller("api-key", { production_view: ["c1"] }), {- jobId: "j1"- })- ).rejects.toMatchObject({ code: "FORBIDDEN", status: 403 });- });-// RLS does not bound an OAuth connector or a workflow: a service function// can write through the direct connection, so its gate is the check.- it("refuses an OAuth or workflow caller whose user lacks the permission", async () => {- for (const kind of ["oauth", "session"] as const) {+ it.each<[AuthedContext["authKind"], Record<string, string[]>]>([+ ["api-key", { production_view: ["c1"] }],+ ["oauth", { production_update: ["c2"] }],+ ["session", { production_update: ["c2"] }]+ ])(+ "refuses a %s caller whose scopes lack the permission in this company",+ async (kind, scopes) => {await expect(- runServiceFn(meta, caller(kind, { production_update: ["c2"] }), {+ callServiceFn(cancel, single, caller(kind, scopes), {jobId: "j1"})).rejects.toMatchObject({ code: "FORBIDDEN", status: 403 });}- });-});+ );-describe("an API caller's client", () => {it("filters an update on a company table by the caller's company", async () => {const filters: [string, string][] = [];const builder = {@@ -129,18 +103,30 @@ describe("an API caller's client", () => {return builder;}};- const context = {- ...caller("session"),- client: { from: () => builder } as unknown as AuthedContext["client"]- };- await runServiceFn(+ const touch = defineServiceFn({+ input: z.object({ jobId: z.string() }),+ permission: { update: "production" },+ async run(ctx, { jobId }) {+ const client = ctx.asCaller.supabase as unknown as {+ from(table: string): {+ update(row: object): { eq(c: string, v: string): unknown };+ };+ };+ client.from("job").update({ name: "x" }).eq("id", jobId);+ return { jobId };+ }+ });++ await callServiceFn(+ touch,+ single,{- name: "production_job_touch",- serviceFn: { path: ["production", "job", "touch"] }- } as ManifestEntry,- context,+ ...caller("session"),+ client: { from: () => builder } as unknown as AuthedContext["client"]+ },{ jobId: "j1" });+expect(filters).toEqual([["companyId", "c1"],["id", "j1"]diff --git a/apps/erp/app/routes/api+/v1+/lib/service-fn.server.ts b/apps/erp/app/routes/api+/v1+/lib/service-fn.server.tsindex 2c87442abb..3681804c67 100644--- a/apps/erp/app/routes/api+/v1+/lib/service-fn.server.ts+++ b/apps/erp/app/routes/api+/v1+/lib/service-fn.server.ts@@ -67,7 +67,16 @@ export async function runServiceFn(context: AuthedContext,input: unknown): Promise<{ data: unknown; count?: number }> {- const fn = serviceFnAt(meta.serviceFn.path);+ return callServiceFn(serviceFnAt(meta.serviceFn.path), meta, context, input);+}++/** `runServiceFn` for a function already resolved from the router. */+export async function callServiceFn<I extends z.ZodType>(+ fn: ServiceFn<I, unknown>,+ meta: Pick<ManifestEntry, "paginates">,+ context: AuthedContext,+ input: z.input<I>+): Promise<{ data: unknown; count?: number }> {const result = await fn(contextFromAuthed(context), input);if (result.error) {const { category, message, status } = result.error;diff --git a/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.test.ts b/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.test.tsindex f5a3bb7388..7f9db55743 100644--- a/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.test.ts+++ b/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.test.ts@@ -8,22 +8,21 @@ import { beforeEach, describe, expect, it, vi } from "vitest";const SECRET = "00112233445566778899aabbccddeeff";const TIMESTAMP = 1_726_070_400;-vi.mock("@carbon/auth/client.server", () => ({- getCarbonServiceRole: () => ({})-}));-vi.mock("@carbon/ee", () => ({+// The installed integration row getIntegration reads; its secrets come from the vault stub.+const integrationRow = { metadata: {}, secretRef: "secret-ref" };+vi.mock("@carbon/auth/client.server", () => {+ const query = {+ select: () => query,+ eq: () => query,+ maybeSingle: async () => ({ data: integrationRow, error: null })+ };+ return { getCarbonServiceRole: () => ({ from: () => query }) };+});+vi.mock("@carbon/ee", async (importOriginal) => ({+ ...(await importOriginal<object>()),resolveIntegrationSecrets: () => ({ apiKey: "api-key", secretKey: SECRET })}));vi.mock("@carbon/jobs", () => ({ trigger: vi.fn() }));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ info: vi.fn(), error: vi.fn(), warning: vi.fn() })-}));-vi.mock("~/modules/settings/settings.service", () => ({- getIntegration: () => ({- data: { metadata: {}, secretRef: "secret-ref" },- error: null- })-}));import { trigger } from "@carbon/jobs";import { action } from "./webhook.paperless-parts.$companyId";diff --git a/apps/erp/app/routes/x+/invoicing+/charges.$id.test.ts b/apps/erp/app/routes/x+/invoicing+/charges.$id.test.tsindex 4c5bf7a5f7..fd0743b479 100644--- a/apps/erp/app/routes/x+/invoicing+/charges.$id.test.ts+++ b/apps/erp/app/routes/x+/invoicing+/charges.$id.test.ts@@ -2,178 +2,55 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { requirePermissions } from "@carbon/auth/auth.server";import type { Database } from "@carbon/database";import { createClient } from "@supabase/supabase-js";-import { beforeEach, describe, expect, it, vi } from "vitest";--const requirePermissions = vi.hoisted(() => vi.fn());-const getCharge = vi.hoisted(() => vi.fn());-const flash = vi.hoisted(() => vi.fn(async () => ({})));-const EmptyComponent = vi.hoisted(() => () => null);--vi.mock("@carbon/auth", () => ({- error: (cause: unknown, message: string) => ({ cause, message }),- // Transitively imported (~/modules/settings reads it at module load to build- // PUBLIC_STORAGE_URL_PREFIX); the mock must export it or the module errors.- SUPABASE_URL: "https://example.supabase.co"-}));-vi.mock("@carbon/auth/auth.server", () => ({ requirePermissions }));-vi.mock("@carbon/auth/session.server", () => ({ flash }));-vi.mock("@carbon/react", () => ({- Button: EmptyComponent,- Drawer: EmptyComponent,- DrawerBody: EmptyComponent,- DrawerContent: EmptyComponent,- DrawerFooter: EmptyComponent,- DrawerHeader: EmptyComponent,- DrawerTitle: EmptyComponent,- HStack: EmptyComponent,- Table: EmptyComponent,- Tbody: EmptyComponent,- Td: EmptyComponent,- Th: EmptyComponent,- Thead: EmptyComponent,- Tr: EmptyComponent,- useDisclosure: vi.fn(),- VStack: EmptyComponent-}));-vi.mock("@lingui/react/macro", () => ({- Trans: EmptyComponent,- useLingui: vi.fn()-}));-vi.mock("@react-aria/i18n", () => ({ useLocale: vi.fn() }));-vi.mock("~/components/Enumerable", () => ({ Enumerable: EmptyComponent }));-vi.mock("~/components/Modals", () => ({ Confirm: EmptyComponent }));-// The route imports only Hyperlink from the ~/components barrel; mock the barrel-// so its unrelated exports (which pull in msg`` from @lingui/core/macro, etc.)-// don't have to be satisfied one transitive dep at a time.-vi.mock("~/components", () => ({ Hyperlink: EmptyComponent }));-vi.mock("~/hooks", () => ({- useCurrencyFormatter: vi.fn(),- usePermissions: vi.fn()-}));-vi.mock("~/modules/accounting/ui/JournalEntries", () => ({- JournalEntryStatus: EmptyComponent-}));-vi.mock("~/modules/invoicing/ui", () => ({ ChargeStatus: EmptyComponent }));-vi.mock("~/modules/invoicing/invoicing.service", () => ({ getCharge }));-vi.mock("~/utils/path", () => ({- path: {- to: {- charges: "/x/invoicing/charges",- chargeVoid: (id: string) => `/x/invoicing/charges/${id}/void`,- file: { previewFile: (value: string) => value }- }- }-}));-+import { expect, it, vi } from "vitest";import { loader } from "./charges.$id";-type FailingTable = "account" | "document" | null;+vi.mock("@carbon/auth/auth.server", () => ({ requirePermissions: vi.fn() }));+vi.mock("@carbon/auth/session.server", () => ({ flash: async () => ({}) }));-function clientFor(failingTable: FailingTable = null) {- const requests: URL[] = [];- const client = createClient<Database>("http://card-detail.test", "key", {+// PostgREST answered over a stubbed fetch: one table fails, the rest succeed.+function clientFailing(failingTable: string) {+ return createClient<Database>("http://charge.test", "key", {auth: { persistSession: false, autoRefreshToken: false },global: {fetch: async (input) => {- const url = new URL(String(input));- requests.push(url);- const table = url.pathname.split("/").at(-1);+ const table = new URL(String(input)).pathname.split("/").at(-1);if (table === failingTable) {- return Response.json(- { message: `${table} lookup failed`, code: "XX000" },- { status: 500 }- );+ return Response.json({ message: "lookup failed" }, { status: 500 });}- if (table === "account") {- return Response.json([- { id: "card-account", number: "2100", name: "Card Liability" },- { id: "expense-account", number: "6100", name: "Travel" }- ]);- }- if (table === "document") {- return Response.json([- {- id: "receipt-1",- name: "receipt.pdf",- path: "company-a/charge/card-1/receipt.pdf"- }- ]);+ if (table === "charge") {+ return Response.json({+ id: "card-1",+ cardAccountId: "card-account",+ offsetAccountId: null,+ journalId: null,+ chargeLine: [{ id: "line-1", accountId: "expense-account" }]+ });}return Response.json([]);}}});- return { client, requests };}-async function runLoader(client: ReturnType<typeof clientFor>["client"]) {- requirePermissions.mockResolvedValue({- client,- companyId: "company-a",- companyGroupId: "group-a"- });- return loader({- request: new Request("http://localhost/x/invoicing/charges/card-1"),- params: { id: "card-1" },- context: {}- } as never);-}--describe("charge detail loader", () => {- beforeEach(() => {- vi.clearAllMocks();- getCharge.mockResolvedValue({- data: {- id: "card-1",- companyId: "company-a",- cardAccountId: "card-account",- offsetAccountId: null,- chargeLine: [{ id: "line-1", accountId: "expense-account" }]- },- error: null- });- });-- it("scopes the primary, account, and document reads to their tenant owner", async () => {- const { client, requests } = clientFor();-- const result = await runLoader(client);-- expect(getCharge).toHaveBeenCalledWith(client, "company-a", "card-1");- const accountRequest = requests.find((url) =>- url.pathname.endsWith("/account")- );- expect(accountRequest?.searchParams.get("companyGroupId")).toBe(- "eq.group-a"- );- expect(accountRequest?.searchParams.has("companyId")).toBe(false);- const documentRequest = requests.find((url) =>- url.pathname.endsWith("/document")- );- expect(documentRequest?.searchParams.get("companyId")).toBe("eq.company-a");- expect(result.accountsById["expense-account"]).toMatchObject({- number: "6100",- name: "Travel"- });- expect(result.receipts).toHaveLength(1);- });-- it.each(["account", "document"] as const)(- "fails closed when the %s auxiliary read fails",- async (table) => {- const { client } = clientFor(table);-- await expect(runLoader(client)).rejects.toMatchObject({ status: 302 });-- expect(flash).toHaveBeenCalledWith(- expect.any(Request),- expect.objectContaining({- cause: expect.objectContaining({ message: `${table} lookup failed` }),- message: "Failed to load charge"- })- );- }- );-});+it.each(["account", "document"])(+ "redirects instead of rendering a partial charge when the %s read fails",+ async (table) => {+ vi.mocked(requirePermissions).mockResolvedValue({+ client: clientFailing(table),+ companyId: "company-a",+ companyGroupId: "group-a"+ } as Awaited<ReturnType<typeof requirePermissions>>);++ await expect(+ loader({+ request: new Request("http://localhost/x/invoicing/charges/card-1"),+ params: { id: "card-1" },+ context: {}+ } as unknown as Parameters<typeof loader>[0])+ ).rejects.toMatchObject({ status: 302 });+ }+);diff --git a/apps/erp/app/routes/x+/reports+/balance-sheet.test.ts b/apps/erp/app/routes/x+/reports+/balance-sheet.test.tsdeleted file mode 100644index 48c176e31f..0000000000--- a/apps/erp/app/routes/x+/reports+/balance-sheet.test.ts+++ /dev/null@@ -1,596 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { requirePermissions } from "@carbon/auth/auth.server";-import { getCarbonServiceRole } from "@carbon/auth/client.server";-import { flash } from "@carbon/auth/session.server";-import type { Database } from "@carbon/database";-import type { SupabaseClient } from "@supabase/supabase-js";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import {- getCompaniesInGroup,- getConsolidatedPeriodSeriesForReport,- getFinancialStatementBalances,- getFinancialStatementPeriodSeries,- getFiscalYearSettings-} from "~/modules/accounting/accounting.service";-import type { ChartPeriodSeries } from "~/modules/accounting/types";-import { NET_INCOME_ACCOUNT_ID } from "~/modules/accounting/types";-import { exportPeriodReport } from "~/modules/accounting/ui/Reports/exportReport";-import { loader } from "./balance-sheet";-import { loader as incomeStatementLoader } from "./income-statement";-import { loader as trialBalanceLoader } from "./trial-balance";--vi.mock("@carbon/auth", async (importOriginal) => ({- ...(await importOriginal<object>()),- error: (cause: unknown, message: string) => ({- cause,- message,- success: false- }),- getAppUrl: () => "http://localhost",- getMESUrl: () => "http://localhost",- CARBON_API_URL: "http://localhost"-}));-vi.mock("@carbon/auth/auth.server", () => ({ requirePermissions: vi.fn() }));-vi.mock("@carbon/auth/session.server", () => ({- flash: vi.fn(async () => ({}))-}));-vi.mock("@carbon/react", () => ({ VStack: () => null }));-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("~/modules/settings/settings.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- getNextSequence: vi.fn()-}));-vi.mock("@carbon/content/glossary", () => ({- getDefinitionText: () => "",- getEntry: () => undefined,- getTermText: () => "",- glossaryEntries: () => [],- hasEntry: () => false,- listEntries: () => [],- lookupEntry: () => undefined,- termSlug: (term: string) => term,- terms: {}-}));-vi.mock("~/modules/shared/shared.models", async (importOriginal) => ({- ...(await importOriginal<object>()),- months: [- "January",- "February",- "March",- "April",- "May",- "June",- "July",- "August",- "September",- "October",- "November",- "December"- ]-}));-vi.mock("~/modules/shared/shared.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- getCompanyTimeZone: vi.fn(async () => "America/New_York")-}));-vi.mock("~/modules/accounting/accounting.service", async (actual) => ({- ...(await actual<object>()),- getCompaniesInGroup: vi.fn(),- getFinancialStatementPeriodSeries: vi.fn(),- getFinancialStatementBalances: vi.fn(),- getFiscalYearSettings: vi.fn(),- getConsolidatedPeriodSeriesForReport: vi.fn()-}));-// accounting.server's operations reach these modules; no report uses them.-vi.mock("~/modules/sales/sales.service", () => ({}));-vi.mock("~/modules/purchasing/purchasing.service", () => ({}));--vi.mock("@carbon/auth/client.server", () => ({- getCarbonServiceRole: vi.fn()-}));-vi.mock("~/modules/accounting/ui/Reports", () => ({- exportPeriodReport: vi.fn(),- getPeriodColumnLabel: vi.fn(),- MultiPeriodStatementTree: () => null,- ReportFilters: () => null-}));--const keys = ["2026-07", "2026-08"];-const companies = [- {- id: "parent",- name: "Parent",- baseCurrencyCode: "USD",- parentCompanyId: null,- timezone: "America/New_York",- isEliminationEntity: false- },- {- id: "child",- name: "Child",- baseCurrencyCode: "EUR",- parentCompanyId: "parent",- timezone: "Europe/Berlin",- isEliminationEntity: false- }-];--function account(- id: string,- parentId: string | null,- accountClass: ChartPeriodSeries["class"],- amounts: number[],- extra: Partial<ChartPeriodSeries> = {}-): ChartPeriodSeries {- return {- id,- parentId,- class: accountClass,- name: id,- number: null,- active: true,- companyGroupId: "group",- isGroup: false,- isSystem: false,- incomeBalance: "Balance Sheet",- accountType: "Equity - No Close",- consolidatedRate: "Current",- createdAt: "2026-01-01T00:00:00Z",- createdBy: "user",- updatedAt: null,- updatedBy: null,- customFields: {},- tags: null,- periods: Object.fromEntries(- keys.map((key, index) => [- key,- {- balanceAtDate: 0,- netChange: 0,- translatedBalance: amounts[index] ?? 0,- translatedNetChange: amounts[index] ?? 0- }- ])- ),- ...extra- };-}--function chart(bookedCta = 0): ChartPeriodSeries[] {- return [- account("balance-sheet", null, "Asset", [40, 20], {- isGroup: true,- isSystem: true- }),- account(- "assets",- "balance-sheet",- "Asset",- [160 + bookedCta, 80 + bookedCta],- { isGroup: true }- ),- account("cash", "assets", "Asset", [160 + bookedCta, 80 + bookedCta]),- account(- "equity",- "balance-sheet",- "Equity",- [120 + bookedCta, 60 + bookedCta],- { isGroup: true }- ),- account("reserves", "equity", "Equity", [bookedCta, bookedCta], {- isGroup: true- }),- account("custom-cta", "reserves", "Equity", [bookedCta, bookedCta], {- name: "FX Reserve Renamed",- number: "3999"- }),- account("child-cta", "reserves", "Equity", [0, 0], { number: "3200" }),- account(NET_INCOME_ACCOUNT_ID, "equity", "Equity", [120, 60]),- account("income-statement", null, "Revenue", [120, 60], {- incomeBalance: "Income Statement",- isGroup: true,- isSystem: true- }),- account("sales", "income-statement", "Revenue", [150, 75], {- incomeBalance: "Income Statement"- }),- account("expense", "income-statement", "Expense", [30, 15], {- incomeBalance: "Income Statement"- })- ];-}--let sourceChart: ChartPeriodSeries[];-let defaults: Record<string, string | null>;-let defaultError: { message: string } | null;-let rootGroup: string;-let rootParent: string | null;-let client: SupabaseClient<Database>;-let reads: Array<{ table: string; filters: Record<string, unknown> }>;--beforeEach(() => {- vi.clearAllMocks();- sourceChart = chart();- defaults = { parent: "custom-cta", child: "child-cta" };- defaultError = null;- rootGroup = "group";- rootParent = null;- reads = [];- client = {- from(table: string) {- const filters: Record<string, unknown> = {};- const builder = {- select: () => builder,- eq: (field: string, value: unknown) => {- filters[field] = value;- return builder;- },- is: (field: string, value: unknown) => {- filters[field] = value;- return builder;- },- single: async () => {- reads.push({ table, filters: { ...filters } });- if (table === "company") {- const row = {- id: "parent",- companyGroupId: rootGroup,- parentCompanyId: rootParent- };- const visible = Object.entries(filters).every(- ([key, value]) => row[key as keyof typeof row] === value- );- return {- data: visible ? { id: row.id } : null,- error: visible- ? null- : { message: "Root company is not in the authorized group" }- };- }- if (table === "accountDefault") {- return {- data: {- currencyTranslationAccount: defaults[String(filters.companyId)]- },- error: defaultError- };- }- if (table === "account") {- const data =- sourceChart.find(- (row) =>- row.id === filters.id &&- row.companyGroupId === filters.companyGroupId- ) ?? null;- return { data, error: null };- }- throw new Error(`Unexpected table ${table}`);- }- };- return builder;- }- } as unknown as SupabaseClient<Database>;- vi.mocked(requirePermissions).mockResolvedValue({- client,- companyId: "child",- companyGroupId: "group",- userId: "user"- } as Awaited<ReturnType<typeof requirePermissions>>);- vi.mocked(getCompaniesInGroup).mockResolvedValue({- data: companies,- error: null- } as Awaited<ReturnType<typeof getCompaniesInGroup>>);- vi.mocked(getFiscalYearSettings).mockResolvedValue({- data: { startMonth: "January" },- error: null- } as Awaited<ReturnType<typeof getFiscalYearSettings>>);- vi.mocked(getFinancialStatementBalances).mockResolvedValue({- data: [],- error: null- });- vi.mocked(getFinancialStatementPeriodSeries).mockImplementation(async () => ({- data: sourceChart,- ctaByBucket: { "2026-07": 40, "2026-08": 20 },- error: null- }));- vi.mocked(getConsolidatedPeriodSeriesForReport).mockImplementation(- async () => ({- data: sourceChart,- ctaByBucket: { "2026-07": 40, "2026-08": 20 },- error: null- })- );-});--afterEach(() => vi.unstubAllGlobals());--function runLoader(- companiesParam = "all",- showTranslated = true,- headers?: HeadersInit-) {- const params = new URLSearchParams({- companies: companiesParam,- showTranslated: String(showTranslated),- startDate: "2026-07-01",- endDate: "2026-08-31"- });- return loader({- request: new Request(`http://localhost/x/reports/balance-sheet?${params}`, {- headers- }),- params: {},- context: {}- } as Parameters<typeof loader>[0]);-}--function amount(rows: ChartPeriodSeries[], id: string, key = "2026-07") {- return rows.find((row) => row.id === id)?.periods[key]?.translatedBalance;-}--describe("balance sheet configured CTA", () => {- it("translates a subsidiary for an accountant who cannot read parent defaults", async () => {- const deniedClient = {- from: () => ({- select() {- return this;- },- eq() {- return this;- },- single: async () => ({- data: null,- error: { message: "Parent defaults are not visible" }- })- })- } as unknown as SupabaseClient<Database>;- vi.mocked(requirePermissions).mockImplementation(- async (_request, permissions) =>- ({- client: permissions.bypassRls ? client : deniedClient,- companyId: "child",- companyGroupId: "group",- userId: "user"- }) as Awaited<ReturnType<typeof requirePermissions>>- );- const result = await runLoader("child");- expect(amount(result.balanceSheet, "custom-cta")).toBe(40);- expect(amount(result.balanceSheet, "balance-sheet")).toBe(0);- expect(reads).toContainEqual({- table: "company",- filters: { id: "parent", companyGroupId: "group", parentCompanyId: null }- });- });-- it.each(["cross-group", "non-root"])(- "refuses %s configuration before reading defaults",- async (caseName) => {- if (caseName === "cross-group") rootGroup = "other-group";- else rootParent = "another-parent";- await expect(runLoader("child")).rejects.toMatchObject({ status: 302 });- expect(reads.some((read) => read.table === "accountDefault")).toBe(false);- }- );-- it("does not escalate an API key when auth returns an RLS client", async () => {- defaultError = {- message: "Parent defaults are not visible to this API key"- };- await expect(- runLoader("child", true, { "carbon-key": "test-report-key" })- ).rejects.toMatchObject({ status: 302 });- expect(getCarbonServiceRole).not.toHaveBeenCalled();- });-- it("does not read root configuration after permission denial", async () => {- vi.mocked(requirePermissions).mockRejectedValue(- new Response("Forbidden", { status: 403 })- );- await expect(runLoader("child")).rejects.toMatchObject({ status: 403 });- expect(reads).toEqual([]);- });-- it.each(["all", "child"])(- "uses the reporting parent's renamed account and recomputes every total for %s",- async (companySelection) => {- const result = await runLoader(companySelection);- expect(amount(result.balanceSheet, "custom-cta")).toBe(40);- expect(amount(result.balanceSheet, "child-cta")).toBe(0);- expect(amount(result.balanceSheet, "reserves")).toBe(40);- expect(amount(result.balanceSheet, "equity")).toBe(160);- expect(amount(result.balanceSheet, "balance-sheet")).toBe(0);- expect(amount(result.balanceSheet, "equity", "2026-08")).toBe(80);- expect(amount(result.balanceSheet, "balance-sheet", "2026-08")).toBe(0);- expect(reads).toContainEqual({- table: "accountDefault",- filters: { companyId: "parent" }- });- }- );-- it("fills single-company translated synthetic income from the full income statement", async () => {- const income = sourceChart.find((row) => row.id === NET_INCOME_ACCOUNT_ID)!;- for (const key of keys) {- income.periods[key] = { netChange: 80, balanceAtDate: 80 };- }- const result = await runLoader("child");- expect(amount(result.balanceSheet, NET_INCOME_ACCOUNT_ID)).toBe(120);- expect(amount(result.balanceSheet, "equity")).toBe(160);- expect(amount(result.balanceSheet, "balance-sheet")).toBe(0);- });-- it("preserves booked CTA and repeated calculations do not mutate the input chart", async () => {- sourceChart = chart(10);- const original = structuredClone(sourceChart);- const first = await runLoader();- const second = await runLoader();- expect(amount(first.balanceSheet, "custom-cta")).toBe(50);- expect(amount(first.balanceSheet, "equity")).toBe(170);- expect(amount(first.balanceSheet, "balance-sheet")).toBe(0);- expect(second.balanceSheet).toEqual(first.balanceSheet);- expect(sourceChart).toEqual(original);- });-- it.each([- {- label: "missing default",- change: () => {- defaults.parent = null;- }- },- {- label: "missing chart account",- change: () => {- defaults.parent = "missing";- }- },- {- label: "inactive",- change: () => {- sourceChart.find((row) => row.id === "custom-cta")!.active = false;- }- },- {- label: "group",- change: () => {- sourceChart.find((row) => row.id === "custom-cta")!.isGroup = true;- }- },- {- label: "wrong class",- change: () => {- sourceChart.find((row) => row.id === "custom-cta")!.class = "Revenue";- }- },- {- label: "wrong statement",- change: () => {- sourceChart.find((row) => row.id === "custom-cta")!.incomeBalance =- "Income Statement";- }- },- {- label: "other company group",- change: () => {- sourceChart.find((row) => row.id === "custom-cta")!.companyGroupId =- "other-group";- }- },- {- label: "missing period cell",- change: () => {- delete sourceChart.find((row) => row.id === "custom-cta")!.periods[- "2026-08"- ];- }- },- {- label: "default lookup failure",- change: () => {- defaultError = { message: "Default lookup failed" };- }- }- ])(- "refuses $label without returning a partial report",- async ({ change }) => {- change();- await expect(runLoader()).rejects.toMatchObject({ status: 302 });- expect(flash).toHaveBeenCalledWith(- expect.any(Request),- expect.objectContaining({ success: false })- );- }- );-- it("propagates a subsidiary error before applying CTA", async () => {- vi.mocked(getConsolidatedPeriodSeriesForReport).mockResolvedValue({- data: null,- ctaByBucket: {},- error: "Source balances do not balance"- });- await expect(runLoader()).rejects.toMatchObject({ status: 302 });- expect(reads).toEqual([]);- });-- it("preserves the untranslated report without resolving CTA defaults", async () => {- const original = structuredClone(sourceChart);- const result = await runLoader("child", false);- expect(result.showTranslated).toBe(false);- expect(sourceChart).toEqual(original);- expect(reads).toEqual([]);- });-- it("exports the corrected leaf, intermediate equity group, and root values", async () => {- const result = await runLoader();- let downloaded: Blob | undefined;- // downloadBlob (@carbon/files) uses the bare URL global, not window.URL.- vi.stubGlobal("URL", {- createObjectURL: (blob: Blob) => {- downloaded = blob;- return "blob:report";- },- revokeObjectURL: vi.fn()- });- vi.stubGlobal("document", {- createElement: () => ({ click: vi.fn() }),- body: { appendChild: vi.fn(), removeChild: vi.fn() }- });- exportPeriodReport({- accounts: result.balanceSheet,- periods: result.periods.map((bucket) => ({- ...bucket,- label: bucket.key- })),- measure: "balanceAtDate",- showTranslated: true,- search: "",- filename: "balance-sheet.csv"- });- const csv = await downloaded?.text();- expect(csv).toContain("3999,FX Reserve Renamed,40,20");- expect(csv).toContain(",reserves,40,20");- expect(csv).toContain(",equity,160,80");- expect(csv).toContain(",balance-sheet,0,0");- });-});--describe.each([- ["balance sheet", loader],- ["income statement", incomeStatementLoader],- ["trial balance", trialBalanceLoader]-] as const)("%s company selection", (_name, reportLoader) => {- it("rejects an unrelated company before reading ledger balances", async () => {- const request = new Request(- "http://localhost/x/reports/balance-sheet?companies=unrelated&startDate=2026-07-01&endDate=2026-08-31"- );- await expect(- reportLoader({ request, params: {}, context: {} } as Parameters<- typeof reportLoader- >[0])- ).rejects.toMatchObject({ status: 404 });- expect(getFinancialStatementPeriodSeries).not.toHaveBeenCalled();- expect(getConsolidatedPeriodSeriesForReport).not.toHaveBeenCalled();- expect(reads).toEqual([]);- });-- it("refuses a company-list lookup failure instead of reporting empty balances", async () => {- vi.mocked(getCompaniesInGroup).mockResolvedValue({- data: null,- error: { message: "Company lookup failed" }- } as unknown as Awaited<ReturnType<typeof getCompaniesInGroup>>);- const request = new Request(- "http://localhost/x/reports/balance-sheet?companies=all&startDate=2026-07-01&endDate=2026-08-31"- );- await expect(- reportLoader({ request, params: {}, context: {} } as Parameters<- typeof reportLoader- >[0])- ).rejects.toMatchObject({ status: 302 });- expect(getFinancialStatementPeriodSeries).not.toHaveBeenCalled();- expect(getConsolidatedPeriodSeriesForReport).not.toHaveBeenCalled();- });-});diff --git a/apps/erp/app/routes/x+/reports+/balance-sheet.tsx b/apps/erp/app/routes/x+/reports+/balance-sheet.tsxindex 3dc7917cd5..717b9f386a 100644--- a/apps/erp/app/routes/x+/reports+/balance-sheet.tsx+++ b/apps/erp/app/routes/x+/reports+/balance-sheet.tsx@@ -25,6 +25,7 @@ import {getFinancialStatementPeriodSeries,getFiscalYearSettings} from "~/modules/accounting/accounting.service";+import { selectReportCompanyIds } from "~/modules/accounting/accounting.utils";import {exportPeriodReport,getPeriodColumnLabel,@@ -89,18 +90,12 @@ export async function loader({ request }: LoaderFunctionArgs) {const parentCompany = companiesList.find((c) => !c.parentCompanyId);const parentCurrency = parentCompany?.baseCurrencyCode ?? null;- const selectedCompanyIds =- companiesParam === "all"- ? companiesList.map((c) => c.id)- : companiesParam- ? [companiesParam]- : [companyId];- if (- selectedCompanyIds.length === 0 ||- selectedCompanyIds.some(- (id) => !companiesList.some((company) => company.id === id)- )- ) {+ const selectedCompanyIds = selectReportCompanyIds(+ companiesParam,+ companiesList.map((c) => c.id),+ companyId+ );+ if (!selectedCompanyIds) {throw new Response("Company not found", { status: 404 });}const isMultiCompany = selectedCompanyIds.length > 1;diff --git a/apps/erp/app/routes/x+/reports+/income-statement.tsx b/apps/erp/app/routes/x+/reports+/income-statement.tsxindex 029439ba1c..5ad38faa9e 100644--- a/apps/erp/app/routes/x+/reports+/income-statement.tsx+++ b/apps/erp/app/routes/x+/reports+/income-statement.tsx@@ -24,6 +24,7 @@ import {getFinancialStatementPeriodSeries,getFiscalYearSettings} from "~/modules/accounting/accounting.service";+import { selectReportCompanyIds } from "~/modules/accounting/accounting.utils";import {exportPeriodReport,getPeriodColumnLabel,@@ -88,18 +89,12 @@ export async function loader({ request }: LoaderFunctionArgs) {const parentCompany = companiesList.find((c) => !c.parentCompanyId);const parentCurrency = parentCompany?.baseCurrencyCode ?? null;- const selectedCompanyIds =- companiesParam === "all"- ? companiesList.map((c) => c.id)- : companiesParam- ? [companiesParam]- : [companyId];- if (- selectedCompanyIds.length === 0 ||- selectedCompanyIds.some(- (id) => !companiesList.some((company) => company.id === id)- )- ) {+ const selectedCompanyIds = selectReportCompanyIds(+ companiesParam,+ companiesList.map((c) => c.id),+ companyId+ );+ if (!selectedCompanyIds) {throw new Response("Company not found", { status: 404 });}const isMultiCompany = selectedCompanyIds.length > 1;diff --git a/apps/erp/app/routes/x+/reports+/trial-balance.tsx b/apps/erp/app/routes/x+/reports+/trial-balance.tsxindex 108653e8e8..aa9861b889 100644--- a/apps/erp/app/routes/x+/reports+/trial-balance.tsx+++ b/apps/erp/app/routes/x+/reports+/trial-balance.tsx@@ -19,6 +19,7 @@ import {getFiscalYearSettings,translateCompanyBalances} from "~/modules/accounting/accounting.service";+import { selectReportCompanyIds } from "~/modules/accounting/accounting.utils";import type { Chart } from "~/modules/accounting/types";import {exportTrialBalance,@@ -82,18 +83,12 @@ export async function loader({ request }: LoaderFunctionArgs) {const parentCompany = companiesList.find((c) => !c.parentCompanyId);const parentCurrency = parentCompany?.baseCurrencyCode ?? null;- const selectedCompanyIds =- companiesParam === "all"- ? companiesList.map((c) => c.id)- : companiesParam- ? [companiesParam]- : [companyId];- if (- selectedCompanyIds.length === 0 ||- selectedCompanyIds.some(- (id) => !companiesList.some((company) => company.id === id)- )- ) {+ const selectedCompanyIds = selectReportCompanyIds(+ companiesParam,+ companiesList.map((c) => c.id),+ companyId+ );+ if (!selectedCompanyIds) {throw new Response("Company not found", { status: 404 });}const isMultiCompany = selectedCompanyIds.length > 1;diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.invoice-summary.test.ts b/apps/erp/app/routes/x+/sales-order+/$orderId.invoice-summary.test.tsdeleted file mode 100644index bb4c791b5b..0000000000--- a/apps/erp/app/routes/x+/sales-order+/$orderId.invoice-summary.test.ts+++ /dev/null@@ -1,201 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { requirePermissions } from "@carbon/auth/auth.server";-import { getCarbonServiceRole } from "@carbon/auth/client.server";-import { beforeEach, describe, expect, it, vi } from "vitest";-import * as sales from "~/modules/sales/sales.service";-import { getCompanySettings } from "~/modules/settings/settings.service";-import { loader } from "./$orderId";--vi.mock("@carbon/auth", () => ({- error: (cause: unknown, message: string) => ({ cause, message })-}));-vi.mock("@carbon/auth/auth.server", () => ({ requirePermissions: vi.fn() }));-vi.mock("@carbon/auth/client.server", () => ({- getCarbonServiceRole: vi.fn()-}));-vi.mock("@carbon/auth/session.server", () => ({- flash: vi.fn(async () => ({}))-}));-vi.mock("@carbon/react", () => ({ VStack: () => null }));-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("~/components/Layout/Panels", () => ({- PanelProvider: () => null,- ResizablePanels: () => null-}));-vi.mock("~/modules/sales/ui/SalesOrder", () => ({- SalesOrderExplorer: () => null,- SalesOrderHeader: () => null,- SalesOrderProperties: () => null-}));-vi.mock("~/modules/settings/settings.service", () => ({- getCompanySettings: vi.fn()-}));-vi.mock("~/utils/handle", () => ({- detailBreadcrumb: () => undefined-}));-vi.mock("~/utils/path", () => ({- path: {- to: {- items: "/x/items",- salesOrders: "/x/sales-orders",- salesOrder: (id: string) => `/x/sales-order/${id}`- }- }-}));-vi.mock("~/modules/sales/sales.service", () => ({- getCustomer: vi.fn(),- getOpportunity: vi.fn(),- getOpportunityDocuments: vi.fn(),- getQuote: vi.fn(),- getSalesOrder: vi.fn(),- getSalesOrderInvoiceLines: vi.fn(),- getSalesOrderInvoicePaymentsByIds: vi.fn(),- getSalesOrderInvoicesByIds: vi.fn(),- getSalesOrderLines: vi.fn(),- getSalesOrderRelatedItems: vi.fn()-}));--const getSalesOrderInvoicePaymentsByIds = vi.mocked(- sales.getSalesOrderInvoicePaymentsByIds-);--beforeEach(() => {- vi.clearAllMocks();- vi.mocked(requirePermissions).mockResolvedValue({- client: {},- companyId: "company-1"- } as Awaited<ReturnType<typeof requirePermissions>>);- vi.mocked(getCarbonServiceRole).mockReturnValue({} as never);- vi.mocked(sales.getSalesOrder).mockResolvedValue({- data: {- id: "order-1",- companyId: "company-1",- opportunityId: "opportunity-1",- customerId: "customer-1",- currencyCode: "USD"- },- error: null- } as never);- vi.mocked(sales.getSalesOrderLines).mockResolvedValue({- data: [],- error: null- } as never);- vi.mocked(sales.getOpportunity).mockResolvedValue({- data: { id: "opportunity-1", quotes: [] },- error: null- } as never);- vi.mocked(sales.getCustomer).mockResolvedValue({- data: { defaultCc: [] },- error: null- } as never);- vi.mocked(getCompanySettings).mockResolvedValue({- data: { defaultCustomerCc: [] },- error: null- } as never);- vi.mocked(sales.getSalesOrderInvoiceLines).mockResolvedValue({- data: [{ invoiceId: "invoice-1" }],- error: null- } as never);- vi.mocked(sales.getSalesOrderInvoicesByIds).mockResolvedValue({- data: [- {- id: "invoice-1",- invoiceTotal: 100,- balance: 0,- status: "Paid",- currencyCode: "USD",- exchangeRate: 1- }- ],- error: null- } as never);- getSalesOrderInvoicePaymentsByIds.mockResolvedValue({- data: [- {- targetSalesInvoiceId: "invoice-1",- appliedAmount: 75,- payment: { status: "Posted" }- }- ],- count: 1,- error: null- });- vi.mocked(sales.getOpportunityDocuments).mockResolvedValue({- data: [],- error: null- } as never);- vi.mocked(sales.getSalesOrderRelatedItems).mockResolvedValue({- data: [],- error: null- } as never);-});--describe("sales order invoice summary", () => {- it("counts applied payment principal instead of discounts and write-offs", async () => {- const result = await loader({- request: new Request("http://localhost/x/sales-order/order-1"),- params: { orderId: "order-1" },- context: {}- } as unknown as Parameters<typeof loader>[0]);-- expect(result.invoiceSummary).toEqual({- invoicedAmount: 100,- paidAmount: 75,- currencyMismatchCount: 0- });- });-- it("returns invoice and payment totals in the order currency", async () => {- vi.mocked(sales.getSalesOrder).mockResolvedValue({- data: {- id: "order-1",- companyId: "company-1",- opportunityId: "opportunity-1",- customerId: "customer-1",- currencyCode: "EUR"- },- error: null- } as never);- vi.mocked(sales.getSalesOrderInvoicesByIds).mockResolvedValue({- data: [- {- id: "invoice-1",- invoiceTotal: 100,- balance: 50,- status: "Partially Paid",- currencyCode: "EUR",- exchangeRate: 0.8- }- ],- error: null- } as never);- getSalesOrderInvoicePaymentsByIds.mockResolvedValue({- data: [- {- targetSalesInvoiceId: "invoice-1",- appliedAmount: 50,- payment: { status: "Posted" }- }- ],- count: 1,- error: null- });-- const result = await loader({- request: new Request("http://localhost/x/sales-order/order-1"),- params: { orderId: "order-1" },- context: {}- } as unknown as Parameters<typeof loader>[0]);-- expect(result.invoiceSummary).toEqual({- invoicedAmount: 80,- paidAmount: 40,- currencyMismatchCount: 0- });- });-});diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.tsxindex cdef02b2fd..304cef4177 100644--- a/apps/erp/app/routes/x+/sales-order+/$orderId.tsx+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.tsx@@ -24,6 +24,10 @@ import {getSalesOrderLines,getSalesOrderRelatedItems} from "~/modules/sales/sales.service";+import {+ type SalesOrderInvoiceSummary,+ summarizeSalesOrderInvoices+} from "~/modules/sales/sales.utils";import {SalesOrderExplorer,SalesOrderHeader,@@ -148,9 +152,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {? await getQuote(client, opportunity.data.quotes[0].id): null;- let invoicedAmount = 0;- let paidAmount = 0;- let currencyMismatchCount = 0;+ let invoiceSummary: SalesOrderInvoiceSummary = {+ invoicedAmount: 0,+ paidAmount: 0,+ currencyMismatchCount: 0+ };if (invoices && payments) {if (invoices.error) {@@ -173,45 +179,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- const paidBaseByInvoiceId = new Map<string, number>();- for (const payment of payments.data ?? []) {- if (!payment.targetSalesInvoiceId) continue;- paidBaseByInvoiceId.set(- payment.targetSalesInvoiceId,- (paidBaseByInvoiceId.get(payment.targetSalesInvoiceId) ?? 0) +- payment.appliedAmount- );- }-- const orderCurrency = salesOrder.data?.currencyCode;-- for (const invoice of invoices.data ?? []) {- // A voided invoice was never billed — it must not inflate the invoiced- // total, nor contribute any payments to the paid total.- if (invoice.status === "Voided") {- continue;- }-- const invoiceTotal = invoice.invoiceTotal ?? 0;- const invoiceCurrency = invoice.currencyCode;-- // Avoid mixing currencies in the same displayed number.- if (- orderCurrency &&- invoiceCurrency &&- invoiceCurrency !== orderCurrency- ) {- currencyMismatchCount += 1;- continue;- }-- invoicedAmount += invoiceTotal * (invoice.exchangeRate ?? 1);- if (invoice.id) {- paidAmount +=- (paidBaseByInvoiceId.get(invoice.id) ?? 0) *- (invoice.exchangeRate ?? 1);- }- }+ invoiceSummary = summarizeSalesOrderInvoices(+ salesOrder.data?.currencyCode,+ invoices.data ?? [],+ payments.data ?? []+ );}const defaultCc = customer?.data?.defaultCc?.length@@ -230,11 +202,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {opportunity: opportunity.data,customer: customer?.data ?? null,quote: quote?.data ?? null,- invoiceSummary: {- invoicedAmount,- paidAmount,- currencyMismatchCount- },+ invoiceSummary,originatedFromQuote: !!opportunity.data.quotes[0]?.id,defaultCc};diff --git a/apps/erp/app/routes/x+/settings+/integrations.oauth-state.test.ts b/apps/erp/app/routes/x+/settings+/integrations.oauth-state.test.tsdeleted file mode 100644index 8a6b0d805f..0000000000--- a/apps/erp/app/routes/x+/settings+/integrations.oauth-state.test.ts+++ /dev/null@@ -1,97 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { describe, expect, it, vi } from "vitest";--const requirePermissions = vi.hoisted(() => vi.fn());-const getIntegrationsWithHealth = vi.hoisted(() => vi.fn());--vi.mock("@carbon/auth", async (importOriginal) => ({- ...(await importOriginal<object>()),- error: vi.fn()-}));-vi.mock("@carbon/auth/auth.server", () => ({ requirePermissions }));-vi.mock("@carbon/auth/session.server", () => ({ flash: vi.fn() }));-vi.mock("@carbon/ee", async (importOriginal) => ({- ...(await importOriginal<typeof import("@carbon/ee")>()),- integrations: [],- quickInstallConnectors: [],- // The loader derives which role slots are taken so the cards can disable a- // conflicting Install. No integrations in this fixture, so no role is held.- getIntegrationIdsByRole: () => []-}));-vi.mock("@carbon/react", () => ({ toast: { error: vi.fn() } }));-vi.mock("@lingui/react/macro", () => ({ useLingui: vi.fn() }));-vi.mock("~/modules/settings/ui", () => ({ IntegrationsList: vi.fn() }));-vi.mock("~/modules/settings/integration-errors", () => ({- getIntegrationError: vi.fn()-}));-vi.mock("~/modules/settings/settings.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- getIntegrationsWithHealth-}));-vi.mock("~/utils/path", () => ({- path: {- to: { integrations: "/x/settings/integrations", settings: "/x/settings" }- }-}));--import { loader } from "./integrations";--/**- * This loader used to issue Ramp's signed OAuth state. It no longer does, and the- * assertion below is the inverse of the one it replaced.- *- * The state moved to `api+/integrations.$id.connect`, because only that route- * knows the chosen install MODE — and the mode has to be inside the signed cookie- * for the callback to trust it. A state issued here could not carry one, so an- * install started from a loader-issued state would land with no mode and silently- * resolve to `provider`: the customer picks "another system posts my ledger" and- * Carbon records the opposite.- *- * Reintroducing a server-issued state here is therefore a real regression, which- * is what this pins. The signed-state behaviour itself is covered by- * `api+/integrations.$id.connect.test.ts`.- */-describe("integrations loader", () => {- it("issues no OAuth state of its own", async () => {- requirePermissions.mockResolvedValue({- client: {},- userId: "user-1",- companyId: "company-1"- });- getIntegrationsWithHealth.mockResolvedValue({ data: [], error: null });-- const result = (await loader({- request: new Request("https://erp.example.com/x/settings/integrations"),- params: {}- } as never)) as {- data?: { oauthStates?: Record<string, string>; state?: string };- init?: { headers?: HeadersInit };- };-- expect(result.data?.oauthStates).toBeUndefined();- // Whatever the wrapper shape, the point is that nothing sets a state cookie.- expect(new Headers(result.init?.headers).get("Set-Cookie")).toBeNull();- });-- it("supplies no correlation value either", async () => {- // EVERY OAuth install now starts at the connect route, which issues a signed,- // browser-bound, single-use state. A value handed out here would be unsigned- // and unbound — reintroducing one is a downgrade, not a convenience.- requirePermissions.mockResolvedValue({- client: {},- userId: "user-1",- companyId: "company-1"- });- getIntegrationsWithHealth.mockResolvedValue({ data: [], error: null });-- const result = (await loader({- request: new Request("https://erp.example.com/x/settings/integrations"),- params: {}- } as never)) as { data?: { state?: string } };-- expect(result.data?.state).toBeUndefined();- });-});diff --git a/apps/erp/app/utils/query.test.ts b/apps/erp/app/utils/query.test.tsindex 9b7fda45b9..73045e931e 100644--- a/apps/erp/app/utils/query.test.ts+++ b/apps/erp/app/utils/query.test.ts@@ -3,25 +3,14 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { describe, expect, it, vi } from "vitest";--// @carbon/auth's barrel export pulls in @carbon/content/glossary, whose Lingui `msg`-// macro isn't transformed under plain vitest (no lingui plugin configured for-// apps/erp tests). Mock it the same way traceability.search.test.ts does --// getSearchTokens/setSearchFilter don't call badRequest or-// parseNumberFromUrlParam, so the mock only needs to satisfy the import.-vi.mock("@carbon/auth", () => ({- badRequest: vi.fn(),- parseNumberFromUrlParam: vi.fn()-}));--const {+import {formatRangeFilter,getGenericFilter,getGenericQueryFilters,getSearchTokens,parseRangeFilter,setSearchFilter-} = await import("./query");+} from "./query";describe("getSearchTokens", () => {it("splits a multi-word search into tokens", () => {@@ -40,7 +29,7 @@ describe("getSearchTokens", () => {]);});- it("returns an empty array for a single word", () => {+ it("returns a single word as one token", () => {expect(getSearchTokens("M8")).toEqual(["M8"]);});diff --git a/apps/erp/app/utils/query.ts b/apps/erp/app/utils/query.tsindex a6426901fe..b21a7039f7 100644--- a/apps/erp/app/utils/query.ts+++ b/apps/erp/app/utils/query.ts@@ -32,8 +32,8 @@ type GenericSchema = {* than `select("*")`, for the same reason: naming the columns lets Postgres* prune the views' unreferenced computed columns instead of materializing them* per row. Adding a column to one of those tables means adding it to the- * constant — `apps/erp/test/list-select-columns.test.ts` fails if an- * `accessorKey` is missing, because the CSV export reads accessors untyped.+ * constant — the `list-select-covers-columns` check (`@carbon/checks`) fails+ * if an `accessorKey` is missing, because the CSV export reads accessors untyped.*/export const LIST_COUNT = "estimated" as const;diff --git a/apps/erp/package.json b/apps/erp/package.jsonindex bed19e2220..e5428b6d3d 100644--- a/apps/erp/package.json+++ b/apps/erp/package.json@@ -5,12 +5,18 @@"@ai-sdk/anthropic": "catalog:","@ai-sdk/openai": "catalog:","@ai-sdk/react": "catalog:",+ "@carbon/serve": "workspace:*",+ "ai": "catalog:"+ },+ "devDependencies": {"@base-ui-components/react": "1.0.0-rc.0","@carbon/account": "workspace:*","@carbon/api": "workspace:*","@carbon/auth": "workspace:*",+ "@carbon/config": "workspace:*","@carbon/content": "workspace:*","@carbon/database": "workspace:*",+ "@carbon/dev": "workspace:*","@carbon/documents": "workspace:*","@carbon/ee": "workspace:*","@carbon/env": "workspace:*",@@ -27,7 +33,6 @@"@carbon/printing": "workspace:*","@carbon/query": "workspace:*","@carbon/react": "workspace:*",- "@carbon/serve": "workspace:*","@carbon/stripe": "workspace:*","@carbon/utils": "workspace:*","@carbon/viewer": "workspace:*",@@ -39,15 +44,18 @@"@emoji-mart/react": "catalog:","@epic-web/remember": "1.1.0","@internationalized/date": "catalog:",+ "@lingui/conf": "catalog:","@lingui/core": "catalog:","@lingui/react": "catalog:",+ "@lingui/vite-plugin": "catalog:","@monaco-editor/react": "4.7.0","@orpc/openapi": "catalog:","@orpc/server": "catalog:","@paper-design/shaders-react": "^0.0.57","@react-aria/i18n": "catalog:",- "react-email": "catalog:",+ "@react-aria/optimize-locales-plugin": "catalog:","@react-pdf/renderer": "catalog:",+ "@react-router/dev": "catalog:","@react-router/remix-routes-option-adapter": "catalog:","@react-types/datepicker": "3.13.5","@react-types/shared": "3.33.1",@@ -56,22 +64,38 @@"@supabase/postgrest-js": "catalog:","@supabase/storage-js": "catalog:","@supabase/supabase-js": "catalog:",+ "@tailwindcss/typography": "catalog:",+ "@tailwindcss/vite": "catalog:","@tanstack/react-query": "catalog:",+ "@tanstack/react-query-devtools": "catalog:","@tanstack/react-table": "8.21.3","@tanstack/react-virtual": "3.13.23","@tiptap/react": "catalog:",+ "@types/d3": "7.4.3",+ "@types/d3-force": "3.0.10",+ "@types/lodash": "4.17.26",+ "@types/lodash.template": "4.5.3",+ "@types/nprogress": "0.2.3",+ "@types/papaparse": "5.5.2",+ "@types/pg": "8.15.6",+ "@types/react": "catalog:",+ "@types/react-csv": "1.1.10",+ "@types/react-dom": "catalog:",+ "@types/tar-stream": "^3.1.4","@upstash/ratelimit": "2.0.8","@vercel/analytics": "catalog:","@vercel/functions": "catalog:","@vercel/react-router": "catalog:","@visx/responsive": "2.17.0",+ "@vitejs/devtools": "catalog:",+ "@vitejs/devtools-rolldown": "catalog:","@xyflow/react": "12.10.2",- "ai": "catalog:","assert-never": "1.4.0","class-variance-authority": "catalog:","clsx": "2.1.1","comlink": "4.4.2","cookie": "catalog:",+ "cross-env": "catalog:","d3": "7.9.0","d3-array": "3.2.4","d3-force": "3.0.0",@@ -91,11 +115,14 @@"motion": "catalog:","motion-number": "0.1.7","nanoid": "catalog:",+ "nodemon": "catalog:","non.geist": "catalog:",+ "npm-run-all": "catalog:","papaparse": "5.3.2","pdf-lib": "^1.17.1","pdfjs-dist": "5.4.296","performant-array-to-tree": "1.11.0",+ "pg": "8.20.0","posthog-js": "catalog:","react": "catalog:","react-colorful": "5.6.1",@@ -104,6 +131,7 @@"react-csv": "2.2.2","react-dom": "catalog:","react-dropzone": "catalog:",+ "react-email": "catalog:","react-hotkeys-hook": "catalog:","react-icons": "catalog:","react-intersection-observer": "9.16.0",@@ -122,56 +150,29 @@"sonner": "2.0.7","spin-delay": "2.0.1","sst": "catalog:",+ "supabase": "catalog:","tailwind-merge": "catalog:",+ "tailwind-scrollbar": "catalog:",+ "tailwind-scrollbar-hide": "catalog:",+ "tailwindcss": "catalog:",+ "tailwindcss-animate": "catalog:","tar-stream": "^3.2.0","tiny-invariant": "1.3.3","tsup": "catalog:","tus-js-client": "4.3.1",+ "typescript": "catalog:",+ "typescript5": "npm:[email protected]","unified": "11.0.5","unist-util-visit": "5.1.0","use-stick-to-bottom": "1.1.3",+ "vite": "catalog:",+ "vitest": "catalog:","zbsearch": "catalog:","zod": "catalog:","zod-form-data": "catalog:","zod-to-json-schema": "3.25.2","zustand": "catalog:"},- "devDependencies": {- "@carbon/config": "workspace:*",- "@carbon/dev": "workspace:*",- "@lingui/conf": "catalog:",- "@lingui/vite-plugin": "catalog:",- "@react-aria/optimize-locales-plugin": "catalog:",- "@react-router/dev": "catalog:",- "@tailwindcss/typography": "catalog:",- "@tailwindcss/vite": "catalog:",- "@tanstack/react-query-devtools": "catalog:",- "@types/d3": "7.4.3",- "@types/d3-force": "3.0.10",- "@types/lodash": "4.17.26",- "@types/lodash.template": "4.5.3",- "@types/nprogress": "0.2.3",- "@types/papaparse": "5.5.2",- "@types/pg": "8.15.6",- "@types/react": "catalog:",- "@types/react-csv": "1.1.10",- "@types/react-dom": "catalog:",- "@types/tar-stream": "^3.1.4",- "@vitejs/devtools": "catalog:",- "@vitejs/devtools-rolldown": "catalog:",- "cross-env": "catalog:",- "nodemon": "catalog:",- "pg": "8.20.0",- "npm-run-all": "catalog:",- "supabase": "catalog:",- "tailwind-scrollbar": "catalog:",- "tailwind-scrollbar-hide": "catalog:",- "tailwindcss": "catalog:",- "tailwindcss-animate": "catalog:",- "typescript": "catalog:",- "vite": "catalog:",- "vitest": "catalog:"- },"private": true,"scripts": {"build": "react-router build",@@ -181,7 +182,7 @@"lint": "biome lint --write ","start": "NODE_ENV=production node ./server/node.ts","test": "vitest run",- "typecheck": "react-router typegen && tsgo --noEmit",+ "typecheck": "react-router typegen && tsc --noEmit","typegen": "react-router typegen"},"sideEffects": [diff --git a/apps/erp/test/__snapshots__/posting-permissions.test.ts.snap b/apps/erp/test/__snapshots__/posting-permissions.test.ts.snapdeleted file mode 100644index 6d03cb9fb2..0000000000--- a/apps/erp/test/__snapshots__/posting-permissions.test.ts.snap+++ /dev/null@@ -1,503 +0,0 @@-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html--exports[`posting permissions > match the reviewed manifest 1`] = `-{- "accounting.activateAccountingPermission": {- "update": "accounting",- },- "accounting.applyAccountImportPermission": {- "update": "accounting",- },- "accounting.journalLegacyDocumentsPermission": {- "update": "accounting",- },- "accounting.postAssetTransferPermission": {- "by": "type",- "rules": {- "adjustCost": {- "update": "accounting",- },- "attachJob": {- "create": "accounting",- },- "capitalize": {- "create": "accounting",- },- "capitalizeCip": {- "create": "accounting",- },- "return": {- "create": "accounting",- },- },- },- "accounting.postChargePermission": {- "update": "invoicing",- },- "accounting.postReimbursementPermission": {- "update": "invoicing",- },- "accounting.previewAssetCapitalizationPermission": {- "view": "accounting",- },- "accounting.previewRevenueRecognitionRunPermission": {- "view": "accounting",- },- "accounting.proposeRevenueRecognitionRunPermission": {- "create": "accounting",- },- "accounting.recalculateRevenueRecognitionRunPermission": {- "update": "accounting",- },- "inventory.issueMaterialPermission": {- "by": "type",- "rules": {- "convertEntity": {- "update": "inventory",- },- "jobCompleteMakeToOrder": {},- "jobOperation": {- "update": "production",- },- "jobOperationBatchComplete": {- "update": "production",- },- "jobOperationBatchOutput": {- "update": "production",- },- "jobOperationDryRun": {- "update": "production",- },- "jobOperationScrap": {- "update": "production",- },- "jobOperationSerialComplete": {- "update": "production",- },- "maintenanceDispatchInventory": {- "update": "resources",- },- "maintenanceDispatchTrackedEntities": {- "update": "resources",- },- "maintenanceDispatchUnconsume": {- "update": "resources",- },- "maintenanceDispatchUnissue": {- "update": "resources",- },- "mergeTrackedEntities": {- "update": "inventory",- },- "partToOperation": {- "update": "production",- },- "scrapTrackedEntity": {- "update": "production",- },- "trackedEntitiesToBatch": {- "update": "production",- },- "trackedEntitiesToOperation": {- "update": "production",- },- "unconsumeTrackedEntities": {- "update": "production",- },- },- },- "inventory.postInventoryAdjustmentPermission": {- "update": "inventory",- },- "inventory.postInventoryCountPermission": {- "update": "inventory",- },- "inventory.postPickingPermission": {},- "inventory.postReceiptPermission": {- "update": "inventory",- },- "inventory.postShipmentPermission": {- "update": "inventory",- },- "inventory.postStockMovementCorrectionPermission": {- "update": "inventory",- },- "inventory.postStockTransferPermission": {},- "inventory.previewSerialUnitCostsPermission": {- "view": "accounting",- },- "inventory.recostSerialUnitPermission": {- "update": "accounting",- },- "inventory.replenishKanbanPermission": {- "by": "mode",- "rules": {- "level": "system",- "scan": {- "create": "inventory",- },- },- },- "invoicing.postMemoPermission": {- "update": "invoicing",- },- "invoicing.postPaymentPermission": {- "update": "invoicing",- },- "invoicing.postPurchaseInvoicePermission": {- "update": "invoicing",- },- "invoicing.postSalesInvoicePermission": {- "update": "invoicing",- },- "items.syncMakeMethodPermission": {- "update": "resources",- },- "production.assignSerialNumbersPermission": {- "update": "production",- },- "production.batchOperationPermission": {- "update": "production",- },- "production.getMethodPermission": {- "update": "production",- },- "production.postProductionEventPermission": {- "update": "production",- },- "production.recalculateRequirementsPermission": {- "update": "production",- },- "production.rescheduleJobPermission": {- "update": "production",- },- "production.triggerReworkPermission": {- "update": "production",- },- "purchasing.createLeaseInvoicesPermission": {- "create": "invoicing",- "update": "purchasing",- },- "purchasing.finalizePurchasingRfqPermission": {- "create": "purchasing",- },- "purchasing.finalizeSupplierQuotePermission": {- "create": "purchasing",- },- "purchasing.postLeaseActionPermission": {- "update": "purchasing",- },- "purchasing.updatePurchasedPricesPermission": {- "update": "purchasing",- },- "quality.postNonconformancePermission": {- "update": "quality",- },- "resources.postMaintenanceEventPermission": {- "update": "resources",- },- "sales.createContractInvoicesPermission": {- "create": "invoicing",- "update": "sales",- },- "sales.createRentalInvoicesPermission": {- "create": "invoicing",- "update": "sales",- },- "sales.postCustomerContractPermission": {- "update": "sales",- },- "sales.postRentalAgreementPermission": {- "update": "sales",- },- "settings.seedCompanyPermission": "system",- "shared.convertDocumentPermission": {- "by": "type",- "rules": {- "methodVersionToActive": {- "update": "resources",- },- "purchaseOrderToPurchaseInvoice": {- "update": "invoicing",- },- "quoteToSalesOrder": {- "update": "sales",- },- "salesOrderToSalesInvoice": {- "update": "invoicing",- },- "salesRfqToQuote": {- "update": "sales",- },- "shipmentToSalesInvoice": {- "update": "invoicing",- },- "supplierQuoteToPurchaseOrder": {- "update": "purchasing",- },- "warehouseTransferToReceipt": {- "update": "inventory",- },- "warehouseTransferToShipment": {- "update": "inventory",- },- },- },- "shared.createDocumentPermission": {- "by": "type",- "rules": {- "journalEntry": {- "create": "accounting",- },- "nonConformanceTasks": {- "update": "quality",- },- "purchaseOrderFromJob": {- "create": [- "purchasing",- "production",- ],- },- "receiptDefault": {- "create": "inventory",- },- "receiptFromInboundTransfer": {- "create": "inventory",- },- "receiptFromPurchaseOrder": {- "create": "inventory",- },- "receiptFromRentalAgreement": {- "create": "inventory",- },- "receiptFromSalesReturnOrder": {- "create": "inventory",- },- "receiptFromWarehouseTransfer": {- "create": "inventory",- },- "receiptLineSplit": {- "create": "inventory",- },- "shipmentDefault": {- "create": "inventory",- },- "shipmentFromPurchaseOrder": {- "create": "inventory",- },- "shipmentFromPurchaseReturnOrder": {- "create": "inventory",- },- "shipmentFromRentalAgreement": {- "create": "inventory",- },- "shipmentFromSalesOrder": {- "create": "inventory",- },- "shipmentFromSalesOrderLine": {- "create": "inventory",- },- "shipmentFromSalesReturnOrder": {- "create": "inventory",- },- "shipmentFromWarehouseTransfer": {- "create": "inventory",- },- "shipmentLineSplit": {- "create": "inventory",- },- },- },-}-`;--exports[`posting permissions > match the reviewed manifest 2`] = `-{- "batch-operations": {- "update": "production",- },- "create": {- "by": "type",- "rules": {- "journalEntry": {- "create": "accounting",- },- "nonConformanceTasks": {- "update": "quality",- },- "purchaseOrderFromJob": {- "create": [- "purchasing",- "production",- ],- },- "receiptDefault": {- "create": "inventory",- },- "receiptFromInboundTransfer": {- "create": "inventory",- },- "receiptFromPurchaseOrder": {- "create": "inventory",- },- "receiptFromRentalAgreement": {- "create": "inventory",- },- "receiptFromSalesReturnOrder": {- "create": "inventory",- },- "receiptFromWarehouseTransfer": {- "create": "inventory",- },- "receiptLineSplit": {- "create": "inventory",- },- "shipmentDefault": {- "create": "inventory",- },- "shipmentFromPurchaseOrder": {- "create": "inventory",- },- "shipmentFromPurchaseReturnOrder": {- "create": "inventory",- },- "shipmentFromRentalAgreement": {- "create": "inventory",- },- "shipmentFromSalesOrder": {- "create": "inventory",- },- "shipmentFromSalesOrderLine": {- "create": "inventory",- },- "shipmentFromSalesReturnOrder": {- "create": "inventory",- },- "shipmentFromWarehouseTransfer": {- "create": "inventory",- },- "shipmentLineSplit": {- "create": "inventory",- },- },- },- "create-contract-invoices": {- "create": "invoicing",- "update": "sales",- },- "create-lease-invoices": {- "create": "invoicing",- "update": "purchasing",- },- "create-rental-invoices": {- "create": "invoicing",- "update": "sales",- },- "issue": {- "by": "type",- "rules": {- "convertEntity": {- "update": "inventory",- },- "jobCompleteMakeToOrder": {},- "jobOperation": {- "update": "production",- },- "jobOperationBatchComplete": {- "update": "production",- },- "jobOperationBatchOutput": {- "update": "production",- },- "jobOperationDryRun": {- "update": "production",- },- "jobOperationScrap": {- "update": "production",- },- "jobOperationSerialComplete": {- "update": "production",- },- "maintenanceDispatchInventory": {- "update": "resources",- },- "maintenanceDispatchTrackedEntities": {- "update": "resources",- },- "maintenanceDispatchUnconsume": {- "update": "resources",- },- "maintenanceDispatchUnissue": {- "update": "resources",- },- "mergeTrackedEntities": {- "update": "inventory",- },- "partToOperation": {- "update": "production",- },- "scrapTrackedEntity": {- "update": "production",- },- "trackedEntitiesToBatch": {- "update": "production",- },- "trackedEntitiesToOperation": {- "update": "production",- },- "unconsumeTrackedEntities": {- "update": "production",- },- },- },- "kanban-replenish": {- "by": "mode",- "rules": {- "level": "system",- "scan": {- "create": "inventory",- },- },- },- "post-charge": {- "update": "invoicing",- },- "post-inventory-adjustment": {- "update": "inventory",- },- "post-maintenance-event": {- "update": "resources",- },- "post-payment": {- "update": "invoicing",- },- "post-picking": {},- "post-production-event": {- "update": "production",- },- "post-purchase-invoice": {- "update": "invoicing",- },- "post-receipt": {- "update": "inventory",- },- "post-sales-invoice": {- "update": "invoicing",- },- "post-shipment": {- "update": "inventory",- },- "propose-revenue-recognition-run": {- "create": "accounting",- },- "recalculate": {- "update": "production",- },- "trigger-rework": {- "update": "production",- },- "update-purchased-prices": {- "update": "purchasing",- },-}-`;diff --git a/apps/erp/test/apply-production-planning-date-actions.test.ts b/apps/erp/test/apply-production-planning-date-actions.test.tsindex 532ddc17a4..c6372026b7 100644--- a/apps/erp/test/apply-production-planning-date-actions.test.ts+++ b/apps/erp/test/apply-production-planning-date-actions.test.ts@@ -2,144 +2,40 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import { describe, expect, it } from "vitest";import {- type CompiledQuery,- type DatabaseConnection,- DummyDriver,- Kysely as KyselyClient,- PostgresAdapter,- PostgresIntrospector,- PostgresQueryCompiler,- type QueryResult-} from "kysely";-import { describe, expect, it, vi } from "vitest";--vi.mock("@carbon/content/glossary", () => ({- terms: {},- getEntry: vi.fn(),- lookupEntry: vi.fn(),- hasEntry: vi.fn(),- termSlug: vi.fn(),- glossaryEntries: () => []-}));-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray | string, ...values: unknown[]) =>- Array.isArray(strings)- ? strings.reduce(- (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),- ""- )- : String(strings)-}));--const { applyProductionPlanningDateActions, nextJobPriority } = await import(- "../app/modules/production/production.service"-);--// The Postgres wire is the boundary: each statement is recorded, and the rows-// "the database" answers with are chosen by what the statement is.-type Responder = (query: CompiledQuery) => unknown[];--class RecordingDriver extends DummyDriver {- readonly sent: CompiledQuery[] = [];- constructor(private readonly respond: Responder) {- super();- }- override async acquireConnection(): Promise<DatabaseConnection> {- return {- executeQuery: async <R>(- query: CompiledQuery- ): Promise<QueryResult<R>> => {- this.sent.push(query);- return { rows: this.respond(query) as R[] };- },- // biome-ignore lint/correctness/useYield: never streamed- streamQuery: async function* () {- throw new Error("not streamed");- }- };- }-}--function database(respond: Responder) {- const driver = new RecordingDriver(respond);- const db = new KyselyClient<KyselyDatabase>({- dialect: {- createAdapter: () => new PostgresAdapter(),- createDriver: () => driver,- createIntrospector: (k) => new PostgresIntrospector(k),- createQueryCompiler: () => new PostgresQueryCompiler()- }- }) as unknown as Kysely<KyselyDatabase>;- return { db, driver };-}--const is = {- claim: (q: CompiledQuery) =>- /^update "planningAction" set "status" = \$1/.test(q.sql) &&- q.parameters.includes("Actioned"),- jobs: (q: CompiledQuery) =>- /^select "id", "locationId", "deadlineType" from "job"/.test(q.sql),- siblings: (q: CompiledQuery) =>- /^select "id", "locationId", "dueDate", "priority", "deadlineType" from "job"/.test(- q.sql- ),- dates: (q: CompiledQuery) => /UPDATE "job" AS j\s+SET "dueDate"/.test(q.sql),- reopen: (q: CompiledQuery) =>- /UPDATE "planningAction" AS a\s+SET "status" = 'Open'/.test(q.sql)-};--const ids = (rows: string[]) => rows.map((id) => ({ id }));-const scope = { companyId: "c1", userId: "u1" };--const moveA = {- planningActionId: "a1",- jobId: "job-a",- suggestedDate: "2026-11-02"-};-const moveB = {- planningActionId: "a2",- jobId: "job-b",- suggestedDate: "2026-11-02"-};--function everythingLands(q: CompiledQuery): unknown[] {- if (is.claim(q)) return ids(["a1", "a2"]);- if (is.jobs(q)) {- return [- { id: "job-a", locationId: "loc", deadlineType: "Soft Deadline" },- { id: "job-b", locationId: "loc", deadlineType: "ASAP" }- ];- }- if (is.siblings(q)) {- // one job already on the target date- return [- {- id: "job-x",- locationId: "loc",- dueDate: "2026-11-02",- priority: 4,- deadlineType: "Soft Deadline"- }- ];- }- if (is.dates(q)) return ids(["job-a", "job-b"]);- return [];-}+ nextJobPriority,+ planJobDateMoves+} from "../app/modules/production/production.service";+// Deadline types rank ASAP < Hard < Soft < No Deadline.describe("nextJobPriority", () => {- it("starts at 0 with no siblings, goes after the last, or before a lower rank", () => {+ it("starts at 0 on a date with no other jobs", () => {expect(nextJobPriority([], "Soft Deadline")).toBe(0);+ });++ it("goes after the last job when nothing ranks lower", () => {expect(nextJobPriority([{ priority: 4, deadlineType: "Soft Deadline" }],"Soft Deadline")).toBe(5);+ });++ it("goes before the first job that ranks lower, at half its priority", () => {expect(nextJobPriority([{ priority: 4, deadlineType: "Soft Deadline" }], "ASAP")).toBe(2);+ });++ it("goes to -1 before a first job at priority 0", () => {+ expect(+ nextJobPriority([{ priority: 0, deadlineType: "Soft Deadline" }], "ASAP")+ ).toBe(-1);+ });++ it("goes halfway between the jobs it falls between", () => {expect(nextJobPriority([@@ -152,137 +48,87 @@ describe("nextJobPriority", () => {});});-describe("applyProductionPlanningDateActions", () => {- it("claims, reads twice and writes every date and priority in one statement", async () => {- const { db, driver } = database(everythingLands);- const result = await applyProductionPlanningDateActions(db, {- ...scope,- actions: [moveA, moveB]- });- expect(result).toEqual({- applied: ["a1", "a2"],- alreadyApplied: [],- refused: []- });- expect(driver.sent.filter(is.claim)).toHaveLength(1);- expect(driver.sent.filter(is.jobs)).toHaveLength(1);- expect(driver.sent.filter(is.siblings)).toHaveLength(1);- expect(driver.sent.filter(is.dates)).toHaveLength(1);- expect(driver.sent).toHaveLength(4);+describe("planJobDateMoves", () => {+ const job = (+ id: string,+ deadlineType: "ASAP" | "Soft Deadline" | "No Deadline" = "Soft Deadline"+ ) => ({ id, locationId: "loc", deadlineType });+ const sibling = (+ overrides: Partial<{+ locationId: string;+ dueDate: string;+ priority: number;+ deadlineType: "Soft Deadline" | "No Deadline";+ }> = {}+ ) => ({+ locationId: "loc",+ dueDate: "2026-11-02",+ priority: 4,+ deadlineType: "Soft Deadline" as const,+ ...overrides});+ const move = (jobId: string) => ({ jobId, suggestedDate: "2026-11-02" });- // job-a (Soft Deadline) goes after the sibling at 4 → 5; job-b (ASAP) goes- // before both → half of the first priority, 2. Each placement sees the one- // before it, as the sequential writes did.- it("ranks moved jobs among the jobs already on the date, in turn", async () => {- const { db, driver } = database(everythingLands);- await applyProductionPlanningDateActions(db, {- ...scope,- actions: [moveA, moveB]- });- const write = driver.sent.find(is.dates)!;- expect(write.parameters).toEqual(- expect.arrayContaining(["job-a", "2026-11-02", 5, "job-b", 2])- );- expect(write.parameters).toEqual(- expect.arrayContaining(["Draft", "Planned", "c1"])- );- });-- // An MRP run between the page's read and the claim can move an Open action's- // date in place. The claim RETURNS the row's date, and that is what is- // written; the page's date is only the fallback for a row that has none.- it("applies the date from the claim, not from the page", async () => {- const { db, driver } = database((q) =>- is.claim(q)- ? [- { id: "a1", suggestedDate: "2026-11-09", suggestedQuantity: null },- { id: "a2", suggestedDate: null, suggestedQuantity: null }- ]- : everythingLands(q)- );- await applyProductionPlanningDateActions(db, {- ...scope,- actions: [moveA, moveB]- });- const write = driver.sent.find(is.dates)!;- expect(write.parameters).toEqual(- expect.arrayContaining(["job-a", "2026-11-09", "job-b", "2026-11-02"])- );- expect(write.parameters).not.toContain("2026-11-02\u0000");- // The siblings read asks for the claimed date, not the page's.- const siblings = driver.sent.find(is.siblings)!;- expect(siblings.parameters).toContain("2026-11-09");- });-- // The job form hides the due-date field for "No Deadline", so a date written- // under that type could be neither seen nor edited on the job, and the- // priority would carry the undated weight. The date apply restates the type- // as the Order path does.- it("gives a No Deadline job a Soft Deadline with its date", async () => {- const { db, driver } = database((q) =>- is.jobs(q)- ? [- { id: "job-a", locationId: "loc", deadlineType: "No Deadline" },- { id: "job-b", locationId: "loc", deadlineType: "ASAP" }- ]- : everythingLands(q)- );- await applyProductionPlanningDateActions(db, {- ...scope,- actions: [moveA, moveB]- });- const write = driver.sent.find(is.dates)!;- expect(write.sql).toContain(- `"deadlineType" = v."deadlineType"::"deadlineType"`- );- // job-a ranks as a Soft Deadline: after the sibling at 4 → 5, not before it.- expect(write.parameters).toEqual(- expect.arrayContaining(["job-a", "2026-11-02", "Soft Deadline", 5])- );- expect(write.parameters).not.toContain("No Deadline");- // A job that already has a dated type keeps it.- expect(write.parameters).toEqual(- expect.arrayContaining(["job-b", "ASAP", 2])- );+ it("places jobs moved to one date in turn, each after the one before", () => {+ expect(+ planJobDateMoves(+ [move("job-a"), move("job-b")],+ [job("job-a"), job("job-b")],+ [sibling()]+ )+ ).toEqual([+ {+ jobId: "job-a",+ dueDate: "2026-11-02",+ deadlineType: "Soft Deadline",+ priority: 5+ },+ {+ jobId: "job-b",+ dueDate: "2026-11-02",+ deadlineType: "Soft Deadline",+ priority: 6+ }+ ]);});- it("leaves an action another apply already claimed alone", async () => {- const { db, driver } = database((q) =>- is.claim(q) ? ids(["a2"]) : everythingLands(q)- );- const result = await applyProductionPlanningDateActions(db, {- ...scope,- actions: [moveA, moveB]- });- expect(result.alreadyApplied).toEqual(["a1"]);- expect(result.applied).toEqual(["a2"]);- const write = driver.sent.find(is.dates)!;- expect(write.parameters).not.toContain("job-a");+ // The job form hides the due date of a No Deadline job, so a dated job+ // must carry a dated type; it then ranks as Soft, ahead of undated jobs.+ it("gives a No Deadline job a Soft Deadline and ranks it as one", () => {+ expect(+ planJobDateMoves(+ [move("job-a")],+ [job("job-a", "No Deadline")],+ [sibling({ deadlineType: "No Deadline" })]+ )+ ).toEqual([+ {+ jobId: "job-a",+ dueDate: "2026-11-02",+ deadlineType: "Soft Deadline",+ priority: 2+ }+ ]);});- // job-a was released to the floor after the page loaded: the guarded UPDATE- // leaves it, and its action goes back to Open for review.- it("un-claims an action whose job left Draft / Planned", async () => {- const { db, driver } = database((q) => {- if (is.dates(q)) return ids(["job-b"]);- if (is.reopen(q)) return ids(["a1"]);- return everythingLands(q);- });- const result = await applyProductionPlanningDateActions(db, {- ...scope,- actions: [moveA, moveB]- });- expect(result.refused).toEqual([{ id: "a1", jobId: "job-a" }]);- expect(result.applied).toEqual(["a2"]);- expect(driver.sent.find(is.reopen)!.parameters).toEqual(- expect.arrayContaining(["a1", "c1"])- );+ it("ranks only among jobs at the same location on the same date", () => {+ expect(+ planJobDateMoves(+ [move("job-a")],+ [job("job-a", "ASAP")],+ [sibling({ locationId: "elsewhere" }), sibling({ dueDate: "2026-11-03" })]+ )+ ).toEqual([+ {+ jobId: "job-a",+ dueDate: "2026-11-02",+ deadlineType: "ASAP",+ priority: 0+ }+ ]);});- it("sends nothing for an empty batch", async () => {- const { db, driver } = database(everythingLands);- await applyProductionPlanningDateActions(db, { ...scope, actions: [] });- expect(driver.sent).toHaveLength(0);+ it("leaves out a move whose job was not found", () => {+ expect(planJobDateMoves([move("gone")], [job("job-a")], [])).toEqual([]);});});diff --git a/apps/erp/test/apply-purchasing-planning-actions.test.ts b/apps/erp/test/apply-purchasing-planning-actions.test.tsindex f1883a7e73..b921620a5f 100644--- a/apps/erp/test/apply-purchasing-planning-actions.test.ts+++ b/apps/erp/test/apply-purchasing-planning-actions.test.ts@@ -2,351 +2,95 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import { describe, expect, it } from "vitest";import {- type CompiledQuery,- type DatabaseConnection,- DummyDriver,- Kysely as KyselyClient,- PostgresAdapter,- PostgresIntrospector,- PostgresQueryCompiler,- type QueryResult-} from "kysely";-import { describe, expect, it, vi } from "vitest";--vi.mock("@carbon/content/glossary", () => ({- terms: {},- getEntry: vi.fn(),- lookupEntry: vi.fn(),- hasEntry: vi.fn(),- termSlug: vi.fn(),- glossaryEntries: () => []-}));-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray | string, ...values: unknown[]) =>- Array.isArray(strings)- ? strings.reduce(- (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),- ""- )- : String(strings)-}));--const { applyPurchasingPlanningActions } = await import(- "../app/modules/purchasing/purchasing.service"-);--// The Postgres wire is the boundary. Each statement the apply sends is-// recorded, and the rows "the database" answers with are chosen by what the-// statement is — the claim, a line write, a read, the un-claim.-type Responder = (query: CompiledQuery) => unknown[];--class RecordingDriver extends DummyDriver {- readonly sent: CompiledQuery[] = [];- constructor(private readonly respond: Responder) {- super();- }- override async acquireConnection(): Promise<DatabaseConnection> {- return {- executeQuery: async <R>(- query: CompiledQuery- ): Promise<QueryResult<R>> => {- this.sent.push(query);- return { rows: this.respond(query) as R[] };- },- // biome-ignore lint/correctness/useYield: never streamed- streamQuery: async function* () {- throw new Error("not streamed");- }- };- }-}--function database(respond: Responder) {- const driver = new RecordingDriver(respond);- const db = new KyselyClient<KyselyDatabase>({- dialect: {- createAdapter: () => new PostgresAdapter(),- createDriver: () => driver,- createIntrospector: (k) => new PostgresIntrospector(k),- createQueryCompiler: () => new PostgresQueryCompiler()- }- }) as unknown as Kysely<KyselyDatabase>;- return { db, driver };-}--const is = {- claim: (q: CompiledQuery) =>- /^update "planningAction" set "status" = \$1/.test(q.sql) &&- q.parameters.includes("Actioned"),- dates: (q: CompiledQuery) =>- /UPDATE "purchaseOrderLine" AS l\s+SET "requiredDate"/.test(q.sql),- quantities: (q: CompiledQuery) =>- /UPDATE "purchaseOrderLine" AS l\s+SET "purchaseQuantity"/.test(q.sql),- lines: (q: CompiledQuery) => /^select .* from "purchaseOrderLine" as "pol"/.test(q.sql),- currencies: (q: CompiledQuery) => /^select .* from "currencies"/.test(q.sql),- cancels: (q: CompiledQuery) => /^delete from "purchaseOrderLine"/.test(q.sql),- reopen: (q: CompiledQuery) =>- /UPDATE "planningAction" AS a\s+SET "status" = 'Open'/.test(q.sql),- drop: (q: CompiledQuery) => /^delete from "planningAction"/.test(q.sql)-};--const ids = (rows: string[]) => rows.map((id) => ({ id }));--const scope = { companyId: "c1", companyGroupId: "g1", userId: "u1" };--const expedite = {- planningActionId: "a-date",- type: "Expedite" as const,- lineId: "pol-date",- purchaseOrderId: "po1",- suggestedDate: "2026-11-02",- suggestedQuantity: null-};-const increase = {- planningActionId: "a-qty",- type: "Increase" as const,- lineId: "pol-qty",- purchaseOrderId: "po2",- suggestedDate: null,- // inventory units; the line below converts at 10 per purchase unit- suggestedQuantity: 55-};-const cancel = {- planningActionId: "a-cancel",- type: "Cancel" as const,- lineId: "pol-cancel",- purchaseOrderId: "po3",- suggestedDate: null,- suggestedQuantity: null-};--const qtyLine = {- id: "pol-qty",+ type PlanningQuantityLine,+ planningQuantityChange+} from "../app/modules/purchasing/purchasing.models";++// 2.00 a purchase unit, 10 inventory units per purchase unit, 10% tax.+const base = (+ overrides: Partial<PlanningQuantityLine> = {}+): PlanningQuantityLine => ({supplierUnitPrice: 2,supplierShippingCost: 0,purchaseQuantity: 4,+ quantityReceived: 0,+ quantityInvoiced: 0,+ receivedComplete: false,taxPercent: 0.1,supplierTaxAmount: 0.8,conversionFactor: 10,- currencyCode: "USD"-};--// Answers as if every write lands: the claim takes every id, each line write-// returns its lines, the quantity read returns the line and its currency.-function everythingLands(q: CompiledQuery): unknown[] {- if (is.claim(q)) return ids(["a-date", "a-qty", "a-cancel"]);- if (is.dates(q)) return ids(["pol-date"]);- if (is.lines(q)) return [qtyLine];- if (is.currencies(q)) return [{ code: "USD", decimalPlaces: 2 }];- if (is.quantities(q)) return ids(["pol-qty"]);- if (is.cancels(q)) return ids(["pol-cancel"]);- return [];-}--describe("applyPurchasingPlanningActions", () => {- it("applies a mixed batch as one statement per kind, inside one transaction", async () => {- const { db, driver } = database(everythingLands);- const result = await applyPurchasingPlanningActions(db, {- ...scope,- actions: [expedite, increase, cancel]- });-- expect(result).toEqual({- applied: ["a-date", "a-qty", "a-cancel"],- alreadyApplied: [],- refused: [],- failed: []- });- // one claim, one date write, one lines read, one currency read, one- // quantity write, one cancel — and nothing per action- expect(driver.sent.filter(is.claim)).toHaveLength(1);- expect(driver.sent.filter(is.dates)).toHaveLength(1);- expect(driver.sent.filter(is.quantities)).toHaveLength(1);- expect(driver.sent.filter(is.cancels)).toHaveLength(1);- expect(driver.sent.filter(is.reopen)).toHaveLength(0);- expect(driver.sent).toHaveLength(6);- });-- it("claims only Open rows, and every write keeps the Draft / Planned guard", async () => {- const { db, driver } = database(everythingLands);- await applyPurchasingPlanningActions(db, {- ...scope,- actions: [expedite, increase, cancel]- });- const claim = driver.sent.find(is.claim)!;- expect(claim.parameters).toEqual(- expect.arrayContaining(["Open", "c1", "a-date", "a-qty", "a-cancel"])- );- for (const write of driver.sent.filter(- (q) => is.dates(q) || is.quantities(q) || is.cancels(q)- )) {- expect(write.sql).toMatch(- /"purchaseOrderId" in \(+select "id" from "purchaseOrder"/i- );- expect(write.parameters).toEqual(- expect.arrayContaining(["Draft", "Planned", "c1"])- );- }- const cancels = driver.sent.find(is.cancels)!;- expect(cancels.sql).toContain('coalesce("quantityReceived"');- expect(cancels.sql).toContain('coalesce("quantityInvoiced"');- // a draft invoice line's RESTRICT reference refuses the line, not the batch- expect(cancels.sql).toMatch(- /not exists \(select "purchaseInvoiceLine"\."id" from "purchaseInvoiceLine"/- );- });-- // 55 inventory units at 10 per purchase unit is 5.5 → 6 purchase units, and- // the stored tax amount follows the new base (2 × 6 at 10% = 1.20).- it("converts a quantity to whole purchase units and restates the tax pair", async () => {- const { db, driver } = database(everythingLands);- await applyPurchasingPlanningActions(db, { ...scope, actions: [increase] });- const write = driver.sent.find(is.quantities)!;- expect(write.parameters).toEqual(- expect.arrayContaining(["pol-qty", 6, 0.1, 1.2])- );- });-- // MRP measures a line by what it still has to bring (`quantityToReceive`). A- // PO reopened from planning can carry a receipt: 55 inventory units still to- // come is 6 purchase units ON TOP of the 2 received — 8 on the line, tax- // 2 × 8 at 10% = 1.60. Writing 6 would have dropped what arrived.- it("adds what was already received to the quantity still to come", async () => {- const { db, driver } = database((q) =>- is.lines(q) ? [{ ...qtyLine, quantityReceived: 2 }] : everythingLands(q)- );- await applyPurchasingPlanningActions(db, { ...scope, actions: [increase] });- const write = driver.sent.find(is.quantities)!;- expect(write.parameters).toEqual(- expect.arrayContaining(["pol-qty", 8, 0.1, 1.6])- );- });+ currencyCode: "USD",+ baseCurrencyCode: "USD",+ ...overrides+});- // A PO with no currency is in the company's base currency. It used to fail- // every quantity change with "Currency (none) has no precision".- it("prices a PO with no currency in the company's base currency", async () => {- const { db, driver } = database((q) =>- is.lines(q)- ? [{ ...qtyLine, currencyCode: null, baseCurrencyCode: "USD" }]- : everythingLands(q)- );- const result = await applyPurchasingPlanningActions(db, {- ...scope,- actions: [increase]+const decimals = new Map([+ ["USD", 2],+ ["JPY", 0]+]);++describe("planningQuantityChange", () => {+ // 55 inventory units at 10 per purchase unit is 5.5 → 6; tax 2 × 6 × 10% = 1.20.+ it("converts to whole purchase units and restates the tax pair", () => {+ expect(planningQuantityChange(base(), decimals, 55)).toEqual({+ ok: true,+ quantity: 6,+ percent: 0.1,+ amount: 1.2,+ receivedComplete: false,+ invoicedComplete: false});- expect(result.failed).toEqual([]);- expect(result.applied).toEqual(["a-qty"]);- expect(driver.sent.find(is.currencies)!.parameters).toContain("USD");});- // An MRP run between the page's read and the claim can move an Open action's- // quantity or date in place. The claim RETURNS the row's values, and those- // are what is written: 75 inventory units at 10 per purchase unit is- // 7.5 → 8, tax 2 × 8 at 10% = 1.60 — not the page's 55.- it("applies the quantity and date from the claim, not from the page", async () => {- const { db, driver } = database((q) =>- is.claim(q)- ? [- { id: "a-date", suggestedDate: "2026-11-09", suggestedQuantity: null },- { id: "a-qty", suggestedDate: null, suggestedQuantity: 75 }- ]- : everythingLands(q)- );- await applyPurchasingPlanningActions(db, {- ...scope,- actions: [expedite, increase]- });- const dates = driver.sent.find(is.dates)!;- expect(dates.parameters).toEqual(- expect.arrayContaining(["pol-date", "2026-11-09"])- );- expect(dates.parameters).not.toContain("2026-11-02");- const quantities = driver.sent.find(is.quantities)!;- expect(quantities.parameters).toEqual(- expect.arrayContaining(["pol-qty", 8, 0.1, 1.6])- );- expect(quantities.parameters).not.toContain(6);+ // The suggestion is what the line still has to bring: 6 to come on top of+ // the 2 received is 8; tax 2 × 8 × 10% = 1.60.+ it("adds what was already received to the quantity still to come", () => {+ expect(+ planningQuantityChange(base({ quantityReceived: 2 }), decimals, 55)+ ).toMatchObject({ ok: true, quantity: 8, amount: 1.6 });});- // Another apply took the row first: its line is never written here.- it("leaves an action another apply already claimed alone", async () => {- const { db, driver } = database((q) =>- is.claim(q) ? ids(["a-qty"]) : everythingLands(q)- );- const result = await applyPurchasingPlanningActions(db, {- ...scope,- actions: [expedite, increase]- });- expect(result.alreadyApplied).toEqual(["a-date"]);- expect(result.applied).toEqual(["a-qty"]);- expect(driver.sent.filter(is.dates)).toHaveLength(0);+ it("marks the line received when nothing more is to come", () => {+ expect(+ planningQuantityChange(base({ quantityReceived: 6 }), decimals, 0)+ ).toMatchObject({ ok: true, quantity: 6, receivedComplete: true });});- // The PO was sent after the page loaded: the guarded write changes nothing,- // the action goes back to Open for review, in the same transaction.- it("un-claims an action whose write was refused", async () => {- const { db, driver } = database((q) => {- if (is.dates(q)) return [];- if (is.reopen(q)) return ids(["a-date"]);- return everythingLands(q);- });- const result = await applyPurchasingPlanningActions(db, {- ...scope,- actions: [expedite, increase]- });- expect(result.refused).toEqual([{ id: "a-date", purchaseOrderId: "po1" }]);- expect(result.applied).toEqual(["a-qty"]);- const reopen = driver.sent.find(is.reopen)!;- expect(reopen.parameters).toEqual(expect.arrayContaining(["a-date", "c1"]));- expect(driver.sent.filter(is.drop)).toHaveLength(0);+ // 1.1 / 0.1 is 11.000000000000002 in floating point; a bare ceil makes 12.+ it("does not round float noise up a whole purchase unit", () => {+ expect(+ planningQuantityChange(base({ conversionFactor: 0.1 }), decimals, 1.1)+ ).toMatchObject({ ok: true, quantity: 11 });});- // An MRP run meanwhile wrote a fresh Open row for the same need, so the- // un-claim would collide with the natural-key index: the claimed row is- // deleted instead, as releasePlanningActionClaim does.- it("deletes a refused action that a fresh MRP row has replaced", async () => {- const { db, driver } = database((q) => {- if (is.dates(q)) return [];- if (is.reopen(q)) return [];- return everythingLands(q);- });- await applyPurchasingPlanningActions(db, {- ...scope,- actions: [expedite]- });- const drop = driver.sent.find(is.drop)!;- expect(drop.parameters).toEqual(- expect.arrayContaining(["a-date", "c1", "Actioned"])- );+ it("treats a line with no conversion factor as one to one", () => {+ expect(+ planningQuantityChange(base({ conversionFactor: null }), decimals, 5)+ ).toMatchObject({ ok: true, quantity: 5 });});- it("reports a line whose currency has no precision, and un-claims it", async () => {- const { db, driver } = database((q) => {- if (is.currencies(q)) return [];- if (is.reopen(q)) return ids(["a-qty"]);- return everythingLands(q);- });- const result = await applyPurchasingPlanningActions(db, {- ...scope,- actions: [increase]- });- expect(result.failed).toEqual([- { id: "a-qty", message: "Currency USD has no precision" }- ]);- expect(result.applied).toEqual([]);- expect(driver.sent.filter(is.quantities)).toHaveLength(0);- expect(driver.sent.filter(is.reopen)).toHaveLength(1);+ // A PO with no currency is in the company's base currency. JPY has no+ // minor unit: 2 × 6 × 10% = 1.2 rounds to 1.+ it("prices a PO with no currency in the company's base currency", () => {+ expect(+ planningQuantityChange(+ base({ currencyCode: null, baseCurrencyCode: "JPY" }),+ decimals,+ 55+ )+ ).toMatchObject({ ok: true, quantity: 6, amount: 1 });});- it("sends nothing for an empty batch", async () => {- const { db, driver } = database(everythingLands);- const result = await applyPurchasingPlanningActions(db, {- ...scope,- actions: []- });- expect(result.applied).toEqual([]);- expect(driver.sent).toHaveLength(0);+ it.each([+ ["the line was not found", undefined],+ ["its currency has no precision", base({ currencyCode: "XTS" })],+ [+ "it has no currency at all",+ base({ currencyCode: null, baseCurrencyCode: null })+ ]+ ])("cannot compute a change when %s", (_label, line) => {+ expect(planningQuantityChange(line, decimals, 55).ok).toBe(false);});});diff --git a/apps/erp/test/assembly-operations.test.ts b/apps/erp/test/assembly-operations.test.tsindex 826c735fe1..50fa77fe1b 100644--- a/apps/erp/test/assembly-operations.test.ts+++ b/apps/erp/test/assembly-operations.test.ts@@ -2,133 +2,53 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { shouldStartAssemblyPlan } from "../app/modules/production/production.models";-// The assembly instruction operations' refusals: what is checked before the-// geometry service, the job, or another company's model is touched.+// Generating steps with no plan yet starts one, unless one is on its way.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("@carbon/env", async (importOriginal) => ({- ...(await importOriginal<typeof import("@carbon/env")>()),- ASSEMBLER_SERVICE_URL: "http://assembler.test"-}));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn(), warn: vi.fn() })-}));-const { trigger } = vi.hoisted(() => ({ trigger: vi.fn() }));-vi.mock("@carbon/jobs", () => ({ trigger, batchTrigger: vi.fn() }));-vi.mock("@carbon/planning", () => ({ runLocationSchedule: vi.fn() }));-vi.mock("../app/modules/production/production.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- createAssemblyPlanJob: vi.fn(async () => ({- data: { id: "plan1" },- error: null- })),- generateAssemblyStepsFromPlan: vi.fn(),- getLatestAssemblyPlanJob: vi.fn(async () => ({ data: null, error: null })),- syncAssemblyInstructionToOperation: vi.fn(),- syncAssemblyStepMaterialsFromMappings: vi.fn(async () => ({ created: 0 })),- upsertAssemblyComponentMapping: vi.fn(async () => ({ error: null }))-}));+const now = new Date("2026-10-20T12:00:00Z");+const minutesAgo = (minutes: number) =>+ new Date(now.getTime() - minutes * 60_000).toISOString();-import {- generateAssemblyStepsFromPlan,- syncAssemblyInstructionToOperation,- upsertAssemblyComponentMapping-} from "../app/modules/production/production.service";-import {- generateAssemblySteps,- mapAssemblyComponent,- syncAssemblyToOperation-} from "../app/modules/production/production.server";-import { createServiceContext } from "@carbon/api/service-fn.server";+beforeEach(() => vi.useFakeTimers({ now }));+afterEach(() => vi.useRealTimers());-/** A client that answers every table's single-row read with `rows[table]`. */-function clientWith(rows: Record<string, unknown>) {- return {- from: (table: string) => {- const chain: Record<string, unknown> = {};- for (const method of ["select", "eq"]) chain[method] = () => chain;- chain.maybeSingle = async () => ({- data: rows[table] ?? null,- error: null- });- return chain;+describe("shouldStartAssemblyPlan", () => {+ it.each(["Queued", "Processing"])(+ "waits for a model that is %s",+ (processingStatus) => {+ expect(shouldStartAssemblyPlan(processingStatus, null)).toBe(false);}- };-}--const contextWith = (rows: Record<string, unknown> = {}) =>- createServiceContext({- actor: {- type: "user",- userId: "u1",- permissions: {- production: { view: [], create: [], update: ["c1"], delete: [] }- }- },- company: { id: "c1", groupId: "g1" },- caller: clientWith(rows) as never,- system: () => clientWith(rows) as never,- pg: () => ({}) as never,- kv: () => ({}) as never- });--beforeEach(() => {- vi.clearAllMocks();- vi.stubGlobal(- "fetch",- vi.fn(async () => ({ ok: true })));-});-describe("syncAssemblyToOperation", () => {- it("refuses an operation on a locked job", async () => {- const result = await syncAssemblyToOperation(- contextWith({ jobOperation: { id: "op1", job: { status: "Closed" } } }),- { id: "ai1", operationId: "op1" }- );- expect(result.error?.category).toBe("rule");- expect(syncAssemblyInstructionToOperation).not.toHaveBeenCalled();+ it("starts a plan for a converted model with no plan job", () => {+ expect(shouldStartAssemblyPlan("Success", null)).toBe(true);});-});--describe("mapAssemblyComponent", () => {- it("refuses a model that is not this company's", async () => {- const result = await mapAssemblyComponent(- contextWith({ item: { id: "i1" } }),- { id: "ai1", modelUploadId: "mu1", geometryHash: "g1", itemId: "i1" }- );- expect(result.error?.category).toBe("notFound");- expect(upsertAssemblyComponentMapping).not.toHaveBeenCalled();- });-});-describe("generateAssemblySteps", () => {- it("does not start a plan while the model is still converting", async () => {- vi.mocked(generateAssemblyStepsFromPlan).mockResolvedValueOnce({- ok: false,- reason: "no-plan",- modelUploadId: "mu1"- });- await generateAssemblySteps(- contextWith({ modelUpload: { processingStatus: "Processing" } }),- { id: "ai1" }- );- expect(trigger).not.toHaveBeenCalled();+ it.each([+ ["Queued", 1],+ ["Processing", 30]+ ])("waits for a %s plan job started %i minutes ago", (status, minutes) => {+ expect(+ shouldStartAssemblyPlan("Success", {+ status,+ createdAt: minutesAgo(minutes)+ })+ ).toBe(false);});- it("refuses to generate over existing steps", async () => {- vi.mocked(generateAssemblyStepsFromPlan).mockResolvedValueOnce({- ok: false,- reason: "steps-exist"- });- const result = await generateAssemblySteps(contextWith(), { id: "ai1" });- expect(result.error).toMatchObject({- category: "rule",- message: "Steps already exist — delete them before generating from the plan"- });+ // A worker that died leaves its row behind; past the stale window it is not running.+ it.each([+ ["Queued", 3],+ ["Processing", 46],+ ["Failed", 1]+ ])("starts over a %s plan job started %i minutes ago", (status, minutes) => {+ expect(+ shouldStartAssemblyPlan("Success", {+ status,+ createdAt: minutesAgo(minutes)+ })+ ).toBe(true);});});diff --git a/apps/erp/test/batch-suggestions.test.ts b/apps/erp/test/batch-suggestions.test.tsindex 44eb8ee163..1373008d60 100644--- a/apps/erp/test/batch-suggestions.test.ts+++ b/apps/erp/test/batch-suggestions.test.ts@@ -5,8 +5,6 @@import { resolveBatchRules } from "@carbon/utils";import { parseDate } from "@internationalized/date";import { describe, expect, it } from "vitest";-// Import the logic module directly — the ERP barrels drag lingui macros vitest-// does not transform (see batching-migration-guards.test.ts).import {batchPlanBreakdown,candidateValueSets,diff --git a/apps/erp/test/batching-migration-guards.test.ts b/apps/erp/test/batching-migration-guards.test.tsdeleted file mode 100644index 3bcb34c529..0000000000--- a/apps/erp/test/batching-migration-guards.test.ts+++ /dev/null@@ -1,76 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { readFileSync } from "node:fs";-import { join } from "node:path";-import { describe, expect, test } from "vitest";--// Regression guards for the Job Operation Batching migration (#1010). These read-// the migration text directly — no DB, no app imports (the ERP barrels drag-// lingui `msg` macros vitest does not transform). They pin the correctness-// properties of the batch candidate RPC and the batch status enum. The feature-// ships as ONE consolidated migration (v2), so everything is asserted against it.--const migrations = join(- process.cwd(),- "..",- "..",- "packages",- "database",- "supabase",- "migrations"-);-const read = (rel: string) => readFileSync(join(migrations, rel), "utf8");--const migration = read("20260905132037_job-operation-batching.sql");--describe("get_batchable_operations is tenant-scoped via RLS", () => {- test("the candidate RPC runs as SECURITY INVOKER so the caller's RLS applies", () => {- // SECURITY INVOKER is what scopes candidates to the caller's company — the- // function itself takes no companyId, so a DEFINER function would leak every- // company's operations.- expect(migration).toMatch(- /CREATE OR REPLACE FUNCTION get_batchable_operations[\s\S]*?SECURITY INVOKER/- );- });-});--describe("started operations are excluded from batch candidates", () => {- test("the RPC adds a NOT EXISTS productionEvent guard", () => {- expect(migration).toMatch(- /NOT EXISTS\s*\([\s\S]*?FROM "productionEvent" pe[\s\S]*?pe\."jobOperationId"\s*=\s*jo\."id"/- );- });-- test("the lane branch renders Active AND Completing batches (read-only Completing)", () => {- // The board shows Active batches (drag targets) and Completing batches- // (read-only, awaiting a retry in MES). Both must appear as lanes. The- // consolidated migration also renders the pre-floor 'Planned' state, which- // this assertion allows without letting Active/Completing drop out.- expect(migration).toMatch(- /OR b\."status"\s+IN\s*\('Planned',\s*'Active',\s*'Completing'\)/- );- });-});--describe("batch status enum", () => {- test("is Planned/Active/Completing/Completed with Completing from day one", () => {- // 'Planned' (pre-floor planning) joined the enum in the consolidated- // migration; 'Completing' still ships in the same CREATE TYPE rather than- // being bolted on by a later ALTER, which is what this pins.- expect(migration).toMatch(- /CREATE TYPE "jobOperationBatchStatus" AS ENUM \('Planned', 'Active', 'Completing', 'Completed'\)/- );- });-- test("has no Cancelled value (dissolve deletes the row instead)", () => {- // A dead enum state forces unreachable UI branches and cannot be removed- // later. The enum declaration must not contain 'Cancelled'.- const enumDecl = migration.match(- /CREATE TYPE "jobOperationBatchStatus" AS ENUM \([^)]*\)/- );- expect(enumDecl).not.toBeNull();- expect(enumDecl?.[0]).not.toContain("Cancelled");- });-});diff --git a/apps/erp/test/batching-tenant-scope-and-fk-locks.test.ts b/apps/erp/test/batching-tenant-scope-and-fk-locks.test.tsdeleted file mode 100644index 7878f44441..0000000000--- a/apps/erp/test/batching-tenant-scope-and-fk-locks.test.ts+++ /dev/null@@ -1,103 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { readFileSync } from "node:fs";-import { join } from "node:path";-import { describe, expect, test } from "vitest";--// Tenant-isolation regression guards for Job Operation Batching (#1010).-// Originally from PR #1137; rewritten for the v2 consolidated migration, which-// scopes candidates via SECURITY INVOKER + RLS (not a company_id parameter) and-// pins batch membership to a company via COMPOSITE tenant FKs. The property-// protected is the same: a batch and its members can never cross a tenant-// boundary. Reads the migration + service text directly — no DB, no app imports-// (the ERP barrels drag lingui `msg` macros vitest does not transform).--const migrations = join(- process.cwd(),- "..",- "..",- "packages",- "database",- "supabase",- "migrations"-);-const read = (rel: string) => readFileSync(join(migrations, rel), "utf8");-const migration = read("20260905132037_job-operation-batching.sql");--describe("batch candidates are tenant-scoped (AC[0])", () => {- test("get_batchable_operations runs SECURITY INVOKER so the caller's RLS scopes rows", () => {- // The function takes no company_id; SECURITY INVOKER means the caller's RLS- // on jobOperation/job restricts candidates to their own company. A DEFINER- // function would leak every company's operations.- expect(migration).toMatch(- /CREATE OR REPLACE FUNCTION get_batchable_operations[\s\S]*?SECURITY INVOKER/- );- });-- test("the JS wrapper passes location + process (no cross-tenant id)", () => {- const service = readFileSync(- join(- process.cwd(),- "app",- "modules",- "production",- "production.service.ts"- ),- "utf8"- );- expect(service).toMatch(/location_id:\s*args\.locationId/);- expect(service).toMatch(/process_id:\s*args\.processId/);- });-});--describe("batch membership is pinned to one company via composite FKs", () => {- test("jobOperation + productionEvent membership FKs carry companyId into the reference", () => {- // A member operation (or its timer) can only join a batch in the SAME- // company — the FK references ("id", "companyId"), not just ("id").- expect(migration).toMatch(- /ADD CONSTRAINT "jobOperation_jobOperationBatchId_fkey"\s*FOREIGN KEY \("jobOperationBatchId", "companyId"\)\s*REFERENCES "jobOperationBatch"\("id", "companyId"\)/s- );- expect(migration).toMatch(- /ADD CONSTRAINT "productionEvent_jobOperationBatchId_fkey"\s*FOREIGN KEY \("jobOperationBatchId", "companyId"\)\s*REFERENCES "jobOperationBatch"\("id", "companyId"\)/s- );- });-- test("member FKs SET NULL only jobOperationBatchId, not the NOT NULL companyId", () => {- // A column-list-less `ON DELETE SET NULL` on a multi-column FK nulls EVERY- // referencing column, including the NOT NULL `companyId` — so deleting a- // batch (or a `DELETE FROM company` cascade) would raise a not-null- // violation. The PG15 column-list form nulls ONLY the batch pointer.- // The standalone 20260904151137 fix was folded into the consolidated- // batching migration when #1550 was squashed, so assert against that.- expect(migration).toMatch(- /ADD CONSTRAINT "jobOperation_jobOperationBatchId_fkey"[\s\S]*?ON DELETE SET NULL \("jobOperationBatchId"\)/- );- expect(migration).toMatch(- /ADD CONSTRAINT "productionEvent_jobOperationBatchId_fkey"[\s\S]*?ON DELETE SET NULL \("jobOperationBatchId"\)/- );- });-- test("jobOperationBatch has a composite tenant PK and companyId FK", () => {- expect(migration).toMatch(- /PRIMARY KEY \("id", "companyId"\)/- );- expect(migration).toMatch(- /"jobOperationBatch_companyId_fkey" FOREIGN KEY \("companyId"\)\s*REFERENCES "company"\("id"\)/s- );- });-- test("RLS gates reads to employees and mutations to production permissions", () => {- expect(migration).toMatch(- /CREATE POLICY "SELECT" ON "public"\."jobOperationBatch"[\s\S]*?get_companies_with_employee_role\(\)/- );- for (const action of ["create", "update", "delete"]) {- expect(migration).toMatch(- new RegExp(- `get_companies_with_employee_permission\\('production_${action}'\\)`- )- );- }- });-});diff --git a/apps/erp/app/modules/purchasing/lease-writes.test.ts b/apps/erp/test/database/post-lease/draft-lease-writes.test.tssimilarity index 80%rename from apps/erp/app/modules/purchasing/lease-writes.test.tsrename to apps/erp/test/database/post-lease/draft-lease-writes.test.tsindex f586b53e97..2987d3b6b6 100644--- a/apps/erp/app/modules/purchasing/lease-writes.test.ts+++ b/apps/erp/test/database/post-lease/draft-lease-writes.test.ts@@ -3,84 +3,30 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.// A Draft lease's terms and assets are saved together with the payment rows-// cut from them, in one transaction. Live database: the writes are Kysely-// transactions, so they cannot be faked.+// cut from them, in one transaction.-import { readFileSync } from "node:fs";import { sql } from "kysely";-import { expect, it, vi } from "vitest";--// purchasing.server's operations reach modules whose `msg` macros only run-// compiled.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("@carbon/content/glossary", () => ({- getDefinitionText: () => "",- getEntry: () => undefined,- getTermText: () => "",- glossaryEntries: () => [],- hasEntry: () => false,- listEntries: () => [],- lookupEntry: () => undefined,- termSlug: (t: string) => t,- terms: {}-}));--import { leaseFixture } from "../../../test/database/fixtures/lease";+import { expect } from "vitest";import {leaseOpeningAsOf,regenerateLeasePayments,saveDraftLeaseLine,updateDraftLease-} from "./purchasing.service";--const LOCAL_HOSTS = ["localhost", "127.0.0.1", "[::1]"];--// vitest.config.ts stubs SUPABASE_DB_URL for every ERP test, so the local-// database is read from the repository's .env.local. Without one, or with-// the stack down, the tests skip.-const localDatabaseUrl = (() => {- try {- const env = readFileSync(- new URL("../../../../../.env.local", import.meta.url),- "utf8"- );- const url = env.match(/^SUPABASE_DB_URL=(.+)$/m)?.[1]?.trim();- return url && LOCAL_HOSTS.includes(new URL(url).hostname) ? url : null;- } catch {- return null;- }-})();+} from "../../../app/modules/purchasing/purchasing.service";+import { leaseFixture } from "../fixtures/lease";+import { databaseTest } from "../fixtures/local-database";type Fixture = Awaited<ReturnType<typeof leaseFixture>>;function leaseTest(name: string, fn: (f: Fixture) => Promise<void>) {- it.skipIf(!localDatabaseUrl)(- name,- async (context) => {- process.env.SUPABASE_DB_URL = localDatabaseUrl!;- let f: Fixture;- try {- f = await leaseFixture();- } catch (error) {- if (- error instanceof Error &&- "code" in error &&- error.code === "ECONNREFUSED"- ) {- context.skip();- }- throw error;- }- try {- await fn(f);- } finally {- await f.cleanup();- }- },- 60_000- );+ databaseTest(name, async () => {+ const f = await leaseFixture();+ try {+ await fn(f);+ } finally {+ await f.cleanup();+ }+ });}/** The terms the fixture's lease was created with, as the validator givesdiff --git a/apps/erp/app/modules/accounting/lease-run-posting.test.ts b/apps/erp/test/database/post-lease/lease-run.test.tssimilarity index 66%rename from apps/erp/app/modules/accounting/lease-run-posting.test.tsrename to apps/erp/test/database/post-lease/lease-run.test.tsindex e2af1b1bf5..ec435483c7 100644--- a/apps/erp/app/modules/accounting/lease-run-posting.test.ts+++ b/apps/erp/test/database/post-lease/lease-run.test.ts@@ -3,77 +3,21 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.// Posting a lease run stamps each lessee schedule line it posts; reversing-// the run clears the stamps. Live database: the posting is one Kysely-// transaction, so it cannot be faked.+// the run clears the stamps. The posting is one Kysely transaction.-import { readFileSync } from "node:fs";-import { expect, it, vi } from "vitest";--// accounting.service (imported by accounting.server) reaches the settings-// barrel and the glossary, whose Lingui `msg` macros vitest does not-// transform. Nothing under test uses them.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("~/modules/settings/settings.service", () => ({- getNextSequence: vi.fn()-}));-vi.mock("@carbon/content/glossary", () => ({- getDefinitionText: () => "",- getEntry: () => undefined,- getTermText: () => "",- glossaryEntries: () => [],- hasEntry: () => false,- listEntries: () => [],- lookupEntry: () => undefined,- termSlug: (t: string) => t,- terms: {}-}));--import { leaseFixture } from "../../../test/database/fixtures/lease";-import { holdInDraftRun } from "../../../test/database/fixtures/run";+import { expect } from "vitest";import {postRevenueRecognitionRun,reverseRevenueRecognitionRun-} from "./accounting.service";--const LOCAL_HOSTS = ["localhost", "127.0.0.1", "[::1]"];--// vitest.config.ts stubs SUPABASE_DB_URL for every ERP test, so the local-// database is read from the repository's .env.local. Without one (CI, a-// clean checkout), or with the stack down, the test skips, as the-// server-functions regressions do.-const localDatabaseUrl = (() => {- try {- const env = readFileSync(- new URL("../../../../../.env.local", import.meta.url),- "utf8"- );- const url = env.match(/^SUPABASE_DB_URL=(.+)$/m)?.[1]?.trim();- return url && LOCAL_HOSTS.includes(new URL(url).hostname) ? url : null;- } catch {- return null;- }-})();+} from "../../../app/modules/accounting/accounting.service";+import { leaseFixture } from "../fixtures/lease";+import { databaseTest } from "../fixtures/local-database";+import { holdInDraftRun } from "../fixtures/run";-it.skipIf(!localDatabaseUrl)(+databaseTest("a lease run stamps its lessee schedule lines and Reverse Run clears them",- async (context) => {- process.env.SUPABASE_DB_URL = localDatabaseUrl!;- let f: Awaited<ReturnType<typeof leaseFixture>>;- try {- f = await leaseFixture();- } catch (error) {- // .env.local exists in every worktree; the stack may simply be down.- if (- error instanceof Error &&- "code" in error &&- error.code === "ECONNREFUSED"- ) {- context.skip();- }- throw error;- }+ async () => {+ const f = await leaseFixture();try {const { db, companyId, leaseId, accounts } = f;const leaseLineId = f.lineIds[0]!;@@ -195,6 +139,5 @@ it.skipIf(!localDatabaseUrl)(} finally {await f.cleanup();}- },- 60_000+ });diff --git a/apps/erp/test/database/post-rental-agreement/__snapshots__/return-unit.test.ts.snap b/apps/erp/test/database/post-rental-agreement/__snapshots__/return-unit.test.ts.snapdeleted file mode 100644index 49f178e251..0000000000--- a/apps/erp/test/database/post-rental-agreement/__snapshots__/return-unit.test.ts.snap+++ /dev/null@@ -1,32 +0,0 @@-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html--exports[`an early return of an Advance unit re-cuts its periods 1`] = `-{- "line": {- "returnedAt": "2026-09-20",- "status": "Returned",- },- "periods": [- {- "amount": 300,- "days": 30,- "dueOn": "2026-09-01",- "isAdjustment": false,- "periodEnd": "2026-09-30",- "periodStart": "2026-09-01",- "rateUnitApplied": null,- "status": "Invoiced",- },- {- "amount": -100,- "days": 20,- "dueOn": "2026-09-20",- "isAdjustment": true,- "periodEnd": "2026-09-30",- "periodStart": "2026-09-01",- "rateUnitApplied": "Month",- "status": "Pending",- },- ],-}-`;diff --git a/apps/erp/test/database/post-rental-agreement/return-unit.test.ts b/apps/erp/test/database/post-rental-agreement/return-unit.test.tsindex 5e8bf34eb5..be4d67044c 100644--- a/apps/erp/test/database/post-rental-agreement/return-unit.test.ts+++ b/apps/erp/test/database/post-rental-agreement/return-unit.test.ts@@ -2,9 +2,9 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-// Pins today's unit return against the live database, so moving the return-// body into `returnRentalUnit` cannot change what it writes. It acts through-// a rental receipt, which re-cuts the periods exactly as the old return did.+// Returning a rental unit through a rental receipt re-cuts its billing+// periods: the invoiced period gets a credit for the unused days and the+// periods after the return are dropped.import { sql } from "kysely";import { expect } from "vitest";@@ -85,7 +85,31 @@ databaseTest(.where("companyId", "=", f.companyId).executeTakeFirstOrThrow();- expect({ periods, line }).toMatchSnapshot();+ // Sep (30 days, 300) was invoiced in advance; used Sep 1-20 = 20 days:+ // 300 * 20/30 - 300 = -100. October, after the return, is dropped.+ expect(periods).toEqual([+ {+ periodStart: "2026-09-01",+ periodEnd: "2026-09-30",+ days: 30,+ amount: 300,+ isAdjustment: false,+ status: "Invoiced",+ rateUnitApplied: null,+ dueOn: "2026-09-01"+ },+ {+ periodStart: "2026-09-01",+ periodEnd: "2026-09-30",+ days: 20,+ amount: -100,+ isAdjustment: true,+ status: "Pending",+ rateUnitApplied: "Month",+ dueOn: "2026-09-20"+ }+ ]);+ expect(line).toEqual({ status: "Returned", returnedAt: "2026-09-20" });} finally {await f.cleanup();}diff --git a/apps/erp/test/i18n-react-macros.test.ts b/apps/erp/test/i18n-react-macros.test.tsdeleted file mode 100644index 550ea482ec..0000000000--- a/apps/erp/test/i18n-react-macros.test.ts+++ /dev/null@@ -1,78 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { readdirSync, readFileSync, statSync } from "node:fs";-import path from "node:path";-import { describe, expect, it } from "vitest";--const appRoot = path.resolve(__dirname, "../app");-const allowedExtensions = new Set([".ts", ".tsx"]);-const excludedSegments = [- ".server.",- ".test.",- ".spec.",- `${path.sep}locales${path.sep}`-];--function collectFiles(dir: string): string[] {- const files: string[] = [];-- for (const entry of readdirSync(dir)) {- const fullPath = path.join(dir, entry);- const stats = statSync(fullPath);-- if (stats.isDirectory()) {- files.push(...collectFiles(fullPath));- continue;- }-- if (!allowedExtensions.has(path.extname(fullPath))) {- continue;- }-- if (excludedSegments.some((segment) => fullPath.includes(segment))) {- continue;- }-- files.push(fullPath);- }-- return files;-}--function relative(filePath: string): string {- return path.relative(path.resolve(__dirname, ".."), filePath);-}--// These assertions mirror `.claude/rules/i18n-lingui-system.md`. Keep them in-// step with it — this file previously banned the `@lingui/core/macro` MODULE-// outright, which flagged 284 files for importing `msg`, the very pattern that-// rule prescribes for route breadcrumbs. A gate that contradicts the documented-// convention cannot be satisfied, so it was never run and rotted for months.-// What the rule actually prohibits is narrower, and is what is checked here.-describe("Lingui React macro migration", () => {- it("never imports the non-contextual `t` from @lingui/core/macro", () => {- // No `runtimeConfigModule` is configured, so this `t` would resolve against- // a global i18n instance rather than the request's.- const offenders = collectFiles(appRoot).filter((filePath) =>- /import\s*\{[^}]*\bt\b[^}]*\}\s*from\s*['"]@lingui\/core\/macro['"]/.test(- readFileSync(filePath, "utf8")- )- );-- expect(offenders.map(relative)).toEqual([]);- });-- it("does not unwrap a literal `msg` at runtime instead of using `t`", () => {- // `i18n._(msg`Scrap`)` is the long way round to `t`Scrap``. Rendering a- // descriptor built ELSEWHERE — `i18n._(someDescriptor)` from a lookup map —- // is legitimate and deliberately not matched here.- const offenders = collectFiles(appRoot).filter((filePath) => {- const source = readFileSync(filePath, "utf8");- return /[._]\(\s*msg`/.test(source) || source.includes("t(msg(");- });-- expect(offenders.map(relative)).toEqual([]);- });-});diff --git a/apps/erp/test/inventory-operations.test.ts b/apps/erp/test/inventory-operations.test.tsindex b471507c07..27010a5a48 100644--- a/apps/erp/test/inventory-operations.test.ts+++ b/apps/erp/test/inventory-operations.test.ts@@ -2,60 +2,31 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { beforeEach, describe, expect, it, vi } from "vitest";--// The service's imports reach the glossary, whose `msg` macro only runs compiled.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn(), warn: vi.fn(), info: vi.fn() })-}));-const { evaluate } = vi.hoisted(() => ({- // Storage rules: the violations each surface reports.- evaluate: vi.fn()-}));-vi.mock("@carbon/ee/rules.server", async () => ({- // The real block / dedupe rules; only the rule reads are stubbed.- ...(await vi.importActual<typeof import("@carbon/ee/rules.server")>(- "@carbon/ee/rules.server"- )),- evaluateLinesForSurface: evaluate,- evaluateSalesRuleLines: vi.fn(),- resolveSalesOrderShipTo: vi.fn()-}));-// The packing slip renders a PDF through module barrels nothing here needs.-vi.mock("../app/modules/inventory/packing-slip.pdf", () => ({- renderPackingSlip: vi.fn()-}));-vi.mock("../app/modules/sales/sales.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- recordSalesRuleOutcome: vi.fn()-}));-vi.mock("../app/modules/inventory/inventory.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- getInventoryCount: vi.fn(),- // The adjustment posting: its database test is post-inventory-adjustment.- postInventoryAdjustment: vi.fn(),- postInventoryCount: vi.fn(),- // Reads the item's tracking type; the serial cap has its own database test.- serialQuantityRefusal: vi.fn(async () => null)-}));--import { InvalidInputError, ServerFnError } from "@carbon/api/errors";-import {- getInventoryCount,- pickRefusal,- postInventoryAdjustment,- postInventoryCount as postCount-} from "../app/modules/inventory/inventory.service";+import { describe, expect, it } from "vitest";+import { ServerFnError } from "@carbon/api/errors";+import { createServiceContext } from "@carbon/api/service-fn.server";import {adjustInventory,postInventoryCount} from "../app/modules/inventory/inventory.server";-import { createServiceContext } from "@carbon/api/service-fn.server";+import {+ adjustmentRuleSurfaces,+ inventoryCountPostingFailure,+ pickRefusal,+ postingFailure+} from "../app/modules/inventory/inventory.service";-const ctx = () =>+/** The caller's client: each table's one row. */+const clientWith = (rows: Record<string, unknown>) => ({+ from: (table: string) => {+ const chain: Record<string, unknown> = {};+ for (const method of ["select", "eq"]) chain[method] = () => chain;+ chain.single = async () => ({ data: rows[table] ?? null, error: null });+ return chain;+ }+});++const ctx = (rows: Record<string, unknown> = {}) =>createServiceContext({actor: {type: "user",@@ -70,29 +41,34 @@ const ctx = () =>}},company: { id: "company-1", groupId: "group-1" },- caller: {} as any,+ caller: clientWith(rows) as any,system: () => ({}) as any,pg: () => ({}) as any,kv: () => ({}) as any});-const violation = (severity: "error" | "warn") => ({- ruleId: `rule-${severity}`,- severity,- message: "No",- lineId: "item-1"-});+describe("adjustmentRuleSurfaces", () => {+ it.each([+ ["Scrap", "pick"],+ ["Negative Adjmt.", "pick"],+ ["Positive Adjmt.", "place"],+ ["Set Quantity", "place"],+ ["Unscrap", "place"]+ ] as const)("checks a %s's bin as a %s", (adjustmentType, surface) => {+ expect(adjustmentRuleSurfaces(adjustmentType, "bin-1")).toEqual([+ "inventoryAdjustment",+ surface+ ]);+ });-beforeEach(() => {- vi.clearAllMocks();- evaluate.mockResolvedValue({ violations: [], ruleNames: {} });- vi.mocked(postInventoryAdjustment).mockResolvedValue({- success: true,- itemLedger: { id: "ledger-1" }+ it("checks no bin rule when no bin is named", () => {+ expect(adjustmentRuleSurfaces("Scrap", undefined)).toEqual([+ "inventoryAdjustment"+ ]);});});-describe("adjustInventory", () => {+describe("adjustInventory input", () => {const scrap = {itemId: "item-1",adjustmentType: "Scrap" as const,@@ -101,135 +77,72 @@ describe("adjustInventory", () => {storageUnitId: "bin-1",scrapReasonId: "reason-1"};+ const parses = (input: object) => adjustInventory.input.safeParse(input).success;- it("is refused by a rule on the bin it takes stock from, and adjusts nothing", async () => {- // A scrap removes stock: only a `pick` rule applies to it.- evaluate.mockImplementation(async ({ surface }) => ({- violations: surface === "pick" ? [violation("error")] : [],- ruleNames: {}- }));-- const result = await adjustInventory(ctx(), scrap);-- expect(result.data).toMatchObject({- violations: [{ ruleId: "rule-error" }]- });- expect(postInventoryAdjustment).not.toHaveBeenCalled();+ it("accepts a scrap with its reason and location", () => {+ expect(parses(scrap)).toBe(true);});- it("ignores a rule on the bin it does not take stock from", async () => {- evaluate.mockImplementation(async ({ surface }) => ({- violations: surface === "place" ? [violation("error")] : [],- ruleNames: {}- }));-- const result = await adjustInventory(ctx(), scrap);-- expect(result.data).toEqual({ itemLedgerId: "ledger-1" });+ it.each([+ ["a scrap with no reason", { ...scrap, scrapReasonId: undefined }],+ ["an adjustment with no location", { ...scrap, locationId: undefined }],+ // The type says which way stock moves; the quantity is a magnitude.+ ["a negative quantity", { ...scrap, quantity: -2 }]+ ])("refuses %s", (_case, input) => {+ expect(parses(input)).toBe(false);});- it("adjusts past an acknowledged warning", async () => {- evaluate.mockResolvedValue({- violations: [violation("warn")],- ruleNames: {}- });-- const blocked = await adjustInventory(ctx(), scrap);- const acknowledged = await adjustInventory(ctx(), {- ...scrap,- acknowledged: true- });-- expect(blocked.data).toHaveProperty("violations");- expect(acknowledged.data).toEqual({ itemLedgerId: "ledger-1" });- });-- it("needs a scrap reason to scrap, and a location for all but an unscrap", async () => {- const noReason = await adjustInventory(ctx(), {- ...scrap,- scrapReasonId: undefined- });- const unscrap = await adjustInventory(ctx(), {- itemId: "item-1",- adjustmentType: "Unscrap",- quantity: 1,- trackedEntityId: "entity-1"- });-- expect(noReason.error?.category).toBe("validation");- expect(unscrap.data).toEqual({ itemLedgerId: "ledger-1" });+ it("takes an unscrap without a location: it resolves it from the scrap", () => {+ expect(+ parses({+ itemId: "item-1",+ adjustmentType: "Unscrap",+ quantity: 1,+ trackedEntityId: "entity-1"+ })+ ).toBe(true);});+});- it("passes the posting's own refusal through, and hides any other failure", async () => {- vi.mocked(postInventoryAdjustment)- .mockRejectedValueOnce(new InvalidInputError("Lot LOT-7 is on hold"))- .mockRejectedValueOnce(new Error("duplicate key"));-- const refused = await adjustInventory(ctx(), scrap);- const failed = await adjustInventory(ctx(), scrap);-- expect(refused.error).toMatchObject({- category: "validation",- message: "Lot LOT-7 is on hold"- });- expect(failed.error).toMatchObject({- category: "internal",- message: "Failed to create manual inventory adjustment"- });+describe("postingFailure", () => {+ it("passes a posting's own refusal through", () => {+ expect(+ postingFailure(ctx(), new ServerFnError("Lot LOT-7 is on hold", 400), "Failed")+ ).toMatchObject({ category: "validation", message: "Lot LOT-7 is on hold" });});- it("refuses a negative quantity: the type says which way stock moves", async () => {- const result = await adjustInventory(ctx(), { ...scrap, quantity: -2 });-- expect(result.error?.category).toBe("validation");- expect(postInventoryAdjustment).not.toHaveBeenCalled();+ it("hides any other failure behind the operation's message", () => {+ expect(+ postingFailure(ctx(), new ServerFnError("duplicate key", 500), "Failed")+ ).toMatchObject({ category: "internal", message: "Failed" });});});describe("postInventoryCount", () => {it("posts only a confirmed count", async () => {- vi.mocked(getInventoryCount).mockResolvedValue({- data: { status: "Draft" }- } as any);-- const result = await postInventoryCount(ctx(), { inventoryCountId: "c1" });-- expect(result.error).toMatchObject({ category: "rule" });- expect(postCount).not.toHaveBeenCalled();- });-- it("returns the lines that cannot post, so the page can mark them", async () => {- vi.mocked(getInventoryCount).mockResolvedValue({- data: { status: "Pending" }- } as any);- vi.mocked(postCount).mockRejectedValue(- new ServerFnError("1 serial line(s) must be counted as 0 or 1", 400, {- invalidLineIds: ["line-1"]- })+ const result = await postInventoryCount(+ ctx({ inventoryCount: { status: "Draft" } }),+ { inventoryCountId: "c1" });+ expect(result.error?.category).toBe("rule");+ });+});- const result = await postInventoryCount(ctx(), { inventoryCountId: "c1" });-- expect(result.data).toEqual({+describe("inventoryCountPostingFailure", () => {+ it("returns the lines that cannot post, so the page can mark them", () => {+ const error = new ServerFnError("1 serial line(s) must be counted as 0 or 1", 400, {+ invalidLineIds: ["line-1"]+ });+ expect(inventoryCountPostingFailure(ctx(), error)).toEqual({invalidLineIds: ["line-1"],message: "1 serial line(s) must be counted as 0 or 1"});});- it("keeps the server function's own status for any other refusal", async () => {- vi.mocked(getInventoryCount).mockResolvedValue({- data: { status: "Pending" }- } as any);- vi.mocked(postCount).mockRejectedValue(- new ServerFnError("Inventory count not found", 404)- );-- const result = await postInventoryCount(ctx(), { inventoryCountId: "c1" });-- expect(result.error).toMatchObject({- category: "notFound",- message: "Inventory count not found"- });+ it("keeps the server function's own status for any other refusal", () => {+ expect(+ inventoryCountPostingFailure(ctx(), new ServerFnError("Inventory count not found", 404))+ ).toMatchObject({ category: "notFound", message: "Inventory count not found" });});});diff --git a/apps/erp/test/items-operations.test.ts b/apps/erp/test/items-operations.test.tsindex efe566acf7..6a5c1eaf2c 100644--- a/apps/erp/test/items-operations.test.ts+++ b/apps/erp/test/items-operations.test.ts@@ -4,28 +4,14 @@import { beforeEach, describe, expect, it, vi } from "vitest";-// The module graph reaches Lingui `msg` macros at load, which only run compiled.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn(), warn: vi.fn(), info: vi.fn() })-}));const { trigger } = vi.hoisted(() => ({ trigger: vi.fn() }));vi.mock("@carbon/jobs", () => ({ trigger }));+// The approval engine works in the database; here it answers per test.vi.mock("@carbon/ee/approvals/document.server", () => ({openApprovalRequests: vi.fn(),cancelPendingApprovals: vi.fn(),decideApprovalRequest: vi.fn()}));-vi.mock("../app/modules/items/items.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- getItemSupersession: vi.fn(),- updateChangeNoticeStatus: vi.fn(),- updateItemMethodAndSourcing: vi.fn(),- upsertItemPlanning: vi.fn(),- upsertItemSupersession: vi.fn()-}));import { openApprovalRequests } from "@carbon/ee/approvals/document.server";import {@@ -36,13 +22,6 @@ import {setItemSourcing,updateItemPlanning} from "../app/modules/items/items.server";-import {- getItemSupersession,- updateChangeNoticeStatus,- updateItemMethodAndSourcing,- upsertItemPlanning,- upsertItemSupersession-} from "../app/modules/items/items.service";import { createServiceContext } from "@carbon/api/service-fn.server";type Write = {@@ -163,16 +142,12 @@ describe("setItemPostingGroup", () => {});describe("setItemSourcing", () => {- it("refuses a call that sets none, or more than one, of the three fields", async () => {- const inputs: Parameters<typeof setItemSourcing>[1][] = [- { ids: ["i1"] },- { ids: ["i1"], replenishmentSystem: "Make", sourcingType: "Drop Ship" }- ];- for (const input of inputs) {- const result = await setItemSourcing(contextFor(unreachable), input);- expect(result.error).toMatchObject({ category: "validation" });- }- expect(updateItemMethodAndSourcing).not.toHaveBeenCalled();+ it.each<Parameters<typeof setItemSourcing>[1]>([+ { ids: ["i1"] },+ { ids: ["i1"], replenishmentSystem: "Make", sourcingType: "Drop Ship" }+ ])("refuses a call that sets none, or more than one, of the three fields", async (input) => {+ const result = await setItemSourcing(contextFor(unreachable), input);+ expect(result.error).toMatchObject({ category: "validation" });});});@@ -226,7 +201,7 @@ describe("setChangeNoticeStatus", () => {});it("submits for approval instead of moving when a rule gates the step", async () => {- const { client } = fakeClient({+ const { client, writes } = fakeClient({changeOrder: { status: "Engineering Complete" }});vi.mocked(openApprovalRequests).mockResolvedValue({@@ -242,11 +217,11 @@ describe("setChangeNoticeStatus", () => {);expect(result.data).toMatchObject({ approvalRequested: true });- expect(updateChangeNoticeStatus).not.toHaveBeenCalled();+ expect(writes).toEqual([]);});it("refuses a second request while one is pending", async () => {- const { client } = fakeClient({+ const { client, writes } = fakeClient({changeOrder: { status: "Engineering Complete" }});vi.mocked(openApprovalRequests).mockResolvedValue({@@ -262,7 +237,7 @@ describe("setChangeNoticeStatus", () => {);expect(result.error).toMatchObject({ category: "conflict" });- expect(updateChangeNoticeStatus).not.toHaveBeenCalled();+ expect(writes).toEqual([]);});});@@ -283,16 +258,13 @@ describe("addItemPredecessor", () => {});it("refuses a predecessor that already has another successor", async () => {- const { client } = fakeClient({- item: { id: "old-part", readableIdWithRevision: "P1" }- });- vi.mocked(getItemSupersession).mockResolvedValue({- data: {+ const { client, writes } = fakeClient({+ item: { id: "old-part", readableIdWithRevision: "P1" },+ itemSupersession: {successorItemId: "other-part",successor: { readableIdWithRevision: "P9" }- },- error: null- } as any);+ }+ });const result = await addItemPredecessor(contextFor(client), {...predecessor,@@ -300,14 +272,13 @@ describe("addItemPredecessor", () => {});expect(result.error).toMatchObject({ category: "rule" });- expect(result.error?.message).toContain("P1 already has a successor (P9)");- expect(upsertItemSupersession).not.toHaveBeenCalled();+ expect(writes).toEqual([]);});});describe("updateItemPlanning", () => {it("refuses a responsible employee who is not an active employee of the company", async () => {- const { client } = fakeClient({ employee: null });+ const { client, writes } = fakeClient({ employee: null });const result = await updateItemPlanning(contextFor(client), {itemId: "i1",@@ -317,6 +288,6 @@ describe("updateItemPlanning", () => {});expect(result.error).toMatchObject({ category: "rule" });- expect(upsertItemPlanning).not.toHaveBeenCalled();+ expect(writes).toEqual([]);});});diff --git a/apps/erp/test/job-complete-logic.test.ts b/apps/erp/test/job-complete-logic.test.tsindex 5153cf6418..e3ccb10111 100644--- a/apps/erp/test/job-complete-logic.test.ts+++ b/apps/erp/test/job-complete-logic.test.ts@@ -3,8 +3,6 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { describe, expect, it } from "vitest";-// Import the logic module directly — the ERP barrels drag lingui macros vitest-// does not transform (see batching-migration-guards.test.ts).import {getDefaultSerialCompleteQuantity,getFinishedUnreceivedQuantity,diff --git a/apps/erp/test/job-lifecycle.test.ts b/apps/erp/test/job-lifecycle.test.tsindex 6bdfa691d7..3519b3f205 100644--- a/apps/erp/test/job-lifecycle.test.ts+++ b/apps/erp/test/job-lifecycle.test.ts@@ -8,69 +8,15 @@ import { beforeEach, describe, expect, it, vi } from "vitest";// what refuses it, and what is still reported when a step after the status// change fails.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("@carbon/env", async (importOriginal) => ({- ...(await importOriginal<typeof import("@carbon/env")>()),- ASSEMBLER_SERVICE_URL: ""-}));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn(), warn: vi.fn() })-}));vi.mock("@carbon/jobs", () => ({ trigger: vi.fn(), batchTrigger: vi.fn() }));vi.mock("@carbon/lib/telemetry", () => ({ trackWorkEvent: vi.fn() }));vi.mock("@carbon/lib/workflows", () => ({ raiseMoment: vi.fn() }));-const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }));-vi.mock("../app/modules/shared/shared.service", async (importOriginal) => {- const actual =- await importOriginal<- typeof import("../app/modules/shared/shared.service")- >();- // The postings the server functions package ran are the boundary; every- // other posting runs its (mocked) body as before.- const stubbed = new Set([- "issue",- "create",- "batch-operations",- "post-inventory-adjustment",- "post-maintenance-event",- "post-picking",- "post-production-event",- "recalculate",- "reschedule",- "trigger-rework"- ]);- return {- ...actual,- invokePosting: ((from: never, name: string, input: never, ...rest: never[]) =>- stubbed.has(name)- ? invoke(name, input)- : (actual.invokePosting as (...args: unknown[]) => unknown)(- from,- name,- input,- ...rest- )) as typeof actual.invokePosting,- invokeCreate: (_from: unknown, input: unknown) => invoke("create", input)- };-});-vi.mock("@carbon/planning", () => ({ runLocationSchedule: vi.fn() }));-vi.mock("../app/modules/production/production.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- recalculateJobRequirements: vi.fn(async () => ({ data: null, error: null })),- runMRP: vi.fn(async () => ({ data: null, error: null })),- returnPickedRemaindersForJob: vi.fn(async () => ({ data: {}, error: null })),- upsertProductionQuantity: vi.fn(async () => ({- data: { id: "pq1" },- error: null- }))+// MRP runs in process against the database; a resumed job's status move is the subject here.+vi.mock("@carbon/planning", () => ({+ runMrp: vi.fn(async () => null),+ runLocationSchedule: vi.fn()}));-import {- returnPickedRemaindersForJob,- upsertProductionQuantity-} from "../app/modules/production/production.service";import {closeJob,completeJob,@@ -83,6 +29,8 @@ import { createServiceContext } from "@carbon/api/service-fn.server";/** Every status the job was moved to, with the statuses the move allowed. */let statusWrites: { status: unknown; fromStatuses?: unknown }[] = [];+/** Every production quantity row inserted. */+let quantityInserts: Record<string, unknown>[] = [];/** The user client: the job as read, its status writes, and the completion RPC's answer. */function callerWith(@@ -106,8 +54,16 @@ function callerWith(};return write;};+ const insert = (rows: Record<string, unknown>[]) => {+ quantityInserts.push(...rows);+ return {+ select: () => ({+ single: async () => ({ data: { id: "pq1" }, error: null })+ })+ };+ };return {- from: () => ({ ...read, update }),+ from: () => ({ ...read, update, insert }),rpc: async () => ({ data: null, ...rpc })};}@@ -133,7 +89,7 @@ const flips = () => statusWrites;beforeEach(() => {vi.clearAllMocks();statusWrites = [];- invoke.mockResolvedValue({ data: {}, error: null });+ quantityInserts = [];});describe("pauseJob", () => {@@ -245,11 +201,11 @@ describe("closeJob", () => {{ jobId: "j1" });expect(result.error?.category).toBe("rule");- expect(invoke).not.toHaveBeenCalled();+ expect(flips()).toEqual([]);});it("keeps the job Closed and warns when the WIP write-off fails", async () => {- invoke.mockResolvedValueOnce({ data: null, error: new Error("no WIP") });+ // The write-off reads the database through `pg`, which this context lacks.const result = await closeJob(contextWith(callerWith({ status: "Completed" })),{ jobId: "j1" }@@ -264,7 +220,7 @@ describe("completeJob", () => {const complete = (caller: unknown) =>completeJob(contextWith(caller), { jobId: "j1", quantityComplete: 5 });- it("returns the database's refusal as a rule, and returns nothing picked", async () => {+ it("returns the database's refusal as a rule", async () => {const result = await complete(callerWith(null, {error: { message: "Quantity is below what was received" }@@ -274,19 +230,15 @@ describe("completeJob", () => {category: "rule",message: "Quantity is below what was received"});- expect(returnPickedRemaindersForJob).not.toHaveBeenCalled();});it("keeps the completion and warns when returning picked material fails", async () => {- vi.mocked(returnPickedRemaindersForJob).mockResolvedValueOnce({- data: null,- error: new Error("sweep failed")- } as never);+ // The sweep posts through `pg`, which this context lacks.const result = await complete(callerWith(null));- expect(result.error).toBeNull();- expect(result.data?.warning).toBe(- "Job completed, but returning picked material failed"- );+ expect(result).toEqual({+ data: { jobId: "j1", warning: expect.any(String) },+ error: null+ });});});@@ -305,16 +257,15 @@ describe("createProductionQuantity", () => {it("refuses a locked job", async () => {const result = await record("Completed", "Production");expect(result.error?.category).toBe("rule");- expect(upsertProductionQuantity).not.toHaveBeenCalled();+ expect(quantityInserts).toEqual([]);});it("keeps a scrap reason only on scrap", async () => {await record("In Progress", "Production");await record("In Progress", "Scrap");- expect(- vi- .mocked(upsertProductionQuantity)- .mock.calls.map(([, quantity]) => quantity.scrapReasonId)- ).toEqual([undefined, "sr1"]);+ expect(quantityInserts.map((row) => row.scrapReasonId)).toEqual([+ undefined,+ "sr1"+ ]);});});diff --git a/apps/erp/test/job-material.test.ts b/apps/erp/test/job-material.test.tsindex 254a8d9329..dfdd453c31 100644--- a/apps/erp/test/job-material.test.ts+++ b/apps/erp/test/job-material.test.ts@@ -2,62 +2,32 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it } from "vitest";-// What a material save does around the row write: a Make to Order material-// pulls its item's method (on create, and only on the change INTO Make to-// Order on update), and the recalculations that fill its estimates. Without-// them a material sat at estimatedQuantity 0 and picking pulled nothing.+// What a material save does around the row write: which parents it refuses,+// and when the recalculation that fills the material's estimates runs.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("@carbon/env", async (importOriginal) => ({- ...(await importOriginal<typeof import("@carbon/env")>()),- ASSEMBLER_SERVICE_URL: ""-}));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn(), warn: vi.fn() })-}));-vi.mock("@carbon/jobs", () => ({ trigger: vi.fn(), batchTrigger: vi.fn() }));-vi.mock("@carbon/planning", () => ({ runLocationSchedule: vi.fn() }));-vi.mock("../app/modules/production/production.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- upsertJobMaterial: vi.fn(async () => ({- data: { id: "jm1", methodType: "Pull from Inventory" },- error: null- })),- pullJobMaterialMakeMethod: vi.fn(async () => ({ data: {}, error: null })),- recalculateJobMakeMethodRequirements: vi.fn(async () => ({- data: {},- error: null- })),- recalculateJobOperationDependencies: vi.fn(async () => ({- data: {},- error: null- }))-}));--import {- pullJobMaterialMakeMethod,- recalculateJobMakeMethodRequirements,- recalculateJobOperationDependencies,- upsertJobMaterial-} from "../app/modules/production/production.service";import {createJobMaterial,updateJobMaterial} from "../app/modules/production/production.server";import { createServiceContext } from "@carbon/api/service-fn.server";-/** The caller's and the service-role client: each table's one row, or none. */-function systemWith(rows: Record<string, unknown>) {+/** Each table's one row, or none; `jobMaterial` writes are recorded and echo an id. */+function clientWith(rows: Record<string, unknown>, writes: string[]) {return {from: (table: string) => {const chain: Record<string, unknown> = {};for (const method of ["select", "eq"]) chain[method] = () => chain;- chain.maybeSingle = async () => ({- data: rows[table] ?? null,+ const write = (op: string) => () => {+ writes.push(`${op} ${table}`);+ return chain;+ };+ chain.insert = write("insert");+ chain.update = write("update");+ chain.maybeSingle = async () => ({ data: rows[table] ?? null, error: null });+ chain.single = async () => ({+ data: { id: "jm1", methodType: "Pull from Inventory" },error: null});return chain;@@ -65,8 +35,12 @@ function systemWith(rows: Record<string, unknown>) {} as never;}-const contextWith = (rows: Record<string, unknown>) =>- createServiceContext({+// The recalculation is the only step that opens the database connection.+const recalculation = new Error("recalculation reached the database");++function save(rows: Record<string, unknown>) {+ const writes: string[] = [];+ const ctx = createServiceContext({actor: {type: "user",userId: "u1",@@ -75,11 +49,15 @@ const contextWith = (rows: Record<string, unknown>) =>}},company: { id: "c1", groupId: "g1" },- caller: systemWith(rows),- system: () => systemWith(rows),- pg: () => ({}) as never,+ caller: clientWith(rows, writes),+ system: () => clientWith(rows, writes),+ pg: () => {+ throw recalculation;+ },kv: () => ({}) as never});+ return { ctx, writes };+}const material = {id: "jm1",@@ -99,35 +77,37 @@ const material = {};const parents = { jobMakeMethod: { id: "jmm1" }, jobOperation: { id: "op1" } };-beforeEach(() => vi.clearAllMocks());-describe("createJobMaterial", () => {- it("leaves a Draft job's estimates to the release", async () => {- const result = await createJobMaterial(- contextWith({ job: { status: "Draft" }, ...parents }),- material- );- expect(result).toEqual({ data: { id: "jm1" }, error: null });- expect(recalculateJobMakeMethodRequirements).not.toHaveBeenCalled();- expect(recalculateJobOperationDependencies).not.toHaveBeenCalled();+ it.each(["Draft", "Planned"])(+ "leaves a %s job's estimates to the release",+ async (status) => {+ const { ctx, writes } = save({ job: { status }, ...parents });+ const result = await createJobMaterial(ctx, material);+ expect(result).toEqual({ data: { id: "jm1" }, error: null });+ expect(writes).toEqual(["insert jobMaterial"]);+ }+ );++ it("recalculates a released job's estimates after the insert", async () => {+ const { ctx, writes } = save({ job: { status: "Ready" }, ...parents });+ const result = await createJobMaterial(ctx, material);+ expect(writes).toEqual(["insert jobMaterial"]);+ expect(result.error?.cause).toBe(recalculation);});+it("refuses a make method that is not the job's", async () => {- const result = await createJobMaterial(- contextWith({ job: { status: "Draft" } }),- material- );+ const { ctx, writes } = save({ job: { status: "Draft" } });+ const result = await createJobMaterial(ctx, material);expect(result.error?.category).toBe("notFound");- expect(upsertJobMaterial).not.toHaveBeenCalled();+ expect(writes).toEqual([]);});});describe("updateJobMaterial", () => {it("refuses a material that is not on this job and method", async () => {- const result = await updateJobMaterial(- contextWith({ job: { status: "Draft" }, ...parents }),- material- );+ const { ctx, writes } = save({ job: { status: "Draft" }, ...parents });+ const result = await updateJobMaterial(ctx, material);expect(result.error?.category).toBe("notFound");- expect(upsertJobMaterial).not.toHaveBeenCalled();+ expect(writes).toEqual([]);});});diff --git a/apps/erp/test/list-select-columns.test.ts b/apps/erp/test/list-select-columns.test.tsdeleted file mode 100644index 43446d81ea..0000000000--- a/apps/erp/test/list-select-columns.test.ts+++ /dev/null@@ -1,146 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { readFileSync } from "node:fs";-import { join } from "node:path";-import { describe, expect, it } from "vitest";--/**- * The view-backed list endpoints select an explicit column list rather than- * `*`, so Postgres can prune the views' unreferenced computed columns.- *- * TypeScript catches most under-selection, because the narrowed select narrows- * the row type. It does NOT catch the CSV export path: `Table/components/- * Download.tsx` reads `row[key]` for each column's `accessorKey`, untyped. A- * column dropped from the select but still declared as an `accessorKey` would- * export as blank with nothing failing.- *- * This test closes that gap: every accessorKey a list table declares must be a- * column its endpoint actually selects.- *- * Known limitation: it does NOT cover `meta.exportValue` / `exportOnlyColumn`- * functions, which read arbitrary row fields rather than a declared accessor- * (e.g. PartsTable's `itemName` reads `row.name`). Those are correct today- * because the column lists were derived by scanning whole table files, but a- * future exportValue reading a dropped column would slip past this. Verify a- * CSV export by hand when adding one.- */--const ROOT = join(__dirname, "..");--type Target = {- label: string;- constant: string;- service: string;- table: string;-};--const TARGETS: Target[] = [- {- label: "parts",- constant: "PARTS_LIST_COLUMNS",- service: "app/modules/items/items.service.ts",- table: "app/modules/items/ui/Parts/PartsTable.tsx"- },- {- label: "materials",- constant: "MATERIALS_LIST_COLUMNS",- service: "app/modules/items/items.service.ts",- table: "app/modules/items/ui/Materials/MaterialsTable.tsx"- },- {- label: "tools",- constant: "TOOLS_LIST_COLUMNS",- service: "app/modules/items/items.service.ts",- table: "app/modules/items/ui/Tools/ToolsTable.tsx"- },- {- label: "consumables",- constant: "CONSUMABLES_LIST_COLUMNS",- service: "app/modules/items/items.service.ts",- table: "app/modules/items/ui/Consumables/ConsumablesTable.tsx"- },- {- label: "services",- constant: "SERVICES_LIST_COLUMNS",- service: "app/modules/items/items.service.ts",- table: "app/modules/items/ui/Services/ServicesTable.tsx"- },- {- label: "purchaseOrders",- constant: "PURCHASE_ORDERS_LIST_COLUMNS",- service: "app/modules/purchasing/purchasing.service.ts",- table: "app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx"- },- {- label: "quotes",- constant: "QUOTES_LIST_COLUMNS",- service: "app/modules/sales/sales.service.ts",- table: "app/modules/sales/ui/Quotes/QuotesTable.tsx"- },- {- label: "salesOrders",- constant: "SALES_ORDERS_LIST_COLUMNS",- service: "app/modules/sales/sales.service.ts",- table: "app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx"- },- {- label: "purchaseInvoices",- constant: "PURCHASE_INVOICES_LIST_COLUMNS",- service: "app/modules/invoicing/invoicing.service.ts",- table: "app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx"- },- {- label: "salesInvoices",- constant: "SALES_INVOICES_LIST_COLUMNS",- service: "app/modules/invoicing/invoicing.service.ts",- table: "app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx"- }-];--function selectedColumns(service: string, constant: string): string[] {- const src = readFileSync(join(ROOT, service), "utf8");- const match = src.match(- new RegExp(`const ${constant} =\\s*\\n?\\s*"([^"]+)" as const;`)- );- if (!match) throw new Error(`${constant} not found in ${service}`);- return match[1].split(",");-}--function declaredAccessorKeys(table: string): string[] {- const src = readFileSync(join(ROOT, table), "utf8");- return [...src.matchAll(/accessorKey:\s*"([^"]+)"/g)]- .map((m) => m[1])- // custom-field columns are keyed `customFields->>{id}` at runtime; the- // `customFields` column itself is what has to be selected.- .filter((key) => !key.startsWith("customFields->>"));-}--describe("list endpoints select every column their table exports", () => {- it.each(TARGETS)(- "$label",- ({ constant, service, table }) => {- const selected = new Set(selectedColumns(service, constant));- const missing = declaredAccessorKeys(table).filter(- (key) => !selected.has(key)- );- expect(- missing,- `${constant} is missing accessorKey(s) used by ${table}. These render ` +- `blank in the CSV export, which nothing else catches.`- ).toEqual([]);- }- );-- it("selects customFields wherever the table renders custom columns", () => {- for (const { label, constant, service, table } of TARGETS) {- const src = readFileSync(join(ROOT, table), "utf8");- if (!src.includes("useCustomColumns")) continue;- expect(- selectedColumns(service, constant),- `${label} renders custom columns but ${constant} omits customFields`- ).toContain("customFields");- }- });-});diff --git a/apps/erp/test/localized-submodule-ui.test.ts b/apps/erp/test/localized-submodule-ui.test.tsdeleted file mode 100644index 0384b12612..0000000000--- a/apps/erp/test/localized-submodule-ui.test.ts+++ /dev/null@@ -1,104 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { describe, expect, test } from "vitest";-import { readFileSync } from "node:fs";-import { join } from "node:path";--const root = join(process.cwd(), "app");--const files = [- "modules/sales/ui/Customers/CustomersTable.tsx",- "modules/sales/ui/Quotes/QuotesTable.tsx",- "modules/sales/ui/SalesRFQ/SalesRFQsTable.tsx",- "modules/sales/ui/SalesOrder/SalesOrdersTable.tsx",- "modules/sales/ui/Customer/CustomerHeader.tsx",- "modules/sales/ui/Quotes/QuoteHeader.tsx",- "modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx",- "modules/sales/ui/SalesOrder/SalesOrderHeader.tsx",- "modules/sales/ui/SalesOrder/SalesOrderSummary.tsx",- "modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx",- "modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx",- "modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx"-];--const forbiddenPatterns: Array<{ pattern: RegExp; description: string }> = [- {- pattern: /header:\s*"[^"]+"/g,- description: "raw string table header"- },- {- pattern: /pluralHeader:\s*"[^"]+"/g,- description: "raw string plural header"- },- {- pattern: /title="[^"]+"/g,- description: "raw string title prop"- },- {- pattern: /<New\s+label="[^"]+"/g,- description: "raw string New label"- },- {- pattern: />\s*Edit\s*</g,- description: "raw Edit menu label"- },- {- pattern: />\s*Delete\s*</g,- description: "raw Delete menu label"- },- {- pattern: /text=\{`Are you sure you want to delete[\s\S]*?This cannot be undone\.`\}/g,- description: "raw delete confirmation text"- },- {- pattern:- /aria-label="(?:Toggle Explorer|More options|Toggle Properties)"/g,- description: "raw header aria label"- },- {- // Requires a non-whitespace character: once the `<Trans>` children are- // stripped above, a correctly localized label is left as an element- // containing only the newline and indentation it was written across, and- // `[^<{]+` alone would match that whitespace and report it as raw.- pattern: /<CardAttributeLabel>\s*[^<{\s][^<{]*<\/CardAttributeLabel>/g,- description: "raw card attribute label"- },- {- pattern:- />\s*(?:Delete Customer|Delete RFQ|Delete Quote|Delete Sales Order|Delete Purchase Invoice|Share|Preview|Finalize|Won|Lost|Cancel|Reopen|Ready for Quote|Quote|No Quote|Post|Payment|Purchase Order|Purchase Orders|Receipt|Receipts|Confirm|New Shipment|New Invoice|Shipments|Ship|Invoices|Invoice|Create Jobs|Edit Shipping|Add Shipping)\s*</g,- description: "raw header action label"- }-];--describe("localized sales and invoicing submodule UI", () => {- test("avoids raw UI strings in localized table and header screens", () => {- const offenders: string[] = [];-- for (const relativePath of files) {- const source = readFileSync(join(root, relativePath), "utf8");- const sanitizedSource = source- .replace(/\/\*[\s\S]*?\*\//g, "")- // Strip already-localized JSX before scanning. The `>Label<` patterns- // below cannot see element boundaries, and `<Trans>Edit</Trans>`- // literally contains `>Edit<` — so without this every correctly- // localized label reported itself as a raw one, and the suite could- // only be satisfied by UNDOING the localization it exists to enforce.- .replace(/<Trans[^>]*>[\s\S]*?<\/Trans>/g, "");-- for (const { pattern, description } of forbiddenPatterns) {- // `RegExp.test` on a /g regex advances `lastIndex` and the object is- // shared across every file in this loop, so a match in one file made- // the next file start mid-string and silently under-report. Reset per- // use rather than dropping the /g flag, which the descriptions rely on.- pattern.lastIndex = 0;- if (pattern.test(sanitizedSource)) {- offenders.push(`${relativePath}: ${description}`);- }- }- }-- expect(offenders).toEqual([]);- });-});diff --git a/apps/erp/test/mcp-manifest-cache-inputs.test.ts b/apps/erp/test/mcp-manifest-cache-inputs.test.tsindex 8c538b1b3e..2c4db7cd23 100644--- a/apps/erp/test/mcp-manifest-cache-inputs.test.ts+++ b/apps/erp/test/mcp-manifest-cache-inputs.test.ts@@ -4,7 +4,7 @@import { existsSync, readdirSync, readFileSync } from "node:fs";import { dirname, join, matchesGlob, relative, resolve } from "node:path";-import ts from "typescript";+import ts from "typescript5";import { describe, expect, it } from "vitest";// The tool manifest is CACHED by turbo (`//#generate:mcp` in the rootdiff --git a/apps/erp/test/people-operations.test.ts b/apps/erp/test/people-operations.test.tsindex d3a069a8c3..e304f335e0 100644--- a/apps/erp/test/people-operations.test.ts+++ b/apps/erp/test/people-operations.test.ts@@ -5,73 +5,38 @@import { createClient } from "@supabase/supabase-js";import { beforeEach, describe, expect, it, vi } from "vitest";-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn(), info: vi.fn(), warn: vi.fn() })-}));-vi.mock("../app/modules/production/production.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- notifyScheduleInputsChanged: vi.fn()-}));-vi.mock("../app/modules/people/people.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- clockIn: vi.fn(),- clockOut: vi.fn(),- createTimeCardEntry: vi.fn(),- deleteTimeCardEntry: vi.fn(),- updateEmployeeJob: vi.fn(),- updateTimeCardEntry: vi.fn()-}));+// The scheduler is told through an event.+const { trigger } = vi.hoisted(() => ({ trigger: vi.fn() }));+vi.mock("@carbon/jobs", () => ({ trigger }));-import { clockInPerson, updateShift } from "../app/modules/people/people.server";-import { clockIn } from "../app/modules/people/people.service";-import { notifyScheduleInputsChanged } from "../app/modules/production/production.service";+import { updateShift } from "../app/modules/people/people.server";+import { timeCardError } from "../app/modules/people/people.service";import { createServiceContext } from "@carbon/api/service-fn.server";const unreachable = () => {throw new Error("must not be reached");};-const ctx = createServiceContext({- actor: {- type: "user",- userId: "user-1",- permissions: {- people: { view: ["company-1"], create: [], update: [], delete: [] }- }- },- company: { id: "company-1", groupId: "group-1" },- caller: {} as never,- system: unreachable as never,- pg: unreachable as never,- kv: unreachable as never-});+const ctx = shiftContext({} as never, []);// The time card helpers refuse with a plain `{ message }`; the database// errors they pass through carry a code. One is the caller's to fix, the// other is ours.-describe("clockInPerson", () => {- it("returns the helper's refusal as a rule the caller can read", async () => {- vi.mocked(clockIn).mockResolvedValue({- data: null,- error: { message: "Already clocked in" }- } as never);- const result = await clockInPerson(ctx, { employeeId: "user-2" });- expect(result.error).toMatchObject({- category: "rule",- message: "Already clocked in"- });+describe("timeCardError", () => {+ it("returns a helper's refusal as a rule the caller can read", () => {+ expect(+ timeCardError(ctx, { message: "Already clocked in" }, "Failed to clock in")+ ).toMatchObject({ category: "rule", message: "Already clocked in" });});- it("hides a database error behind its own message", async () => {- vi.mocked(clockIn).mockResolvedValue({- data: null,- error: { message: "duplicate key value", code: "23505" }- } as never);- const result = await clockInPerson(ctx, { employeeId: "user-2" });- expect(result.error).toMatchObject({- category: "internal",- message: "Failed to clock in"- });+ it("hides a database error behind the operation's own message", () => {+ expect(+ timeCardError(+ ctx,+ { message: "duplicate key value", code: "23505" },+ "Failed to clock in"+ )+ ).toMatchObject({ category: "internal", message: "Failed to clock in" });});});@@ -132,7 +97,7 @@ const SHIFT = {};describe("updateShift", () => {- beforeEach(() => vi.mocked(notifyScheduleInputsChanged).mockClear());+ beforeEach(() => trigger.mockClear());// The shift UPDATE policy needs people update; create alone saved nothing.it("needs people update, not create", async () => {@@ -156,7 +121,7 @@ describe("updateShift", () => {expect(sent[0]?.method).toBe("PATCH");expect(sent[0]?.url.searchParams.get("id")).toBe("eq.shift-missing");expect(sent[0]?.url.searchParams.get("companyId")).toBe("eq.company-1");- expect(notifyScheduleInputsChanged).not.toHaveBeenCalled();+ expect(trigger).not.toHaveBeenCalled();});it("saves the shift and marks the schedule stale", async () => {@@ -166,6 +131,8 @@ describe("updateShift", () => {SHIFT);expect(result).toEqual({ data: { id: "shift-1" }, error: null });- expect(notifyScheduleInputsChanged).toHaveBeenCalledOnce();+ expect(trigger.mock.calls.map(([event]) => event)).toEqual([+ "schedule-inputs-changed"+ ]);});});diff --git a/apps/erp/test/planning-action-scope.test.ts b/apps/erp/test/planning-action-scope.test.tsindex eabb85241a..f0ca20bef4 100644--- a/apps/erp/test/planning-action-scope.test.ts+++ b/apps/erp/test/planning-action-scope.test.ts@@ -10,105 +10,57 @@ import {resolvePlanningActionScope} from "../app/modules/production/ui/Planning/planning-action-scope";+const partFilter = { column: "type", operator: "eq", value: "Part" };+describe("resolvePlanningActionScope", () => {- it("passes the grid's own filters through untouched and restricts nothing", () => {- const filters = [{ column: "type", operator: "eq", value: "Part" }];- expect(- resolvePlanningActionScope({ filters })- ).toEqual({- gridFilters: filters,+ it("passes the grid's own filters through and restricts nothing", () => {+ expect(resolvePlanningActionScope({ filters: [partFilter] })).toEqual({+ gridFilters: [partFilter],actionTypes: undefined,actionAssignees: undefined});});- it("strips the Actions-column filter and returns it as the RPC's type argument", () => {- const { gridFilters, actionTypes } = resolvePlanningActionScope({- filters: [- { column: "type", operator: "eq", value: "Part" },- { column: PLANNING_ACTIONS_COLUMN, operator: "eq", value: "Cancel" }- ],- });- expect(gridFilters).toEqual([- { column: "type", operator: "eq", value: "Part" }- ]);- expect(actionTypes).toEqual(["Cancel"]);- });-- it("accepts the multi-value `in` encoding, without duplicates", () => {- expect(- resolvePlanningActionScope({- filters: [- {- column: PLANNING_ACTIONS_COLUMN,- operator: "in",- value: "Cancel,Order"- },- { column: PLANNING_ACTIONS_COLUMN, operator: "eq", value: "Cancel" }- ],- }).actionTypes- ).toEqual(["Cancel", "Order"]);- });-- it("strips the Assignee filter and returns its people as the RPC's assignees argument", () => {+ it("strips the Actions and Assignee filters into the RPC's arguments", () => {expect(resolvePlanningActionScope({filters: [- { column: "type", operator: "eq", value: "Part" },+ partFilter,+ { column: PLANNING_ACTIONS_COLUMN, operator: "eq", value: "Cancel" },{ column: PLANNING_ASSIGNEE_COLUMN, operator: "eq", value: "user-a" }]})).toEqual({- gridFilters: [{ column: "type", operator: "eq", value: "Part" }],- actionTypes: undefined,+ gridFilters: [partFilter],+ actionTypes: ["Cancel"],actionAssignees: ["user-a"]});});- it("accepts several people in the `in` encoding, without duplicates", () => {- expect(- resolvePlanningActionScope({+ it.each([+ ["actionTypes", PLANNING_ACTIONS_COLUMN],+ ["actionAssignees", PLANNING_ASSIGNEE_COLUMN]+ ] as const)(+ "reads the `in` encoding into %s without duplicates",+ (key, column) => {+ const scope = resolvePlanningActionScope({filters: [- {- column: PLANNING_ASSIGNEE_COLUMN,- operator: "in",- value: "user-a,user-b"- },- { column: PLANNING_ASSIGNEE_COLUMN, operator: "eq", value: "user-a" }+ { column, operator: "in", value: "x,y" },+ { column, operator: "eq", value: "x" }]- }).actionAssignees- ).toEqual(["user-a", "user-b"]);- });+ });+ expect(scope[key]).toEqual(["x", "y"]);+ }+ );- it("returns assignees and types together — the RPC matches both on the same action", () => {- expect(- resolvePlanningActionScope({- filters: [- { column: PLANNING_ACTIONS_COLUMN, operator: "eq", value: "Cancel" },- { column: PLANNING_ASSIGNEE_COLUMN, operator: "eq", value: "user-a" }- ]- })- ).toEqual({- gridFilters: [],- actionTypes: ["Cancel"],- actionAssignees: ["user-a"]+ it.each([+ ["actionTypes", PLANNING_ACTIONS_COLUMN],+ ["actionAssignees", PLANNING_ASSIGNEE_COLUMN]+ ] as const)("an empty value restricts no %s", (key, column) => {+ const scope = resolvePlanningActionScope({+ filters: [{ column, operator: "eq", value: "" }]});- });-- it("an empty Assignee filter value restricts nothing", () => {- expect(- resolvePlanningActionScope({- filters: [{ column: PLANNING_ASSIGNEE_COLUMN, operator: "eq", value: "" }]- }).actionAssignees- ).toBeUndefined();- });-- it("an empty filter value restricts nothing", () => {- expect(- resolvePlanningActionScope({- filters: [{ column: PLANNING_ACTIONS_COLUMN, operator: "eq", value: "" }],- }).actionTypes- ).toBeUndefined();+ expect(scope[key]).toBeUndefined();});});@@ -120,26 +72,18 @@ describe("actionsOfTypes", () => {{ id: "d", type: "Cancel" }] as const;- it("shows every action when the grid is not filtered by type", () => {- expect(actionsOfTypes(actions, undefined)).toEqual([...actions]);- expect(actionsOfTypes(actions, null)).toEqual([...actions]);- expect(actionsOfTypes(actions, [])).toEqual([...actions]);- });-- it("keeps only the filtered type, in the original order", () => {- expect(actionsOfTypes(actions, ["Expedite"]).map((a) => a.id)).toEqual([- "a",- "c"- ]);- });-- it("keeps any of several filtered types", () => {- expect(- actionsOfTypes(actions, ["Cancel", "Defer"]).map((a) => a.id)- ).toEqual(["b", "d"]);- });+ it.each([undefined, null, []])(+ "shows every action when the type filter is %j",+ (types) => {+ expect(actionsOfTypes(actions, types)).toEqual([...actions]);+ }+ );- it("returns nothing when the row has no action of the filtered type", () => {- expect(actionsOfTypes(actions, ["Order"])).toEqual([]);+ it.each([+ [["Expedite"], ["a", "c"]],+ [["Cancel", "Defer"], ["b", "d"]],+ [["Order"], []]+ ])("keeps only actions of %j, in the original order", (types, ids) => {+ expect(actionsOfTypes(actions, types).map((a) => a.id)).toEqual(ids);});});diff --git a/apps/erp/test/planning-job-editable.test.ts b/apps/erp/test/planning-job-editable.test.tsdeleted file mode 100644index a8e719b005..0000000000--- a/apps/erp/test/planning-job-editable.test.ts+++ /dev/null@@ -1,45 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { describe, expect, it, vi } from "vitest";--// The models barrel reaches the glossary's lingui macros, which vitest does not-// transform (same stub as Schedule/Kanban/date-utils.test.ts).-vi.mock("@carbon/content/glossary", () => ({- terms: {},- getEntry: vi.fn(),- lookupEntry: vi.fn(),- hasEntry: vi.fn(),- termSlug: vi.fn(),- glossaryEntries: () => []-}));--import { isJobEditableFromPlanning } from "../app/modules/production/production.models";--// Planning's Apply used a blocklist (Ready / In Progress / Paused), so a job-// completed, closed or cancelled after MRP ran could still be edited or-// re-cancelled from a stale action. Only an unreleased job may change.-describe("isJobEditableFromPlanning", () => {- it("allows a job that is not released yet", () => {- expect(isJobEditableFromPlanning("Draft")).toBe(true);- expect(isJobEditableFromPlanning("Planned")).toBe(true);- });-- it("refuses a job on the floor", () => {- expect(isJobEditableFromPlanning("Ready")).toBe(false);- expect(isJobEditableFromPlanning("In Progress")).toBe(false);- expect(isJobEditableFromPlanning("Paused")).toBe(false);- });-- it("refuses a job that is finished, closed or cancelled", () => {- expect(isJobEditableFromPlanning("Completed")).toBe(false);- expect(isJobEditableFromPlanning("Closed")).toBe(false);- expect(isJobEditableFromPlanning("Cancelled")).toBe(false);- });-- it("refuses a job with no status", () => {- expect(isJobEditableFromPlanning(null)).toBe(false);- expect(isJobEditableFromPlanning(undefined)).toBe(false);- });-});diff --git a/apps/erp/test/posting-permissions.test.ts b/apps/erp/test/posting-permissions.test.tsindex 10a08f57f8..da24756c26 100644--- a/apps/erp/test/posting-permissions.test.ts+++ b/apps/erp/test/posting-permissions.test.ts@@ -2,45 +2,69 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { Constants } from "@carbon/database";import { describe, expect, it } from "vitest";-/**- * Every ported posting's declared permission, pinned: each `*Permission`- * export of a module service, and the permission each posting `@carbon/jobs`- * and `@carbon/ee` call checks a caller's client against. A change here is a- * change to who may run the posting: review the diff, then update the- * snapshot with `vitest -u`.- */-describe("posting permissions", () => {- const described = (rule: unknown) =>- typeof rule === "function" ? rule.toString() : rule;+// Permission claims are `<module>_<action>`, module lowercased.+const MODULES = new Set(+ Constants.public.Enums.module.map((module) => module.toLowerCase())+);++// These admit any member of the company. Widening who may run a posting is a+// review decision: add an entry only after one.+const OPEN_TO_ANY_MEMBER = [+ "inventory.issueMaterialPermission.jobCompleteMakeToOrder",+ "inventory.postPickingPermission",+ "inventory.postStockTransferPermission"+];- it("match the reviewed manifest", async () => {- const modules = import.meta.glob<Record<string, unknown>>(- "../app/modules/*/*.service.ts"+/** Each permission a rule can resolve to, named `<file>.<export>[.<value>]`. */+function leaves(name: string, rule: unknown): [string, unknown][] {+ if (rule && typeof rule === "object" && "by" in rule && "rules" in rule) {+ return Object.entries(rule.rules as Record<string, unknown>).map(+ ([value, leaf]) => [`${name}.${value}`, leaf]);- const manifest: Record<string, unknown> = {};- for (const [path, load] of Object.entries(modules).sort()) {- const file = path.split("/").pop()!.replace(/\.service\.ts$/, "");- for (const [name, rule] of Object.entries(await load())) {- if (name.endsWith("Permission")) {- manifest[`${file}.${name}`] = described(rule);- }- }+ }+ return [[name, rule]];+}++async function permissionExports() {+ const modules = import.meta.glob<Record<string, unknown>>(+ "../app/modules/*/*.service.ts"+ );+ const out: [string, unknown][] = [];+ for (const [path, load] of Object.entries(modules)) {+ const file = path.split("/").pop()?.replace(/\.service\.ts$/, "");+ for (const [name, rule] of Object.entries(await load())) {+ if (name.endsWith("Permission")) out.push(...leaves(`${file}.${name}`, rule));}- expect(Object.keys(manifest).length).toBeGreaterThan(0);- expect(manifest).toMatchSnapshot();+ }+ return out;+}- const { postingPermissions } = await import(- "../app/modules/postings.server"- );- expect(- Object.fromEntries(- Object.entries(postingPermissions).map(([name, rule]) => [- name,- described(rule)- ])+describe("posting permissions", () => {+ it("each requires a named module, is system-only, or is reviewed as open", async () => {+ const all = await permissionExports();+ const open = all+ .filter(+ ([, rule]) =>+ rule !== "system" &&+ Object.keys((rule ?? {}) as object).length === 0)- ).toMatchSnapshot();+ .map(([name]) => name)+ .sort();+ expect(open).toEqual(OPEN_TO_ANY_MEMBER);+ }, 120_000);++ it("names only modules that exist, so no claim can satisfy a typo", async () => {+ const unknown = (await permissionExports()).flatMap(([name, rule]) =>+ rule === "system"+ ? []+ : Object.values(rule as Record<string, string | string[]>)+ .flat()+ .filter((module) => !MODULES.has(module))+ .map((module) => `${name}: ${module}`)+ );+ expect(unknown).toEqual([]);}, 120_000);});diff --git a/apps/erp/test/production-planning.test.ts b/apps/erp/test/production-planning.test.tsindex d115fe264b..2dcf389386 100644--- a/apps/erp/test/production-planning.test.ts+++ b/apps/erp/test/production-planning.test.ts@@ -2,47 +2,18 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it } from "vitest";// Production planning's writes: planning edits only this location's Draft or// Planned jobs, a released job's suggestion goes to review, and a write that// changed nothing says so.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("@carbon/env", async (importOriginal) => ({- ...(await importOriginal<typeof import("@carbon/env")>()),- ASSEMBLER_SERVICE_URL: ""-}));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn(), warn: vi.fn() })-}));-vi.mock("@carbon/jobs", () => ({ trigger: vi.fn(), batchTrigger: vi.fn() }));-vi.mock("@carbon/planning", () => ({ runLocationSchedule: vi.fn() }));-vi.mock("../app/modules/production/production.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- dismissPlanningActions: vi.fn(),- getPlanningActionsByIds: vi.fn(),- markPlanningActionsActioned: vi.fn(),- notifyScheduleInputsChanged: vi.fn(),- recalculateJobRequirements: vi.fn(async () => ({ data: null, error: null })),- updatePlanningJob: vi.fn(async () => ({ updated: true, error: null }))-}));--import {- dismissPlanningActions,- getPlanningActionsByIds,- markPlanningActionsActioned,- recalculateJobRequirements,- updatePlanningJob-} from "../app/modules/production/production.service";import {applyPlanningActions,- dismissProductionPlanningActions,planJobFromPlanning,updatePlannedJob} from "../app/modules/production/production.server";+import { changedPlanningActions } from "../app/modules/production/production.service";import { createServiceContext } from "@carbon/api/service-fn.server";type Job = {@@ -53,30 +24,56 @@ type Job = {salesOrderLineId?: string | null;};-/** The service role: the planning job read. */-function systemWithJob(job: Job | null) {- const chain: Record<string, unknown> = {};- for (const method of ["select", "eq"]) chain[method] = () => chain;- chain.maybeSingle = async () => ({ data: job, error: null });- return { from: () => chain };+/** Supabase: each table's one row, whatever the filter; updates are recorded. */+function supabaseWith(rows: Record<string, unknown>, writes: string[]) {+ return {+ from: (table: string) => {+ const chain: Record<string, unknown> = {};+ for (const method of ["select", "eq", "in"]) chain[method] = () => chain;+ chain.update = () => {+ writes.push(`update ${table}`);+ return chain;+ };+ const row = () => ({ data: rows[table] ?? null, error: null });+ chain.maybeSingle = async () => row();+ chain.single = async () => row();+ chain.then = (resolve: (value: unknown) => unknown) =>+ resolve({ data: rows[table] ? [rows[table]] : [], error: null });+ return chain;+ }+ };}-/** Kysely: the jobs the actions target, as `{ id, status }` rows. */-function pgWithJobs(jobs: { id: string; status: string }[]) {- const query: Record<string, unknown> = {};- for (const method of ["select", "where"]) query[method] = () => query;- query.execute = async () => jobs;- return { selectFrom: () => query };+/** Kysely: each table's rows, whatever the filter; updates are recorded. */+function kyselyWith(rows: Record<string, unknown[]>, writes: string[]) {+ const query = (result: () => unknown[]) => {+ const chain: Record<string, unknown> = {};+ for (const method of ["select", "selectAll", "where", "set", "returning"]) {+ chain[method] = () => chain;+ }+ chain.execute = async () => result();+ return chain;+ };+ return {+ selectFrom: (table: string) => query(() => rows[table] ?? []),+ updateTable: (table: string) => {+ writes.push(`update ${table}`);+ return query(() => []);+ }+ };}-const contextWith = ({+function planning({job = null,+ planningAction = [],jobs = []}: {job?: Job | null;+ planningAction?: Record<string, unknown>[];jobs?: { id: string; status: string }[];-}) =>- createServiceContext({+}) {+ const writes: string[] = [];+ const ctx = createServiceContext({actor: {type: "user",userId: "u1",@@ -86,10 +83,12 @@ const contextWith = ({},company: { id: "c1", groupId: "g1" },caller: {} as never,- system: () => systemWithJob(job) as never,- pg: () => pgWithJobs(jobs) as never,+ system: () => supabaseWith({ job }, writes) as never,+ pg: () => kyselyWith({ planningAction, job: jobs }, writes) as never,kv: () => ({}) as never});+ return { ctx, writes };+}const draft = (overrides: Partial<Job> = {}): Job => ({id: "j1",@@ -98,53 +97,51 @@ const draft = (overrides: Partial<Job> = {}): Job => ({...overrides});-beforeEach(() => vi.clearAllMocks());-describe("updatePlannedJob", () => {- const edit = (job: Job | null) =>- updatePlannedJob(contextWith({ job }), {+ const edit = (job: Job) => {+ const { ctx, writes } = planning({ job });+ const result = updatePlannedJob(ctx, {locationId: "loc1",job: { id: "j1", field: "quantity", value: 5 }});-- it("refuses another location's job and a released one, before writing", async () => {- expect((await edit(draft({ locationId: "loc2" }))).error?.category).toBe(- "conflict"- );- expect((await edit(draft({ status: "Ready" }))).error?.category).toBe(- "conflict"- );- expect(updatePlanningJob).not.toHaveBeenCalled();+ return { result, writes };+ };++ it.each([+ ["another location's job", draft({ locationId: "loc2" })],+ ["a released job", draft({ status: "Ready" })]+ ])("refuses %s before writing", async (_case, job) => {+ const { result, writes } = edit(job);+ expect((await result).error?.category).toBe("conflict");+ expect(writes).toEqual([]);});+ // The recalculation runs against the database, which this test has none of.it("keeps a saved quantity when the recalculation fails, and says so", async () => {- vi.mocked(recalculateJobRequirements).mockResolvedValueOnce({- data: null,- error: new Error("recalc failed")- } as never);- const result = await edit(draft());- expect(result.error).toBeNull();- expect(result.data?.warning).toBeTruthy();+ const { result, writes } = edit(draft());+ expect(await result).toEqual({+ data: { id: "j1", warning: expect.any(String) },+ error: null+ });+ expect(writes).toEqual(["update job"]);});});describe("planJobFromPlanning", () => {- it("refuses a job a sales order owns", async () => {- const result = await planJobFromPlanning(- contextWith({ job: draft({ salesOrderLineId: "sol1" }) }),- { locationId: "loc1", jobId: "j1" }- );- expect(result.error).toMatchObject({- category: "conflict",- message: "This job is for a sales order. Plan it on the job."+ it("refuses a Draft job a sales order owns", async () => {+ const { ctx } = planning({ job: draft({ salesOrderLineId: "sol1" }) });+ const result = await planJobFromPlanning(ctx, {+ locationId: "loc1",+ jobId: "j1"});+ expect(result.error?.category).toBe("conflict");});});describe("applyPlanningActions", () => {it("sends a released job's suggestion to review without claiming it", async () => {- vi.mocked(getPlanningActionsByIds).mockResolvedValueOnce({- data: [+ const { ctx, writes } = planning({+ planningAction: [{id: "pa1",status: "Open",@@ -153,56 +150,49 @@ describe("applyPlanningActions", () => {suggestedQuantity: 10}],- error: null- } as never);- const result = await applyPlanningActions(- contextWith({ jobs: [{ id: "j1", status: "In Progress" }] }),- { planningActionIds: ["pa1", "pa1"] }- );+ jobs: [{ id: "j1", status: "In Progress" }]+ });+ const result = await applyPlanningActions(ctx, {+ planningActionIds: ["pa1", "pa1"]+ });expect(result.data).toEqual({applied: [],requiresManualAction: [{ id: "pa1", jobId: "j1" }],warnings: [],errors: []});- expect(markPlanningActionsActioned).not.toHaveBeenCalled();+ expect(writes).toEqual([]);});- it("keeps only the requested type", async () => {- vi.mocked(getPlanningActionsByIds).mockResolvedValueOnce({- data: [{ id: "pa1", status: "Open", type: "Defer", jobId: "j1" }],- error: null- } as never);- const result = await applyPlanningActions(contextWith({ jobs: [] }), {+ it("refuses an action of another type than the one requested", async () => {+ const { ctx } = planning({+ planningAction: [{ id: "pa1", status: "Open", type: "Defer", jobId: "j1" }]+ });+ const result = await applyPlanningActions(ctx, {planningActionIds: ["pa1"],type: "Cancel"});- expect(result.data?.errors).toEqual([- "Planning action pa1 is a Defer, not Cancel"- ]);+ expect(result.data).toEqual({+ applied: [],+ requiresManualAction: [],+ warnings: [],+ errors: ["Planning action pa1 is a Defer, not Cancel"]+ });});});-describe("dismissProductionPlanningActions", () => {- it("is a conflict when every action changed since the page loaded", async () => {- vi.mocked(dismissPlanningActions).mockResolvedValueOnce({- data: [],- error: null- } as never);- const result = await dismissProductionPlanningActions(contextWith({}), {- planningActionIds: ["pa1"]- });- expect(result.error?.category).toBe("conflict");+describe("changedPlanningActions", () => {+ const { ctx } = planning({});++ it("is a conflict when every action changed since the page loaded", () => {+ expect(+ changedPlanningActions(ctx, { data: [], error: null }, 1, "dismiss")+ ).toMatchObject({ category: "conflict" });});- it("counts what changed", async () => {- vi.mocked(dismissPlanningActions).mockResolvedValueOnce({- data: [{ id: "pa1" }],- error: null- } as never);- const result = await dismissProductionPlanningActions(contextWith({}), {- planningActionIds: ["pa1", "pa2"]- });- expect(result.data).toEqual({ changed: 1, requested: 2 });+ it("counts what changed of what was requested", () => {+ expect(+ changedPlanningActions(ctx, { data: [{ id: "pa1" }], error: null }, 2, "dismiss")+ ).toEqual({ changed: 1, requested: 2 });});});diff --git a/apps/erp/test/quality-operations.test.ts b/apps/erp/test/quality-operations.test.tsindex d5bb2ed542..86261f0c51 100644--- a/apps/erp/test/quality-operations.test.ts+++ b/apps/erp/test/quality-operations.test.ts@@ -2,79 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { beforeEach, describe, expect, it, vi } from "vitest";--// The service's imports reach the glossary, whose `msg` macro only runs compiled.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn(), warn: vi.fn(), info: vi.fn() })-}));--const { disposition, invoke, postNonconformance } = vi.hoisted(() => ({- // The inspection engine's lot disposition.- disposition: vi.fn(),- // The server functions (`create`).- invoke: vi.fn(),- // The inventory write-off's posting.- postNonconformance: vi.fn()-}));-vi.mock("@carbon/database/quality", async (importOriginal) => ({- ...(await importOriginal<typeof import("@carbon/database/quality")>()),- dispositionInspection: disposition-}));-vi.mock("../app/modules/quality/quality.service", async (importOriginal) => ({- ...(await importOriginal<- typeof import("../app/modules/quality/quality.service")- >()),- postNonconformance-}));-vi.mock("../app/modules/shared/shared.service", async (importOriginal) => {- const actual =- await importOriginal<- typeof import("../app/modules/shared/shared.service")- >();- // The postings the server functions package ran are the boundary; every- // other posting runs its (mocked) body as before.- const stubbed = new Set([- "issue",- "create",- "batch-operations",- "post-inventory-adjustment",- "post-maintenance-event",- "post-picking",- "post-production-event",- "recalculate",- "reschedule",- "trigger-rework"- ]);- return {- ...actual,- invokePosting: ((from: never, name: string, input: never, ...rest: never[]) =>- stubbed.has(name)- ? invoke(name, input)- : (actual.invokePosting as (...args: unknown[]) => unknown)(- from,- name,- input,- ...rest- )) as typeof actual.invokePosting,- invokeCreate: (_from: unknown, input: unknown) => invoke("create", input)- };-});-+import { describe, expect, it } from "vitest";import { createServiceContext } from "@carbon/api/service-fn.server";--const {+import {createIssue,- rejectInspection,saveInspectionDocument,setIssueStatus,updateIssueField,updateIssueItemField,updateQualityDocumentField-} = await import("../app/modules/quality/quality.server");+} from "../app/modules/quality/quality.server";const quality = {quality: {@@ -127,96 +64,6 @@ function contextWith(rows: Record<string, unknown> = {}) {return { ctx, writes: db.writes };}-beforeEach(() => {- vi.clearAllMocks();- invoke.mockResolvedValue({ data: { journalId: null }, error: null });- postNonconformance.mockResolvedValue({ journalId: null });-});--describe("rejecting an inspection lot", () => {- const writeOff = { itemId: "part-2", quantity: -5, locationId: "loc-1" };-- it("posts the lot's write-off, and with no issue asked for, stops there", async () => {- disposition.mockResolvedValue({- data: { id: "insp-1", status: "Failed", writeOff },- error: null- });- const { ctx } = contextWith();-- const result = await rejectInspection(ctx, {- id: "insp-1",- createNcr: false- });-- expect(result).toEqual({- data: { id: "insp-1", issueId: null },- error: null- });- // Only Receipt lots: a Job Operation lot is rejected from the shop floor.- expect(disposition.mock.calls[0]![1]).toMatchObject({- decision: "Reject",- requireSource: "Receipt"- });- expect(postNonconformance).toHaveBeenCalledWith(expect.anything(), {- documentType: "Inbound Inspection",- documentId: "insp-1",- description: "Inbound inspection lot rejected",- movements: [{ ...writeOff, trackedEntityId: null }]- });- });-- it("posts nothing for a lot with no write-off (tracked, or not inventory)", async () => {- disposition.mockResolvedValue({- data: { id: "insp-1", status: "Failed", writeOff: null },- error: null- });- const { ctx } = contextWith();-- const result = await rejectInspection(ctx, {- id: "insp-1",- createNcr: false- });-- expect(result.error).toBeNull();- expect(postNonconformance).not.toHaveBeenCalled();- });-- // Closing the issue restores value on Use As Is on the assumption the- // reject wrote it off, so an issue opened after a failed write-off would- // count the lot twice.- it("opens no issue when the write-off fails to post", async () => {- disposition.mockResolvedValue({- data: { id: "insp-1", status: "Failed", writeOff },- error: null- });- postNonconformance.mockRejectedValue(new Error("no account"));- const { ctx, writes } = contextWith();-- const result = await rejectInspection(ctx, { id: "insp-1" });-- expect(result.error?.message).toMatch(- /^Lot rejected, but the inventory write-off failed to post/- );- expect(writes).toEqual([]);- });-- it("is refused when the engine refuses the lot", async () => {- disposition.mockResolvedValue({- data: null,- error: { message: "Only receipt lots" }- });- const { ctx } = contextWith();-- const result = await rejectInspection(ctx, { id: "insp-1" });-- expect(result.error).toMatchObject({- category: "rule",- message: "Failed to reject lot"- });- expect(postNonconformance).not.toHaveBeenCalled();- });-});-describe("opening an issue", () => {const issue = {name: "Cracked housing",@@ -262,18 +109,12 @@ describe("issue status", () => {status: "Registered"});- expect(result.error).toMatchObject({- category: "rule",- message:- "This NCR posted inventory transactions and can't be reopened. Create a correcting entry instead."- });+ expect(result.error?.category).toBe("rule");expect(writes).toEqual([]);});});describe("a closed issue is locked", () => {- const locked = "Cannot modify a closed issue. Reopen it first.";-it("refuses a field change when any of the issues is closed", async () => {const { ctx, writes } = contextWith({nonConformance: [@@ -288,7 +129,7 @@ describe("a closed issue is locked", () => {value: "High"});- expect(result.error).toMatchObject({ category: "rule", message: locked });+ expect(result.error?.category).toBe("rule");expect(writes).toEqual([]);});@@ -303,7 +144,7 @@ describe("a closed issue is locked", () => {value: "Scrap"});- expect(result.error).toMatchObject({ category: "rule", message: locked });+ expect(result.error?.category).toBe("rule");expect(writes).toEqual([]);});@@ -316,22 +157,20 @@ describe("a closed issue is locked", () => {value: "Scrap"});- expect(result.error).toMatchObject({- category: "notFound",- message: "Issue item not found"- });+ expect(result.error?.category).toBe("notFound");expect(writes).toEqual([]);});it("refuses a negative quantity", async () => {- const { ctx } = contextWith();+ const { ctx, writes } = contextWith();const result = await updateIssueItemField(ctx, {id: "nci-1",field: "quantity",value: -3,expectedQuantity: 0});- expect(result.error?.message).toContain("Quantity must be zero or more");+ expect(result.error?.category).toBe("validation");+ expect(writes).toEqual([]);});});@@ -343,10 +182,7 @@ describe("quality document fields", () => {field: "status",value: "Published"});- expect(result.error).toMatchObject({- category: "validation",- message: "Invalid status"- });+ expect(result.error?.category).toBe("validation");expect(writes).toEqual([]);});@@ -380,10 +216,7 @@ describe("saving an inspection plan", () => {delete: []}});- expect(result.error).toMatchObject({- category: "validation",- message: "Legacy balloons payload requires anchors"- });+ expect(result.error?.category).toBe("validation");expect(writes).toEqual([]);});});diff --git a/apps/erp/test/release-jobs.test.ts b/apps/erp/test/release-jobs.test.tsindex 838c07dfe9..c77849dcf2 100644--- a/apps/erp/test/release-jobs.test.ts+++ b/apps/erp/test/release-jobs.test.ts@@ -4,21 +4,11 @@import { beforeEach, describe, expect, it, vi } from "vitest";-// The service's imports now reach the glossary, whose `msg` macro only runs compiled.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("@carbon/env", async (importOriginal) => ({- ...(await importOriginal<typeof import("@carbon/env")>()),- ASSEMBLER_SERVICE_URL: ""-}));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn() })-}));+// Releasing jobs and batches: what is released, skipped or refused, and the+// order of the steps, which `events` records as they reach the outside world.+const { invoke, events } = vi.hoisted(() => ({- // The `create` server function: purchase orders for outside operations.invoke: vi.fn(),- // What reached the outside world, in order.events: [] as string[]}));vi.mock("../app/modules/shared/shared.service", async (importOriginal) => {@@ -26,20 +16,9 @@ vi.mock("../app/modules/shared/shared.service", async (importOriginal) => {await importOriginal<typeof import("../app/modules/shared/shared.service")>();- // The postings the server functions package ran are the boundary; every- // other posting runs its (mocked) body as before.- const stubbed = new Set([- "issue",- "create",- "batch-operations",- "post-inventory-adjustment",- "post-maintenance-event",- "post-picking",- "post-production-event",- "recalculate",- "reschedule",- "trigger-rework"- ]);+ // Postings are database work with their own database tests; here they+ // answer `invoke`.+ const stubbed = new Set(["create", "batch-operations", "recalculate"]);return {...actual,invokePosting: ((from: never, name: string, input: never, ...rest: never[]) =>@@ -55,35 +34,26 @@ vi.mock("../app/modules/shared/shared.service", async (importOriginal) => {};});vi.mock("@carbon/planning", () => ({- runLocationSchedule: vi.fn(async () => {- events.push("schedule");+ runMrp: vi.fn(),+ runLocationSchedule: vi.fn()+}));+vi.mock("@carbon/jobs", () => ({+ trigger: vi.fn(async (event: string) => {+ if (event === "schedule-inputs-changed") events.push("notify");})}));+vi.mock("@carbon/lib/workflows", () => ({ raiseMoment: vi.fn() }));+vi.mock("@carbon/lib/telemetry", () => ({ trackWorkEvent: vi.fn() }));+// The readiness read has its own test (job-release-readiness).vi.mock("../app/modules/production/production.service", async (importOriginal) => ({...(await importOriginal<object>()),- getJobReleaseReadiness: vi.fn(),- recalculateJobRequirements: vi.fn(async () => ({ data: null, error: null })),- runMRP: vi.fn(async () => ({ data: null, error: null })),- updateJobStatus: vi.fn(async (_client, { id }) => {- events.push(`ready:${id}`);- return { error: null, updated: true };- }),- releaseJobOperationBatch: vi.fn(async (_client, _db, { batchId }) => {- events.push(`batch:${batchId}`);- return { data: null, error: null };- }),- notifyScheduleInputsChanged: vi.fn(async () => {- events.push("notify");- })+ getJobReleaseReadiness: vi.fn()}));-import { runLocationSchedule } from "@carbon/planning";-import {- getJobReleaseReadiness,- recalculateJobRequirements,- runMRP,- updateJobStatus-} from "../app/modules/production/production.service";+import { runLocationSchedule, runMrp } from "@carbon/planning";+// Before the server module: loaded first, the service gets the stubbed+// postings (shared.service imports it back, and a cycle sees the original).+import { getJobReleaseReadiness } from "../app/modules/production/production.service";import {planDraftJob,releaseBatches,@@ -92,6 +62,61 @@ import {} from "../app/modules/production/production.server";import { createServiceContext } from "@carbon/api/service-fn.server";+type Row = Record<string, unknown>;++/**+ * A Supabase client over in-memory tables. `eq` and `in` filter on the+ * columns a row has; an update changes the rows still matching, and each+ * status change is logged to `events`. `inFilterSizes` records how many job+ * ids each read sent.+ */+function database(+ tables: Record<string, Row[]>,+ { releasedDateError = null as { message: string } | null } = {}+) {+ const inFilterSizes: number[] = [];+ const from = (table: string) => {+ let rows = tables[table] ?? [];+ let values: Row | null = null;+ const write = () => {+ if (values?.releasedDate) return { data: null, error: releasedDateError };+ for (const row of rows) {+ Object.assign(row, values);+ if (values?.status) {+ events.push(`${String(values.status).toLowerCase()}:${row.id}`);+ }+ }+ return { data: rows.map((row) => ({ id: row.id })), error: null };+ };+ const filter = (column: string, accepts: (value: unknown) => boolean) => {+ rows = rows.filter((row) => !(column in row) || accepts(row[column]));+ return chain;+ };+ const chain: Record<string, any> = {+ select: () => (values ? Promise.resolve(write()) : chain),+ update: (next: Row) => {+ values = next;+ return chain;+ },+ eq: (column: string, value: unknown) =>+ filter(column, (cell) => cell === value),+ in: (column: string, list: unknown[]) => {+ if (table === "job" && column === "id") inFilterSizes.push(list.length);+ return filter(column, (cell) => list.includes(cell));+ },+ order: () => chain,+ is: () => chain,+ maybeSingle: async () => ({ data: rows[0] ?? null, error: null }),+ then: (resolve: (value: unknown) => unknown) =>+ Promise.resolve(values ? write() : { data: rows, error: null }).then(+ resolve+ )+ };+ return chain;+ };+ return { client: { from } as any, inFilterSizes };+}+const contextFor = (client: any) =>createServiceContext({actor: {@@ -103,85 +128,81 @@ const contextFor = (client: any) =>},company: { id: "company-1", groupId: "group-1" },caller: client,- system: () => ({}) as any,+ system: () => client,pg: () => ({}) as any,kv: () => ({}) as any});-// The release-date write: a chainable, thenable stand-in for the user client.-function clientWith(stamp: { error: null | { message: string } }) {- const chain: Record<string, any> = {};- for (const method of ["update", "eq"]) chain[method] = () => chain;- chain.then = (resolve: (value: unknown) => unknown) =>- Promise.resolve({ data: null, ...stamp }).then(resolve);- return { from: () => chain } as any;+/** The postings, by name: the defaults succeed; `overrides` replaces one. */+function postings(+ overrides: Partial<Record<string, (input: any) => Promise<unknown>>> = {}+) {+ return async (name: string, input: any) => {+ if (overrides[name]) return overrides[name](input);+ if (name === "recalculate") events.push("recalculate");+ if (name === "batch-operations") events.push(`batch:${input.batchId}`);+ return name === "create"+ ? { data: { purchaseOrderIdsBySupplierId: {} }, error: null }+ : { data: {}, error: null };+ };}-const release = (client: any, jobIds = ["job-1"]) =>- releaseCheckedJobs(contextFor(client), {- jobIds,- purchaseOrdersBySupplierId: {}- });-beforeEach(() => {vi.clearAllMocks();events.length = 0;- invoke.mockResolvedValue({- data: { purchaseOrderIdsBySupplierId: {} },- error: null+ invoke.mockImplementation(postings());+ vi.mocked(runMrp).mockImplementation(async () => {+ events.push("mrp");+ return null as never;});- vi.mocked(updateJobStatus).mockImplementation(async (_client, { id }) => {- events.push(`ready:${id}`);- return { error: null, updated: true } as any;+ vi.mocked(runLocationSchedule).mockImplementation(async () => {+ events.push("schedule");+ return undefined as never;});});describe("releaseCheckedJobs", () => {- it("releases past a failed MRP run", async () => {- vi.mocked(runMRP).mockResolvedValueOnce({- data: null,- error: new Error("planning blew up")+ const release = (jobs: Row[], options = {}) =>+ releaseCheckedJobs(contextFor(database({ job: jobs }, options).client), {+ jobIds: jobs.map((job) => job.id as string),+ purchaseOrdersBySupplierId: {}});- const result = await release(clientWith({ error: null }));++ it("recalculates, runs MRP, then flips the job to Ready", async () => {+ const result = await release([{ id: "job-1", status: "Planned" }]);expect(result.data).toEqual({failure: null,purchaseOrdersBySupplierId: {},releasedJobIds: ["job-1"]});+ expect(events).toEqual(["recalculate", "mrp", "ready:job-1"]);+ });++ it("releases past a failed MRP run", async () => {+ vi.mocked(runMrp).mockRejectedValueOnce(new Error("planning blew up"));+ const result = await release([{ id: "job-1", status: "Planned" }]);+ expect(result.data?.releasedJobIds).toEqual(["job-1"]);});it("flips only a job still Draft or Planned, and stops when it is not", async () => {- vi.mocked(updateJobStatus).mockResolvedValueOnce({- error: null,- updated: false- } as any);- const result = await release(clientWith({ error: null }), [- "job-1",- "job-2"- ]);- expect(vi.mocked(updateJobStatus).mock.calls[0]?.[1]).toMatchObject({- status: "Ready",- fromStatuses: ["Draft", "Planned"]- });+ const jobs = [+ { id: "job-1", status: "Cancelled" },+ { id: "job-2", status: "Planned" }+ ];+ const result = await release(jobs);expect(result.data).toMatchObject({- failure: {- category: "conflict",- message: "The job is no longer Draft or Planned"- },- purchaseOrdersBySupplierId: {},+ failure: { category: "conflict" },releasedJobIds: []});+ expect(jobs.map((job) => job.status)).toEqual(["Cancelled", "Planned"]);});it("reports a failed release-date write on a job that is released", async () => {- const result = await release(- clientWith({ error: { message: "connection reset" } })- );+ const result = await release([{ id: "job-1", status: "Planned" }], {+ releasedDateError: { message: "connection reset" }+ });expect(result.data).toMatchObject({- failure: {- message: "The job is released, but its release date could not be saved"- },- purchaseOrdersBySupplierId: {},+ failure: { category: "internal" },releasedJobIds: ["job-1"]});});@@ -190,86 +211,60 @@ describe("releaseCheckedJobs", () => {// The planning drawer's Plan on a Draft job follows releaseJobs' order: MRP// must never count a job as supply while its requirements are stale.describe("planDraftJob", () => {- // The user client: the job's status, read before anything runs.- const jobWithStatus = (status: string) => {- const chain: Record<string, any> = {};- for (const method of ["select", "eq"]) chain[method] = () => chain;- chain.maybeSingle = async () => ({ data: { status }, error: null });- return { from: () => chain } as any;- };- const plan = (status = "Draft") =>- planDraftJob(contextFor(jobWithStatus(status)), { jobId: "job-1" });+ const plan = (job: Row) =>+ planDraftJob(contextFor(database({ job: [job] }).client), {+ jobId: "job-1"+ });it("refuses a job that is not Draft before recalculating it", async () => {- expect((await plan("Planned")).error?.category).toBe("conflict");- expect(recalculateJobRequirements).not.toHaveBeenCalled();+ const result = await plan({ id: "job-1", status: "Planned" });+ expect(result.error?.category).toBe("conflict");+ expect(events).toEqual([]);});- it("recalculates, flips only from Draft, then runs MRP", async () => {- const order: string[] = [];- vi.mocked(recalculateJobRequirements).mockImplementationOnce(async () => {- order.push("recalculate");- return { data: null, error: null } as any;- });- vi.mocked(updateJobStatus).mockImplementationOnce(async () => {- order.push("flip");- return { error: null, updated: true } as any;- });- vi.mocked(runMRP).mockImplementationOnce(async () => {- order.push("mrp");- return { data: null, error: null } as any;- });-- expect(await plan()).toEqual({ data: { warning: null }, error: null });- expect(order).toEqual(["recalculate", "flip", "mrp"]);- expect(vi.mocked(updateJobStatus).mock.calls[0]?.[1]).toMatchObject({- status: "Planned",- fromStatuses: ["Draft"]- });+ it("recalculates, flips Draft to Planned, then runs MRP", async () => {+ const result = await plan({ id: "job-1", status: "Draft" });+ expect(result).toEqual({ data: { warning: null }, error: null });+ expect(events).toEqual(["recalculate", "planned:job-1", "mrp"]);});it("leaves the job Draft, and runs no MRP, when the recalculation fails", async () => {- vi.mocked(recalculateJobRequirements).mockResolvedValueOnce({- data: null,- error: { message: "boom" }- } as any);-- const result = await plan();+ invoke.mockImplementation(+ postings({+ recalculate: async () => ({ data: null, error: { message: "boom" } })+ })+ );+ const job = { id: "job-1", status: "Draft" };+ const result = await plan(job);expect(result.error?.category).toBe("internal");- expect(updateJobStatus).not.toHaveBeenCalled();- expect(runMRP).not.toHaveBeenCalled();+ expect(job.status).toBe("Draft");+ expect(events).toEqual([]);});- it("runs no MRP when the job is no longer Draft", async () => {- vi.mocked(updateJobStatus).mockResolvedValueOnce({- error: null,- updated: false- } as any);-- expect((await plan()).error?.category).toBe("conflict");- expect(runMRP).not.toHaveBeenCalled();+ it("runs no MRP when the job left Draft during the recalculation", async () => {+ const job = { id: "job-1", status: "Draft" };+ invoke.mockImplementation(+ postings({+ recalculate: async () => {+ job.status = "Ready";+ return { data: {}, error: null };+ }+ })+ );+ expect((await plan(job)).error?.category).toBe("conflict");+ expect(events).toEqual([]);});it("keeps the job Planned and warns when MRP fails", async () => {- vi.mocked(runMRP).mockResolvedValueOnce({- data: null,- error: new Error("planning blew up")- });-- const result = await plan();- expect(result.error).toBeNull();- expect(result.data?.warning).toBeTruthy();+ vi.mocked(runMrp).mockRejectedValueOnce(new Error("planning blew up"));+ const job = { id: "job-1", status: "Draft" };+ const result = await plan(job);+ expect(result.data?.warning).toEqual(expect.any(String));+ expect(job.status).toBe("Planned");});});-type JobRow = {- id: string;- jobId: string;- status: string;- locationId: string;-};--const job = (id: string, overrides: Partial<JobRow> = {}): JobRow => ({+const job = (id: string, overrides: Row = {}): Row => ({id,jobId: id.toUpperCase(),status: "Planned",@@ -291,30 +286,6 @@ const ready = (id: string, overrides: Record<string, unknown> = {}) => ({...overrides});-// The user client: reads of the selected jobs (the `in` filter applied) and-// the release-date write. `inFilterSizes` records how many ids each read sent.-function clientFor(jobs: JobRow[]) {- const inFilterSizes: number[] = [];- const from = () => {- let rows: unknown = jobs;- const chain: Record<string, any> = {};- for (const method of ["select", "eq", "order"]) chain[method] = () => chain;- chain.update = () => {- rows = null;- return chain;- };- chain.in = (_column: string, ids: string[]) => {- inFilterSizes.push(ids.length);- rows = (rows as JobRow[]).filter((row) => ids.includes(row.id));- return chain;- };- chain.then = (resolve: (value: unknown) => unknown) =>- Promise.resolve({ data: rows, error: null }).then(resolve);- return chain;- };- return { client: { from } as any, inFilterSizes };-}-function readiness(jobs: ReturnType<typeof ready>[],suppliers: {@@ -330,9 +301,13 @@ function readiness(describe("releaseJobs", () => {const run = (- jobs: JobRow[],- input: { jobIds: string[]; purchaseOrdersBySupplierId?: Record<string, string> }- ) => releaseJobs(contextFor(clientFor(jobs).client), input);+ jobs: Row[],+ input: {+ jobIds: string[];+ purchaseOrdersBySupplierId?: Record<string, string>;+ supplierProcessByOperationId?: Record<string, string>;+ }+ ) => releaseJobs(contextFor(database({ job: jobs }).client), input);it("releases Draft and Planned jobs, and lists the rest as skipped", async () => {readiness([ready("j1"), ready("j2")]);@@ -355,32 +330,17 @@ describe("releaseJobs", () => {it("commits each Ready status before the scheduler runs", async () => {readiness([ready("j1")]);await run([job("j1")], { jobIds: ["j1"] });- expect(events).toEqual(["ready:j1", "schedule"]);+ expect(events).toEqual(["recalculate", "mrp", "ready:j1", "schedule"]);});it("names a job that is not ready and still releases the others", async () => {- readiness([- ready("j1", { manufacturingBlocked: true }),- ready("j2"),- ready("j3", { nothingToMake: true }),- ready("j4", {- makeToAssetError:- "A job linked to a sales order line cannot complete to a fixed asset"- })- ]);- const { data } = await run([job("j1"), job("j2"), job("j3"), job("j4")], {- jobIds: ["j1", "j2", "j3", "j4"]+ readiness([ready("j1", { manufacturingBlocked: true }), ready("j2")]);+ const { data } = await run([job("j1"), job("j2")], {+ jobIds: ["j1", "j2"]});expect(data?.released).toEqual([{ jobId: "j2", readableId: "J2" }]);expect(data?.failed).toEqual([- { jobId: "j1", readableId: "J1", message: "manufacturing is blocked" },- { jobId: "j3", readableId: "J3", message: "nothing to make" },- {- jobId: "j4",- readableId: "J4",- message:- "A job linked to a sales order line cannot complete to a fixed asset"- }+ { jobId: "j1", readableId: "J1", message: expect.any(String) }]);});@@ -393,17 +353,14 @@ describe("releaseJobs", () => {];readiness([ready("j1", { supplierIds: ["supplier-a"] })], suppliers);const refused = await run([job("j1")], { jobIds: ["j1"] });- expect(refused.data?.failed[0]?.message).toBe(- "choose a purchase order for its outside operations on the job"- );+ expect(refused.data?.failed.map((ref) => ref.jobId)).toEqual(["j1"]);- readiness([ready("j1", { supplierIds: ["supplier-a"] })], suppliers);const chosen = await run([job("j1")], {jobIds: ["j1"],purchaseOrdersBySupplierId: { "supplier-a": "po-1" }});expect(chosen.data?.released).toHaveLength(1);- expect(invoke.mock.calls[0]?.[1]).toMatchObject({+ expect(invoke.mock.calls.find(([name]) => name === "create")?.[1]).toMatchObject({purchaseOrdersBySupplierId: { "supplier-a": "po-1" }});});@@ -418,13 +375,17 @@ describe("releaseJobs", () => {);// The map is the function's own and filled in afterwards: copy it per call.const sent: Record<string, string>[] = [];- invoke.mockImplementation(async (_name, input) => {- sent.push({ ...input.purchaseOrdersBySupplierId });- return {- data: { purchaseOrderIdsBySupplierId: { "supplier-a": "po-new" } },- error: null- };- });+ invoke.mockImplementation(+ postings({+ create: async (input) => {+ sent.push({ ...input.purchaseOrdersBySupplierId });+ return {+ data: { purchaseOrderIdsBySupplierId: { "supplier-a": "po-new" } },+ error: null+ };+ }+ })+ );await run([job("j1"), job("j2")], {jobIds: ["j1", "j2"],purchaseOrdersBySupplierId: {}@@ -433,21 +394,19 @@ describe("releaseJobs", () => {});it("reports a job that left Draft or Planned during the release, and schedules each location once", async () => {- readiness([ready("j1"), ready("j2"), ready("j3", {})]);- vi.mocked(updateJobStatus).mockImplementation(async (_client, { id }) => {- events.push(`ready:${id}`);- return { error: null, updated: id !== "j2" } as any;- });- const { data } = await run(- [job("j1"), job("j2"), job("j3", { locationId: "location-2" })],- { jobIds: ["j1", "j2", "j3"] }+ readiness([ready("j1"), ready("j2"), ready("j3")]);+ const jobs = [job("j1"), job("j2"), job("j3", { locationId: "location-2" })];+ invoke.mockImplementation(+ postings({+ recalculate: async (input) => {+ if (input.id === "j2") jobs[1]!.status = "Cancelled";+ return { data: {}, error: null };+ }+ }));+ const { data } = await run(jobs, { jobIds: ["j1", "j2", "j3"] });expect(data?.failed).toEqual([- {- jobId: "j2",- readableId: "J2",- message: "The job is no longer Draft or Planned"- }+ { jobId: "j2", readableId: "J2", message: expect.any(String) }]);expect(vi.mocked(runLocationSchedule).mock.calls.map(([args]) => args.locationId)@@ -456,15 +415,17 @@ describe("releaseJobs", () => {it("counts and schedules a job released before its purchase orders failed", async () => {readiness([ready("j1")]);- invoke.mockResolvedValueOnce({- data: null,- error: { message: "no supplier currency" }- });+ invoke.mockImplementation(+ postings({+ create: async () => ({+ data: null,+ error: { message: "no supplier currency" }+ })+ })+ );const { data } = await run([job("j1")], { jobIds: ["j1"] });expect(data?.released).toHaveLength(1);- expect(data?.warnings[0]?.message).toMatch(- /^The job is released, but its purchase orders could not be created/- );+ expect(data?.warnings.map((ref) => ref.jobId)).toEqual(["j1"]);expect(runLocationSchedule).toHaveBeenCalledOnce();});@@ -481,9 +442,9 @@ describe("releaseJobs", () => {it("loads a large selection in groups, and releases it in job order", async () => {const ids = Array.from({ length: 250 }, (_, index) => `j${index}`);// Stored out of order, so the release order is the function's own doing.- const { client, inFilterSizes } = clientFor(- [...ids].reverse().map((id) => job(id, { jobId: id.padStart(5, "0") }))- );+ const { client, inFilterSizes } = database({+ job: [...ids].reverse().map((id) => job(id, { jobId: id.padStart(5, "0") }))+ });readiness(ids.map((id) => ready(id)));const { data } = await releaseJobs(contextFor(client), { jobIds: ids });expect(inFilterSizes.slice(0, 3)).toEqual([100, 100, 50]);@@ -497,61 +458,17 @@ describe("releaseJobs", () => {it("refuses a supplier choice for an operation of another job", async () => {readiness([ready("j1")]);- const system = {- from: () => {- const chain: Record<string, any> = {};- for (const method of ["select", "eq", "in"]) chain[method] = () => chain;- chain.then = (resolve: (value: unknown) => unknown) =>- Promise.resolve({ data: [], error: null }).then(resolve);- return chain;- }- };- const ctx = createServiceContext({- ...({} as any),- actor: {- type: "user",- userId: "user-1",- permissions: {- production: { view: [], create: [], update: ["company-1"], delete: [] }- }- },- company: { id: "company-1", groupId: "group-1" },- caller: clientFor([job("j1")]).client,- system: () => system as any,- pg: () => ({}) as any,- kv: () => ({}) as any- });- const { error } = await releaseJobs(ctx, {+ const { error } = await run([job("j1")], {jobIds: ["j1"],supplierProcessByOperationId: { "op-elsewhere": "sp-1" }});expect(error).toMatchObject({ category: "validation" });- expect(updateJobStatus).not.toHaveBeenCalled();+ expect(events).toEqual([]);});});describe("releaseBatches", () => {- // Tables by name; `in` filters on the column it names.- function clientWith(tables: Record<string, Record<string, unknown>[]>) {- return {- from: (table: string) => {- let rows = tables[table] ?? [];- const chain: Record<string, any> = {};- for (const method of ["select", "eq", "order", "update"]) {- chain[method] = () => chain;- }- chain.in = (column: string, values: string[]) => {- rows = rows.filter((row) => values.includes(row[column] as string));- return chain;- };- chain.then = (resolve: (value: unknown) => unknown) =>- Promise.resolve({ data: rows, error: null }).then(resolve);- return chain;- }- } as any;- }-- const tables = {+ const tables = () => ({jobOperationBatch: [{ id: "b1", readableId: "BAT1", status: "Planned", workCenterId: "wc1" },{ id: "b2", readableId: "BAT2", status: "Active", workCenterId: "wc1" },@@ -565,15 +482,21 @@ describe("releaseBatches", () => {{ id: "j1", jobId: "J1", status: "Planned" },{ id: "j3", jobId: "J3", status: "Planned" }]- };+ });+ const release = (batchIds: string[]) =>+ releaseBatches(contextFor(database(tables()).client), { batchIds });it("releases a batch's jobs, then the batch, then tells the scheduler", async () => {readiness([ready("j1")]);- const { data } = await releaseBatches(contextFor(clientWith(tables)), {- batchIds: ["b1"]- });+ const { data } = await release(["b1"]);expect(data?.released).toEqual([{ batchId: "b1", readableId: "BAT1" }]);- expect(events).toEqual(["ready:j1", "batch:b1", "notify"]);+ expect(events).toEqual([+ "recalculate",+ "mrp",+ "ready:j1",+ "batch:b1",+ "notify"+ ]);});it("skips a batch that is not Planned, and refuses one whose job is not ready", async () => {@@ -589,20 +512,12 @@ describe("releaseBatches", () => {error: null}) as any);- const { data } = await releaseBatches(contextFor(clientWith(tables)), {- batchIds: ["b1", "b2", "b3"]- });+ const { data } = await release(["b1", "b2", "b3"]);expect(data?.released.map((ref) => ref.batchId)).toEqual(["b1"]);expect(data?.skipped).toEqual([{ batchId: "b2", readableId: "BAT2", status: "Active" }]);- expect(data?.failed).toEqual([- {- batchId: "b3",- readableId: "BAT3",- message: "Fix these jobs before releasing: J3: manufacturing is blocked"- }- ]);+ expect(data?.failed.map((ref) => ref.batchId)).toEqual(["b3"]);expect(events).not.toContain("batch:b3");});});diff --git a/apps/erp/test/resolve-location-id.test.ts b/apps/erp/test/resolve-location-id.test.tsindex 8c955abbc0..90acbc6e2b 100644--- a/apps/erp/test/resolve-location-id.test.ts+++ b/apps/erp/test/resolve-location-id.test.ts@@ -2,7 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { describe, expect, it, vi } from "vitest";+import { describe, expect, it } from "vitest";import { resolveLocationId } from "~/modules/shared/shared.service";@@ -20,143 +20,83 @@ const OWN_LOCATION = "loc_owned_by_a";const FOREIGN_LOCATION = "loc_owned_by_b";const DEFAULT_LOCATION = "loc_default_of_a";-/**- * Minimal stand-in for the bits of the supabase client this function touches:- * `.from("location").select().eq().eq().maybeSingle()` for the scoping probe,- * and `.from("userDefaults")…` / `.from("location")…` for the fallbacks.- * `location` rows are keyed by (id, companyId), mirroring the composite PK.- */-function makeClient(locations: { id: string; companyId: string }[]) {- const calls: string[] = [];-- const client = {- calls,- from(table: string) {- calls.push(table);- const filters: Record<string, unknown> = {};- const builder: Record<string, unknown> = {- select: () => builder,- eq: (col: string, val: unknown) => {- filters[col] = val;- return builder;- },- order: () => builder,- maybeSingle: async () => {- const match = locations.find(- (l) => l.id === filters.id && l.companyId === filters.companyId- );- return { data: match ? { id: match.id } : null, error: null };- },- single: async () => ({- data: { locationId: DEFAULT_LOCATION },- error: null- }),- then: undefined- };- return builder;- }- };-- return client as unknown as Parameters<typeof resolveLocationId>[0] & {- calls: string[];+type Row = Record<string, unknown>;++/** A Supabase client over in-memory tables; `eq` filters, and reads are logged. */+function clientWith(tables: Record<string, Row[]>) {+ const reads: string[] = [];+ const from = (table: string) => {+ reads.push(table);+ let rows = tables[table] ?? [];+ const chain: Record<string, unknown> = {+ select: () => chain,+ order: () => chain,+ eq: (column: string, value: unknown) => {+ rows = rows.filter((row) => row[column] === value);+ return chain;+ },+ maybeSingle: async () => ({ data: rows[0] ?? null, error: null }),+ then: (resolve: (value: unknown) => unknown) =>+ resolve({ data: rows, error: null })+ };+ return chain;};+ return { client: { from } as never, reads };}-function args(searchParams: string) {- return {+const company = clientWith({+ location: [+ { id: DEFAULT_LOCATION, companyId: COMPANY },+ { id: OWN_LOCATION, companyId: COMPANY },+ { id: FOREIGN_LOCATION, companyId: "company_b" }+ ],+ userDefaults: [+ { userId: "user_1", companyId: COMPANY, locationId: DEFAULT_LOCATION }+ ]+});++const resolve = (+ { client }: ReturnType<typeof clientWith>,+ searchParams: string+) =>+ resolveLocationId(client, new Request("https://erp.test/x/priority/dates"), {searchParams: new URLSearchParams(searchParams),userId: "user_1",companyId: COMPANY,onDefaultsError: "/x/production",onNoLocations: "/x/production"- };-}--// `~/modules/resources` is a barrel that reaches UI components and so pulls in-// `@carbon/content/glossary`, whose `msg` macro is untransformed under vitest (no-// lingui plugin here). Stub it so this test exercises the server helper only.-vi.mock("@carbon/content/glossary", () => ({- getDefinitionText: () => "",- getEntry: () => undefined,- getTermText: () => "",- glossaryEntries: [],- hasEntry: () => false,- listEntries: () => [],- lookupEntry: () => undefined,- termSlug: () => "",- terms: {}-}));--// The defaults path goes through `getUserDefaults`, which reads a different-// table via a different shape; stub it so these cases exercise only the-// scoping decision.-vi.mock("~/modules/users/users.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- getUserDefaults: async () => ({- data: { locationId: DEFAULT_LOCATION },- error: null- })-}));--vi.mock("~/modules/resources/resources.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- getLocationsList: async () => ({- data: [{ id: DEFAULT_LOCATION }],- error: null- })-}));+ });describe("resolveLocationId company scoping", () => {- const request = new Request("https://erp.test/x/priority/dates");-it("returns a ?location= that belongs to the caller's company", async () => {- const client = makeClient([{ id: OWN_LOCATION, companyId: COMPANY }]);-- const result = await resolveLocationId(- client,- request,- args(`location=${OWN_LOCATION}`)+ expect(await resolve(company, `location=${OWN_LOCATION}`)).toBe(+ OWN_LOCATION);-- expect(result).toBe(OWN_LOCATION);});- it("never returns a ?location= belonging to another company", async () => {- const client = makeClient([- { id: OWN_LOCATION, companyId: COMPANY },- { id: FOREIGN_LOCATION, companyId: "company_b" }- ]);-- const result = await resolveLocationId(- client,- request,- args(`location=${FOREIGN_LOCATION}`)- );-- expect(result).not.toBe(FOREIGN_LOCATION);- expect(result).toBe(DEFAULT_LOCATION);+ it.each([+ ["belonging to another company", FOREIGN_LOCATION],+ ["that does not exist", "loc_does_not_exist"]+ ])("falls back to the user's default for a ?location= %s", async (_case, id) => {+ expect(await resolve(company, `location=${id}`)).toBe(DEFAULT_LOCATION);});- it("falls back for a ?location= that does not exist at all", async () => {- const client = makeClient([{ id: OWN_LOCATION, companyId: COMPANY }]);-- const result = await resolveLocationId(- client,- request,- args("location=loc_does_not_exist")- );-- expect(result).toBe(DEFAULT_LOCATION);+ it("falls back to the company's first location without a default", async () => {+ const noDefaults = clientWith({+ location: [{ id: OWN_LOCATION, companyId: COMPANY }]+ });+ expect(await resolve(noDefaults, "")).toBe(OWN_LOCATION);});it("skips the scoping probe when no ?location= is supplied", async () => {- const client = makeClient([{ id: OWN_LOCATION, companyId: COMPANY }]);-- const result = await resolveLocationId(client, request, args(""));-- expect(result).toBe(DEFAULT_LOCATION);- // The probe is the only reason this function reads `location` directly;- // the absent-param path must not pay for it.- expect(client.calls).not.toContain("location");+ const probe = clientWith({+ location: [{ id: OWN_LOCATION, companyId: COMPANY }],+ userDefaults: [+ { userId: "user_1", companyId: COMPANY, locationId: DEFAULT_LOCATION }+ ]+ });+ expect(await resolve(probe, "")).toBe(DEFAULT_LOCATION);+ // The probe is the only reason this function reads `location` directly.+ expect(probe.reads).toEqual(["userDefaults"]);});});diff --git a/apps/erp/test/resources-operations.test.ts b/apps/erp/test/resources-operations.test.tsindex 7f06aae2f4..f4e1965002 100644--- a/apps/erp/test/resources-operations.test.ts+++ b/apps/erp/test/resources-operations.test.ts@@ -4,14 +4,6 @@import { beforeEach, describe, expect, it, vi } from "vitest";-// The service's imports reach the glossary, whose `msg` macro only runs compiled.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn(), warn: vi.fn(), info: vi.fn() })-}));-const { invoke, trigger } = vi.hoisted(() => ({// The server functions (`issue`, `post-maintenance-event`).invoke: vi.fn(),@@ -23,20 +15,9 @@ vi.mock("../app/modules/shared/shared.service", async (importOriginal) => {await importOriginal<typeof import("../app/modules/shared/shared.service")>();- // The postings the server functions package ran are the boundary; every- // other posting runs its (mocked) body as before.- const stubbed = new Set([- "issue",- "create",- "batch-operations",- "post-inventory-adjustment",- "post-maintenance-event",- "post-picking",- "post-production-event",- "recalculate",- "reschedule",- "trigger-rework"- ]);+ // Postings are database work with their own database tests; here they+ // answer `invoke`, and what they are sent is the contract.+ const stubbed = new Set(["issue", "post-maintenance-event"]);return {...actual,invokePosting: ((from: never, name: string, input: never, ...rest: never[]) =>@@ -47,8 +28,7 @@ vi.mock("../app/modules/shared/shared.service", async (importOriginal) => {name,input,...rest- )) as typeof actual.invokePosting,- invokeCreate: (_from: unknown, input: unknown) => invoke("create", input)+ )) as typeof actual.invokePosting};});vi.mock("@carbon/jobs", () => ({ trigger }));@@ -168,10 +148,7 @@ describe("maintenance timecards", () => {const result = await createMaintenanceEvent(ctx, timecard);expect(result).toEqual({- data: {- id: "ev-1",- warning: "Timecard added, but its labor cost did not post"- },+ data: { id: "ev-1", warning: expect.any(String) },error: null});expect(writes.map((w) => `${w.op}:${w.table}`)).toEqual([@@ -300,7 +277,7 @@ describe("creating a process that requires an ability", () => {requiresAbility: true});- expect(result.error?.message).toBe("Failed to create process ability.");+ expect(result.error?.category).toBe("internal");expect(writes.map((w) => [w.op, w.table, w.payload])).toContainEqual(["update","process",@@ -344,9 +321,7 @@ describe("training assignments", () => {employeeId: "user-2"});- expect(result.error?.message).toBe(- "This employee is not assigned this training"- );+ expect(result.error?.category).toBe("rule");expect(writes).toEqual([]);});});@@ -365,20 +340,6 @@ describe("a training's guide", () => {expect(writes).toEqual([]);});- it("changes only while the training is Draft", async () => {- const { ctx } = contextWith({ training: [] });-- const result = await updateTrainingField(ctx, {- ids: ["tr-1"],- field: "guidePath",- value: "company-1/training/tr-1/upload/guide.pdf"- });-- expect(result.error?.message).toBe(- "The guide can only change while the training is Draft"- );- });-it("clears the training's video", async () => {const { ctx, writes } = contextWith({ training: [{ id: "tr-1" }] });@@ -405,7 +366,7 @@ describe("a training's video", () => {value: "https://vimeo.com/123456789"});- expect(result.error?.message).toBe("Enter a YouTube video link");+ expect(result.error?.category).toBe("validation");expect(writes).toEqual([]);});@@ -424,18 +385,16 @@ describe("a training's video", () => {guidePath: null});});+});- it("changes only while the training is Draft", async () => {+describe("a training's guide or video", () => {+ it.each([+ ["guidePath", "company-1/training/tr-1/upload/guide.pdf"] as const,+ ["videoUrl", "https://www.youtube.com/watch?v=dQw4w9WgXcQ"] as const+ ])("changes %s only while the training is Draft", async (field, value) => {+ // The update is scoped to Draft trainings: none matched.const { ctx } = contextWith({ training: [] });-- const result = await updateTrainingField(ctx, {- ids: ["tr-1"],- field: "videoUrl",- value: "https://www.youtube.com/watch?v=dQw4w9WgXcQ"- });-- expect(result.error?.message).toBe(- "The video can only change while the training is Draft"- );+ const result = await updateTrainingField(ctx, { ids: ["tr-1"], field, value });+ expect(result.error?.category).toBe("rule");});});diff --git a/apps/erp/test/sales-operations.test.ts b/apps/erp/test/sales-operations.test.tsindex a55c9e0447..e864430fb4 100644--- a/apps/erp/test/sales-operations.test.ts+++ b/apps/erp/test/sales-operations.test.ts@@ -4,14 +4,6 @@import { beforeEach, describe, expect, it, vi } from "vitest";-// The service's imports reach the glossary, whose `msg` macro only runs compiled.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn(), warn: vi.fn(), info: vi.fn() })-}));-const { evaluate, invoke, recorded } = vi.hoisted(() => ({// The sales-rule evaluator: what the rules find on the document.evaluate: vi.fn(),@@ -34,10 +26,8 @@ vi.mock("@carbon/ee/rules.server", async () => {vi.mock("@carbon/lib/workflows", () => ({ raiseMoment: vi.fn() }));vi.mock("../app/modules/shared/shared.service", async (importOriginal) => ({...(await importOriginal<object>()),- refuseUnlessOwned: vi.fn(async () => null),- sendSalesOrderEmail: vi.fn(),+ // Cached in Redis, which tests have none of.getCompanyTimeZone: vi.fn(async () => "UTC"),- getLocationTimeZone: vi.fn(async () => "UTC"),// The postings (convert, create) run through invokePosting / invokeCreate.invokePosting: (_from: unknown, name: string, input: unknown) =>invoke(name, input),@@ -83,6 +73,7 @@ function serviceRole(rows: Record<string, unknown> = {}) {for (const method of ["select","eq",+ "match","in","limit","order",@@ -105,12 +96,15 @@ function serviceRole(rows: Record<string, unknown> = {}) {return { from } as any;}+// The company's own quote and order.+const owned = { quote: { id: "quote-1" }, salesOrder: { id: "order-1" } };+const contextFor = (permissions: Permissions) =>createServiceContext({actor: { type: "user", userId: "user-1", permissions },company: { id: "company-1", groupId: "group-1" },caller: serviceRole(),- system: () => serviceRole(),+ system: () => serviceRole(owned),pg: () => ({}) as any,kv: () => ({}) as any});diff --git a/apps/erp/test/schedule-moves.test.ts b/apps/erp/test/schedule-moves.test.tsindex c0cc2f9f04..733e53200b 100644--- a/apps/erp/test/schedule-moves.test.ts+++ b/apps/erp/test/schedule-moves.test.ts@@ -7,23 +7,10 @@ import { beforeEach, describe, expect, it, vi } from "vitest";// A card dropped on the schedule boards: which moves are refused before// anything is written, and when the scheduler is told.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("@carbon/env", async (importOriginal) => ({- ...(await importOriginal<typeof import("@carbon/env")>()),- ASSEMBLER_SERVICE_URL: ""-}));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn(), warn: vi.fn() })-}));-vi.mock("@carbon/jobs", () => ({ trigger: vi.fn(), batchTrigger: vi.fn() }));-vi.mock("@carbon/planning", () => ({ runLocationSchedule: vi.fn() }));-vi.mock("../app/modules/production/production.service", () => ({- notifyScheduleInputsChanged: vi.fn()-}));+// The scheduler is told through an event.+const { trigger } = vi.hoisted(() => ({ trigger: vi.fn() }));+vi.mock("@carbon/jobs", () => ({ trigger }));-import { notifyScheduleInputsChanged } from "../app/modules/production/production.service";import {moveScheduleJob,reorderScheduleOperations@@ -171,7 +158,7 @@ describe("reorderScheduleOperations", () => {message: "Invalid scheduling request"});expect(caller.writes).toEqual([]);- expect(notifyScheduleInputsChanged).not.toHaveBeenCalled();+ expect(trigger).not.toHaveBeenCalled();});});@@ -189,7 +176,9 @@ describe("moveScheduleJob", () => {const result = await move(caller);expect(result.error).toBeNull();expect(caller.writes).toEqual(["job"]);- expect(notifyScheduleInputsChanged).toHaveBeenCalledOnce();+ expect(trigger.mock.calls.map(([event]) => event)).toEqual([+ "schedule-inputs-changed"+ ]);});it("refuses a column that is not a date before writing", async () => {@@ -205,11 +194,11 @@ describe("moveScheduleJob", () => {category: "conflict",message: "Job unavailable or locked"});- expect(notifyScheduleInputsChanged).not.toHaveBeenCalled();+ expect(trigger).not.toHaveBeenCalled();});it("keeps the move when the scheduler cannot be told", async () => {- vi.mocked(notifyScheduleInputsChanged).mockResolvedValueOnce(false);+ trigger.mockRejectedValueOnce(new Error("event bus down"));const result = await move(callerWith({ job: { data: { id: "j1" }, error: null } }));expect(result.error).toBeNull();});diff --git a/apps/erp/test/settings-operations.test.ts b/apps/erp/test/settings-operations.test.tsindex 7f8b3a29f7..30342ba7ae 100644--- a/apps/erp/test/settings-operations.test.ts+++ b/apps/erp/test/settings-operations.test.ts@@ -5,25 +5,18 @@import { createClient } from "@supabase/supabase-js";import { beforeEach, describe, expect, it, vi } from "vitest";-// The service's imports reach the glossary, whose `msg` macro only runs compiled.-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })-}));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn(), warn: vi.fn(), info: vi.fn() })-}));-const {stripeAccount,consoleSetting,requireMfaSetting,- mfaEmails,+ batchTrigger,unmappedRequiredAccounts} = vi.hoisted(() => ({stripeAccount: vi.fn(),consoleSetting: vi.fn(),requireMfaSetting: vi.fn(),- mfaEmails: vi.fn(),+ // Inngest: the two-factor announcement is sent through it.+ batchTrigger: vi.fn(),unmappedRequiredAccounts: vi.fn()}));vi.mock("@carbon/ee/accounting", async (importOriginal) => ({@@ -45,25 +38,23 @@ vi.mock("@carbon/ee/two-factor.server", () => ({vi.mock("@carbon/printing/printing.server", () => ({invalidatePrinterCache: vi.fn()}));-vi.mock("../app/services/mfa-email.server", () => ({- sendMfaRequiredEmails: mfaEmails-}));+vi.mock("@carbon/jobs", () => ({ batchTrigger, trigger: vi.fn() }));import { EntitlementError } from "@carbon/ee/entitlements.server";import { createServiceContext } from "@carbon/api/service-fn.server";-const {+import {removePrinterRoute,setIntegrationSyncEnabled,- updatePostingSync,+ transitionSyncOperations,updateInventorySettings,updateInvoicingSettings,updatePeopleSettings,updatePlanningSettings,- transitionSyncOperations,+ updatePostingSync,updateSecuritySettings,updateSubsidiaryDetails-} = await import("../app/modules/settings/settings.server");+} from "../app/modules/settings/settings.server";const settings = {settings: {@@ -177,10 +168,7 @@ describe("invoicing settings", () => {invoiceAutomation: "Post and Send via Stripe"});- expect(result.error).toMatchObject({- category: "rule",- message: "Connect Stripe in Integrations first"- });+ expect(result.error?.category).toBe("rule");expect(writes).toEqual([]);});@@ -227,10 +215,7 @@ describe("people settings", () => {const result = await updatePeopleSettings(ctx, { consoleEnabled: true });- expect(result.error).toMatchObject({- category: "entitlement",- message: "Console mode requires the Business plan"- });+ expect(result.error?.category).toBe("entitlement");});it("generates no console PIN for a key caller: the key holder may not be its creator", async () => {@@ -257,20 +242,21 @@ describe("security settings", () => {requireMfaSetting.mockResolvedValue({ error: null });});- it("emails the company when two-factor goes from optional to required", async () => {- const { ctx } = contextWith({ companySettings: { requireMfa: false } });-- await updateSecuritySettings(ctx, { requireMfa: true });+ const company = (requireMfa: boolean) =>+ contextWith({+ companySettings: { requireMfa },+ company: { name: "Acme" },+ employees: [{ id: "user-2", email: "[email protected]", name: "Ada" }]+ });- expect(mfaEmails).toHaveBeenCalledWith(expect.anything(), "company-1");+ it("emails the company when two-factor goes from optional to required", async () => {+ await updateSecuritySettings(company(false).ctx, { requireMfa: true });+ expect(batchTrigger).toHaveBeenCalledOnce();});it("does not announce a requirement that was already on", async () => {- const { ctx } = contextWith({ companySettings: { requireMfa: true } });-- await updateSecuritySettings(ctx, { requireMfa: true });-- expect(mfaEmails).not.toHaveBeenCalled();+ await updateSecuritySettings(company(true).ctx, { requireMfa: true });+ expect(batchTrigger).not.toHaveBeenCalled();});});@@ -378,10 +364,7 @@ describe("an accounting integration's settings", () => {syncEnabled: true});- expect(result.error).toMatchObject({- category: "rule",- message: "Map the remaining 2 required accounts before turning on sync"- });+ expect(result.error?.category).toBe("rule");expect(writes).toEqual([]);});@@ -487,10 +470,7 @@ describe("retrying or skipping sync operations", () => {to: "Pending"});- expect(result.error).toMatchObject({- category: "rule",- message: "Updated 1 of 3 sync operations"- });+ expect(result.error?.category).toBe("rule");expect(result.error?.cause).toEqual([{ id: "op-2", reason: "invalid transition In Flight → Pending" },{ id: "op-3", reason: "Sync operation op-3 not found" }diff --git a/apps/erp/test/update-purchase-order-line-schedule.test.ts b/apps/erp/test/update-purchase-order-line-schedule.test.tsdeleted file mode 100644index ccfc89254b..0000000000--- a/apps/erp/test/update-purchase-order-line-schedule.test.ts+++ /dev/null@@ -1,122 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import type { Kysely, KyselyDatabase } from "@carbon/database/client";-import {- type CompiledQuery,- type DatabaseConnection,- DummyDriver,- Kysely as KyselyClient,- PostgresAdapter,- PostgresIntrospector,- PostgresQueryCompiler,- type QueryResult-} from "kysely";-import { describe, expect, it, vi } from "vitest";--vi.mock("@carbon/content/glossary", () => ({- terms: {},- getEntry: vi.fn(),- lookupEntry: vi.fn(),- hasEntry: vi.fn(),- termSlug: vi.fn(),- glossaryEntries: () => []-}));-// The service's module graph reaches @carbon/onboarding, whose content builds-// Lingui `msg` descriptors at load; the macro is not compiled under vitest-// (same stub as production.service.test.ts).-vi.mock("@lingui/core/macro", () => ({- msg: (strings: TemplateStringsArray | string, ...values: unknown[]) =>- Array.isArray(strings)- ? strings.reduce(- (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),- ""- )- : String(strings)-}));--const { updatePurchaseOrderLineSchedule } = await import(- "../app/modules/purchasing/purchasing.service"-);--// The drawer's inline edit of one open PO line: a quantity or a required date,-// with the Draft / Planned guard inside the one UPDATE so a PO sent after the-// route read it is left alone. (Planning's Cancel, which deletes a line, is-// set-based with the rest of Apply — apply-purchasing-planning-actions.test.ts.)--class RecordingDriver extends DummyDriver {- readonly sent: CompiledQuery[] = [];- constructor(private readonly returnedIds: string[]) {- super();- }- override async acquireConnection(): Promise<DatabaseConnection> {- return {- executeQuery: async <R>(- query: CompiledQuery- ): Promise<QueryResult<R>> => {- this.sent.push(query);- return { rows: this.returnedIds.map((id) => ({ id })) as R[] };- },- // biome-ignore lint/correctness/useYield: never streamed- streamQuery: async function* () {- throw new Error("not streamed");- }- };- }-}--function database(returnedIds: string[]) {- const driver = new RecordingDriver(returnedIds);- const db = new KyselyClient<KyselyDatabase>({- dialect: {- createAdapter: () => new PostgresAdapter(),- createDriver: () => driver,- createIntrospector: (k) => new PostgresIntrospector(k),- createQueryCompiler: () => new PostgresQueryCompiler()- }- }) as unknown as Kysely<KyselyDatabase>;- return { db, driver };-}--const args = { lineId: "pol1", purchaseOrderId: "po1", companyId: "c1" };--describe("updatePurchaseOrderLineSchedule", () => {- const dateChange = {- lineId: "pol1",- companyId: "c1",- companyGroupId: "g1",- userId: "u1",- requiredDate: "2026-11-02"- };-- it("updates the line only while its PO is Draft or Planned, in one statement", async () => {- const { db, driver } = database(["pol1"]);- // A date change reads nothing first, so the client is never used.- await updatePurchaseOrderLineSchedule({} as never, db, dateChange);-- expect(driver.sent).toHaveLength(1);- const [{ sql, parameters }] = driver.sent;- expect(sql).toMatch(/^update "purchaseOrderLine" set "requiredDate" = \$1/);- expect(sql).toMatch(- /"purchaseOrderId" in \(select "id" from "purchaseOrder" where "companyId" = \$\d+ and "status" in \(\$\d+, \$\d+\)\)/- );- expect(parameters).toEqual(- expect.arrayContaining(["pol1", "c1", "Draft", "Planned"])- );- });-- it("reports the line updated", async () => {- const { db } = database(["pol1"]);- expect(- await updatePurchaseOrderLineSchedule({} as never, db, dateChange)- ).toEqual({ updated: true, error: null });- });-- it("reports nothing updated when the PO left Draft / Planned", async () => {- const { db } = database([]);- expect(- await updatePurchaseOrderLineSchedule({} as never, db, dateChange)- ).toEqual({ updated: false, error: null });- });-});diff --git a/apps/erp/test/users-account-operations.test.ts b/apps/erp/test/users-account-operations.test.tsindex daa8bfb791..ccbf803296 100644--- a/apps/erp/test/users-account-operations.test.ts+++ b/apps/erp/test/users-account-operations.test.ts@@ -2,134 +2,126 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { beforeEach, describe, expect, it, vi } from "vitest";--vi.mock("@lingui/core/macro", () => ({ msg: (value: unknown) => value }));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({ error: vi.fn(), info: vi.fn(), warn: vi.fn() })-}));-vi.mock("../app/modules/users/users.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- deleteUserAttributeValue: vi.fn(),- getChangelogPanelEntry: vi.fn(),- getCurrentUser: vi.fn(),- updateAvatar: vi.fn(),- upsertUserAttributeValue: vi.fn()-}));--vi.mock("../app/modules/people/people.service", async (importOriginal) => ({- ...(await importOriginal<object>()),- getAttribute: vi.fn()-}));-+import { describe, expect, it } from "vitest";import {deleteAttributeValue,updateOwnAvatar,upsertAttributeValue} from "../app/modules/users/users.server";-import {- deleteUserAttributeValue,- getCurrentUser,- updateAvatar,- upsertUserAttributeValue-} from "../app/modules/users/users.service";-import { getAttribute } from "../app/modules/people/people.service";import { createServiceContext } from "@carbon/api/service-fn.server";-// Saving the avatar saves the new value, then deletes the photo it replaced.-// The order is the point: deleting first and then failing the save left-// avatarUrl pointing at a file that no longer existed.-const USER_ID = "5f0c3d2a-1b2c-4d5e-8f90-123456789abc";+const OTHER = "9a8b7c6d-0000-4000-8000-000000000000";const GENERATED = "dicebear:voxel-art:3f2b8c4e-6a1d-4f7e-9b2c:1e3a8a";-const calls: string[] = [];-const remove = vi.fn(async (paths: string[]) => {- calls.push(`remove:${paths.join(",")}`);- return { error: null };-});+/**+ * The user's client: each table's one row for a read; each write, and each+ * avatar photo removed, is logged to `calls`. `failing` names the tables+ * whose writes fail.+ */+function clientWith(rows: Record<string, unknown>, failing: string[] = []) {+ const calls: string[] = [];+ const from = (table: string) => {+ let written = false;+ const write = (entry: string) => {+ calls.push(entry);+ written = true;+ return chain;+ };+ const answer = () =>+ failing.includes(table)+ ? { data: null, error: { message: "boom" } }+ : { data: written ? { id: "value-1" } : (rows[table] ?? null), error: null };+ const chain: Record<string, any> = {+ select: () => chain,+ eq: () => chain,+ update: (values: { avatarUrl?: string }) =>+ write(table === "user" ? `update:${values.avatarUrl}` : `update ${table}`),+ insert: () => write(`insert ${table}`),+ delete: () => write(`delete ${table}`),+ single: async () => answer(),+ then: (resolve: (value: unknown) => unknown) => resolve(answer())+ };+ return chain;+ };+ const storage = {+ from: () => ({+ remove: async (paths: string[]) => {+ calls.push(`remove:${paths.join(",")}`);+ return { error: null };+ }+ })+ };+ return { client: { from, storage } as never, calls };+}const unreachable = () => {throw new Error("must not be reached");};-function saveAvatar(path: string) {- const ctx = createServiceContext({+function contextAs(caller: never, permissions: Record<string, unknown> = {}) {+ return createServiceContext({// `{}` admits a member of the company: anyone holding a grant there.actor: {type: "user",userId: USER_ID,permissions: {- documents: { view: ["company-1"], create: [], update: [], delete: [] }- }+ documents: { view: ["company-1"], create: [], update: [], delete: [] },+ ...permissions+ } as never},company: { id: "company-1", groupId: "group-1" },- caller: { storage: { from: () => ({ remove }) } } as never,+ caller,system: unreachable as never,pg: unreachable as never,kv: unreachable as never});- return updateOwnAvatar(ctx, { path });}-beforeEach(() => {- vi.clearAllMocks();-});-+// Saving the avatar saves the new value, then deletes the photo it replaced:+// deleting first and then failing the save left avatarUrl pointing at a file+// that no longer existed.describe("updateOwnAvatar", () => {- beforeEach(() => {- calls.length = 0;- remove.mockClear();- vi.mocked(updateAvatar).mockImplementation((async (- _client: unknown,- _userId: string,- value: string | null- ) => {- calls.push(`update:${value}`);- return { error: null };- }) as never);- vi.mocked(getCurrentUser).mockResolvedValue({- data: { avatarUrl: `${USER_ID}.webp` },- error: null- } as never);- });+ async function saveAvatar(+ path: string,+ { previous = `${USER_ID}.webp`, failing = [] as string[] } = {}+ ) {+ const { client, calls } = clientWith({ user: { avatarUrl: previous } }, failing);+ const result = await updateOwnAvatar(contextAs(client), { path });+ return { result, calls };+ }it("saves the generated avatar, THEN deletes the photo it replaced", async () => {- const result = await saveAvatar(GENERATED);+ const { result, calls } = await saveAvatar(GENERATED);expect(result.error).toBeNull();expect(calls).toEqual([`update:${GENERATED}`, `remove:${USER_ID}.webp`]);});it("keeps the photo when the save fails", async () => {- vi.mocked(updateAvatar).mockResolvedValue({- error: { message: "boom" }- } as never);- const result = await saveAvatar(GENERATED);+ const { result, calls } = await saveAvatar(GENERATED, { failing: ["user"] });expect(result.error?.category).toBe("internal");- expect(remove).not.toHaveBeenCalled();+ expect(calls).toEqual([`update:${GENERATED}`]);});it("deletes nothing when the previous avatar was generated", async () => {- vi.mocked(getCurrentUser).mockResolvedValue({- data: { avatarUrl: "dicebear:croodles-neutral:abc" },- error: null- } as never);- await saveAvatar(GENERATED);+ const { calls } = await saveAvatar(GENERATED, {+ previous: "dicebear:croodles-neutral:abc"+ });expect(calls).toEqual([`update:${GENERATED}`]);});it("does not delete a photo the new upload overwrote in place", async () => {- await saveAvatar(`${USER_ID}.webp`);+ const { calls } = await saveAvatar(`${USER_ID}.webp`);expect(calls).toEqual([`update:${USER_ID}.webp`]);});it("removes an old upload with a different extension", async () => {- await saveAvatar(`${USER_ID}.png`);+ const { calls } = await saveAvatar(`${USER_ID}.png`);expect(calls).toEqual([`update:${USER_ID}.png`, `remove:${USER_ID}.webp`]);});it("refuses another user's file and changes nothing", async () => {- const result = await saveAvatar("someone-else.webp");+ const { result, calls } = await saveAvatar("someone-else.webp");expect(result.error?.category).toBe("validation");expect(calls).toEqual([]);});@@ -138,81 +130,47 @@ describe("updateOwnAvatar", () => {// Anyone with resources update may change anyone's attribute values; others// only their own, of an attribute marked as self-managed.describe("attribute values", () => {- const OTHER = "9a8b7c6d-0000-4000-8000-000000000000";- const value = {- userAttributeId: "attribute-1",- type: "text",- value: "Blue"- };-- function contextAs(permissions: Record<string, unknown>) {- return createServiceContext({- actor: {- type: "user",- userId: USER_ID,- permissions: {- documents: { view: ["company-1"], create: [], update: [], delete: [] },- ...permissions- } as never- },- company: { id: "company-1", groupId: "group-1" },- caller: {} as never,- system: unreachable as never,- pg: unreachable as never,- kv: unreachable as never- });- }-- beforeEach(() => {- vi.mocked(upsertUserAttributeValue).mockResolvedValue({- data: { id: "value-1" },- error: null- } as never);- vi.mocked(deleteUserAttributeValue).mockResolvedValue({- error: null- } as never);- });+ const value = { userAttributeId: "attribute-1", type: "text", value: "Blue" };+ const attribute = (canSelfManage: boolean) =>+ clientWith({ userAttribute: { canSelfManage } });it("lets resources update change another person's value", async () => {+ const { client } = attribute(false);const result = await upsertAttributeValue(- contextAs({ resources: { update: ["company-1"] } }),+ contextAs(client, { resources: { update: ["company-1"] } }),{ ...value, userId: OTHER });expect(result.data).toEqual({ userAttributeValueId: "value-1" });});it("refuses another person's value without resources update", async () => {- const result = await upsertAttributeValue(contextAs({}), {+ const { client, calls } = attribute(true);+ const result = await upsertAttributeValue(contextAs(client), {...value,userId: OTHER});expect(result.error?.category).toBe("forbidden");- expect(upsertUserAttributeValue).not.toHaveBeenCalled();+ expect(calls).toEqual([]);});it("lets a person set their own self-managed value", async () => {- vi.mocked(getAttribute).mockResolvedValue({- data: { canSelfManage: true },- error: null- } as never);- const result = await upsertAttributeValue(contextAs({}), {+ const { client, calls } = attribute(true);+ const result = await upsertAttributeValue(contextAs(client), {...value,userId: USER_ID});expect(result.error).toBeNull();+ expect(calls).toEqual(["insert userAttributeValue"]);});it("refuses removing their own value of a managed attribute", async () => {- vi.mocked(getAttribute).mockResolvedValue({- data: { canSelfManage: false },- error: null- } as never);- const result = await deleteAttributeValue(contextAs({}), {+ const { client, calls } = attribute(false);+ const result = await deleteAttributeValue(contextAs(client), {userId: USER_ID,userAttributeId: "attribute-1",userAttributeValueId: "value-1"});expect(result.error?.category).toBe("forbidden");- expect(deleteUserAttributeValue).not.toHaveBeenCalled();+ expect(calls).toEqual([]);});});diff --git a/apps/erp/vitest.config.ts b/apps/erp/vitest.config.tsindex 848a7929d5..42e2247081 100644--- a/apps/erp/vitest.config.ts+++ b/apps/erp/vitest.config.ts@@ -4,6 +4,7 @@import { linguiWithoutIdQuery } from "@carbon/dev/vite";import { lingui } from "@lingui/vite-plugin";+import { globSync, readFileSync } from "node:fs";import type { Plugin } from "vite";import { defineConfig } from "vitest/config";@@ -28,6 +29,18 @@ function moduleMacrosOnly(plugins: Plugin[]): Plugin[] {});}+const tests = globSync(["app/**/*.test.{ts,tsx}", "test/**/*.test.ts"], {+ cwd: import.meta.dirname+});+// Mocking a module, stubbing a global or writing process.env changes what+// every later import sees; a file that does gets modules of its own.+const isolates = (file: string) =>+ /\bvi\.(mock|doMock|stubGlobal|stubEnv)\(|process\.env(\.\w+|\[[^\]]+\])\s*=(?!=)|delete process\.env/.test(+ readFileSync(`${import.meta.dirname}/${file}`, "utf8")+ );+const isolated = tests.filter(isolates);+const shared = tests.filter((file) => !isolates(file));+export default defineConfig({// Compile Lingui macros in .ts modules as the app does, so a service that// reads a `msg` table can be imported without stubbing the macro. Components@@ -38,7 +51,15 @@ export default defineConfig({tsconfigPaths: true,},test: {- include: ["app/**/*.test.ts", "app/**/*.test.tsx", "test/**/*.test.ts"],+ // Each test file loading the app's modules afresh was nearly all of the+ // suite's time: the tests ran in 24 of its 400 seconds on CI. Files+ // that mock, stub or set the environment for nothing share loaded+ // modules instead; a file that does keeps its own, since a module+ // another file loaded first would ignore it.+ projects: [+ { extends: true, test: { name: "isolated", include: isolated } },+ { extends: true, test: { name: "shared", include: shared, isolate: false } }+ ],passWithNoTests: true,// @carbon/env throws at import time when these are unset; tests that// transitively import a module barrel (e.g. modules/shared) hit it.@@ -55,7 +76,9 @@ export default defineConfig({SUPABASE_DB_URL:process.env.SUPABASE_DB_URL ?? "postgresql://stub.invalid/postgres",SESSION_SECRET: "test",- REDIS_URL: "redis://localhost"+ // No Redis, as on CI: a test that reaches it hangs here too, rather+ // than passing against a developer's local Redis and failing on CI.+ REDIS_URL: "redis://stub.invalid"}}});diff --git a/apps/mes/app/services/models.batch.test.ts b/apps/mes/app/services/models.batch.test.tsindex 271a426e60..a50c2965de 100644--- a/apps/mes/app/services/models.batch.test.ts+++ b/apps/mes/app/services/models.batch.test.ts@@ -5,142 +5,56 @@import { describe, expect, it } from "vitest";import { completeJobOperationBatchValidator } from "./models";-// The Complete Batch form submits variable-length per-member quantities as a-// nested array (ValidatedForm), with quantity/scrap coerced from form strings via-// zfd.numeric. The validator must parse that shape into a typed array the-// batch-operations posting's "complete" path consumes. See-// .ai/specs/2026-08-21-job-operation-batching.md.-describe("completeJobOperationBatchValidator", () => {- it("parses per-member quantities and optional scrap", () => {- const result = completeJobOperationBatchValidator.safeParse({- batchId: "bat_1",- members: [- { jobOperationId: "op_1", quantity: 5 },- { jobOperationId: "op_2", quantity: 20, scrapQuantity: 2 },- { jobOperationId: "op_3", quantity: 10 }- ]- });-- expect(result.success).toBe(true);- if (result.success) {- expect(result.data.batchId).toBe("bat_1");- expect(result.data.members).toHaveLength(3);- expect(result.data.members[1]).toEqual({- jobOperationId: "op_2",- quantity: 20,- scrapQuantity: 2- });- }- });-- it("coerces numeric strings from the form (zfd.numeric)", () => {- const result = completeJobOperationBatchValidator.safeParse({- batchId: "bat_1",- members: [{ jobOperationId: "op_1", quantity: "7", scrapQuantity: "1" }]- });-- expect(result.success).toBe(true);- if (result.success) {- expect(result.data.members[0]).toEqual({- jobOperationId: "op_1",- quantity: 7,- scrapQuantity: 1- });- }+function parse(members: Record<string, unknown>[]) {+ return completeJobOperationBatchValidator.safeParse({+ batchId: "bat_1",+ members});+}- it("rejects an empty members array", () => {- const result = completeJobOperationBatchValidator.safeParse({- batchId: "bat_1",- members: []- });- expect(result.success).toBe(false);- });-- it("rejects a missing batchId", () => {- const result = completeJobOperationBatchValidator.safeParse({- members: [{ jobOperationId: "op_1", quantity: 5 }]- });- expect(result.success).toBe(false);- });-- it("rejects a negative quantity", () => {- const result = completeJobOperationBatchValidator.safeParse({- batchId: "bat_1",+describe("completeJobOperationBatchValidator", () => {+ it("parses per-member form strings into numbers", () => {+ expect(+ parse([+ { jobOperationId: "op_1", quantity: "7", scrapQuantity: "1" },+ { jobOperationId: "op_2", quantity: "20" }+ ]).data?.members+ ).toEqual([+ { jobOperationId: "op_1", quantity: 7, scrapQuantity: 1 },+ { jobOperationId: "op_2", quantity: 20 }+ ]);+ });++ it("keeps fractional quantities, rounded to internal precision", () => {+ // Operation quantities can be fractional for weight/length units of measure.+ expect(+ parse([+ { jobOperationId: "op_1", quantity: 0.123456, scrapQuantity: 0.25 }+ ]).data?.members+ ).toEqual([+ { jobOperationId: "op_1", quantity: 0.12346, scrapQuantity: 0.25 }+ ]);+ });++ it.each([+ { name: "no members", members: [] },+ {+ name: "a negative quantity",members: [{ jobOperationId: "op_1", quantity: -1 }]- });- expect(result.success).toBe(false);- });-- // An excluded ("Not in this run") member's quantity input is disabled, so its- // NumberControlled is omitted from FormData entirely — the member arrives with- // NO `quantity` key. The validator must accept that (quantity is optional); the- // route then forces the excluded member to 0. This is the revert-guard for- // making `quantity` optional.- it("accepts an excluded member with no quantity key", () => {- const result = completeJobOperationBatchValidator.safeParse({- batchId: "bat_1",- members: [- { jobOperationId: "op_1", quantity: 5 },- { jobOperationId: "op_2", excluded: "true" }- ]- });-- expect(result.success).toBe(true);- if (result.success) {- expect(result.data.members[1].quantity).toBeUndefined();- expect(result.data.members[1].excluded).toBe("true");}+ ])("rejects $name", ({ members }) => {+ expect(parse(members).success).toBe(false);});- // "Not in this run" travels as a string flag from a Hidden input (the same- // idiom as productionEventValidator's `exclusive`); the route maps- // `excluded === "true"` to a boolean before running the posting. An empty- // string (row included) must parse as absent, not as a truthy flag.- it("parses the excluded string flag per member", () => {- const result = completeJobOperationBatchValidator.safeParse({- batchId: "bat_1",- members: [+ it("accepts an excluded member whose disabled quantity input was not submitted", () => {+ expect(+ parse([{ jobOperationId: "op_1", quantity: 5, excluded: "" },- { jobOperationId: "op_2", quantity: 0, excluded: "true" }- ]- });-- expect(result.success).toBe(true);- if (result.success) {- expect(result.data.members[0].excluded).toBeUndefined();- expect(result.data.members[1].excluded).toBe("true");- }- });-});--describe("completeJobOperationBatchValidator — decimals", () => {- const parseMember = (member: Record<string, unknown>) =>- completeJobOperationBatchValidator.safeParse({- batchId: "bat_1",- members: [{ jobOperationId: "op_1", ...member }]- });-- it("accepts a fractional quantity", () => {- const result = parseMember({ quantity: 0.5 });- expect(result.success).toBe(true);- if (result.success) expect(result.data.members[0]!.quantity).toBe(0.5);- });-- it("rounds quantity to internal precision at parse", () => {- const result = parseMember({ quantity: 0.123456 });- expect(result.success).toBe(true);- if (result.success) expect(result.data.members[0]!.quantity).toBe(0.12346);- });-- it("accepts a fractional scrap quantity", () => {- const result = parseMember({ quantity: 1, scrapQuantity: 0.25 });- expect(result.success).toBe(true);- if (result.success)- expect(result.data.members[0]!.scrapQuantity).toBe(0.25);- });-- it("rejects a negative quantity", () => {- expect(parseMember({ quantity: -1 }).success).toBe(false);+ { jobOperationId: "op_2", excluded: "true" }+ ]).data?.members+ ).toEqual([+ { jobOperationId: "op_1", quantity: 5 },+ { jobOperationId: "op_2", excluded: "true" }+ ]);});});diff --git a/apps/mes/package.json b/apps/mes/package.jsonindex 2848625cba..3701a9265f 100644--- a/apps/mes/package.json+++ b/apps/mes/package.json@@ -2,10 +2,15 @@"name": "mes","type": "module","dependencies": {+ "@carbon/serve": "workspace:*"+ },+ "devDependencies": {"@carbon/account": "workspace:*","@carbon/api": "workspace:*","@carbon/auth": "workspace:*",+ "@carbon/config": "workspace:*","@carbon/database": "workspace:*",+ "@carbon/dev": "workspace:*","@carbon/documents": "workspace:*","@carbon/ee": "workspace:*","@carbon/files": "workspace:*",@@ -15,7 +20,6 @@"@carbon/lib": "workspace:*","@carbon/locale": "workspace:*","@carbon/logger": "workspace:*",- "@carbon/serve": "workspace:*","@carbon/notifications": "workspace:*","@carbon/printing": "workspace:*","@carbon/query": "workspace:*",@@ -30,10 +34,12 @@"@emoji-mart/data": "catalog:","@emoji-mart/react": "catalog:","@internationalized/date": "catalog:",+ "@lingui/conf": "catalog:","@lingui/core": "catalog:","@lingui/react": "catalog:","@lingui/vite-plugin": "catalog:","@react-aria/i18n": "catalog:",+ "@react-aria/optimize-locales-plugin": "catalog:","@react-pdf/renderer": "catalog:","@react-router/dev": "catalog:","@react-router/remix-routes-option-adapter": "catalog:",@@ -44,6 +50,7 @@"@tailwindcss/typography": "catalog:","@tailwindcss/vite": "catalog:","@tanstack/react-query": "catalog:",+ "@tanstack/react-query-devtools": "catalog:","@tiptap/core": "catalog:","@tiptap/extension-color": "catalog:","@tiptap/extension-list-item": "catalog:",@@ -56,20 +63,27 @@"@tiptap/pm": "catalog:","@tiptap/react": "catalog:","@tiptap/starter-kit": "catalog:",+ "@types/react": "catalog:",+ "@types/react-dom": "catalog:","@vercel/analytics": "catalog:","@vercel/functions": "catalog:","@vercel/react-router": "catalog:",+ "@vitejs/devtools": "catalog:",+ "@vitejs/devtools-rolldown": "catalog:","@xyflow/react": "12.10.2","class-variance-authority": "catalog:","cookie": "catalog:",+ "cross-env": "catalog:","dompurify": "catalog:",- "motion": "catalog:","isbot": "catalog:","konva": "^9.3.22","kysely": "catalog:","localforage": "1.10.0",+ "motion": "catalog:","nanoid": "catalog:",+ "nodemon": "catalog:","non.geist": "catalog:",+ "npm-run-all": "catalog:","pdfjs-dist": "5.4.296","posthog-js": "catalog:","react": "catalog:",@@ -86,31 +100,17 @@"sst": "catalog:","supabase": "catalog:","tailwind-merge": "catalog:",- "tailwindcss-animate": "catalog:",- "tsup": "catalog:",- "zod": "catalog:",- "zod-form-data": "catalog:"- },- "devDependencies": {- "@tanstack/react-query-devtools": "catalog:",- "@lingui/conf": "catalog:",- "@react-aria/optimize-locales-plugin": "catalog:",- "@carbon/config": "workspace:*",- "@carbon/dev": "workspace:*",- "@types/react": "catalog:",- "@types/react-dom": "catalog:",- "cross-env": "catalog:",- "nodemon": "catalog:",- "npm-run-all": "catalog:","tailwind-scrollbar": "catalog:","tailwind-scrollbar-hide": "catalog:","tailwindcss": "catalog:",+ "tailwindcss-animate": "catalog:",+ "tsup": "catalog:","typescript": "catalog:",- "@vitejs/devtools": "catalog:",- "@vitejs/devtools-rolldown": "catalog:","vite": "catalog:","vitest": "catalog:",- "wait-on": "catalog:"+ "wait-on": "catalog:",+ "zod": "catalog:",+ "zod-form-data": "catalog:"},"private": true,"scripts": {@@ -121,7 +121,7 @@"lint": "biome lint --write ","start": "NODE_ENV=production node ./server/node.ts","test": "vitest run",- "typecheck": "react-router typegen && tsgo --noEmit",+ "typecheck": "react-router typegen && tsc --noEmit","typegen": "react-router typegen"},"sideEffects": [diff --git a/apps/starter/package.json b/apps/starter/package.jsonindex 6a43ee0a2d..77c469e364 100644--- a/apps/starter/package.json+++ b/apps/starter/package.json@@ -66,7 +66,7 @@"dev": "react-router dev","lint": "biome lint --write ","start": "react-router-serve ./build/server/index.js",- "typecheck": "react-router typegen && tsgo --noEmit",+ "typecheck": "react-router typegen && tsc --noEmit","typegen": "react-router typegen"},"sideEffects": [diff --git a/docs/content/package.json b/docs/content/package.jsonindex 475beabf28..c162f9d552 100644--- a/docs/content/package.json+++ b/docs/content/package.json@@ -15,7 +15,7 @@"lint": "biome lint --write ","test": "vitest run","test:watch": "vitest",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"dependencies": {"@lingui/core": "catalog:",diff --git a/docs/content/src/glossary/terms.test.ts b/docs/content/src/glossary/terms.test.tsindex 87a92419b7..e11ff35879 100644--- a/docs/content/src/glossary/terms.test.ts+++ b/docs/content/src/glossary/terms.test.ts@@ -30,11 +30,6 @@ describe("glossary", () => {}});- it("slugs are unique", () => {- const ids = Object.keys(terms);- expect(new Set(ids).size).toBe(ids.length);- });-it("href, if set, points at /docs, /guides, or an absolute URL — shape only", () => {const shape = /^\/(docs|guides)\/|^https?:\/\//;for (const [id, entry] of entriesById) {@@ -54,16 +49,11 @@ describe("glossary", () => {}});- it("termSlug() round-trips a normal term name", () => {+ it("termSlug lowercases, trims and hyphenates a term name", () => {expect(termSlug("Make to Order")).toBe("make-to-order");expect(termSlug(" Mixed-Case TEXT ")).toBe("mixed-case-text");});- it("getEntry is total over TermId", () => {- // `getEntry` is typed as `(id: TermId) => GlossaryEntry` — no undefined.- expect(getTermText(getEntry("method"))).toBe("Method");- });-it("hasEntry / lookupEntry resolve unknown slugs to nothing", () => {expect(hasEntry("method")).toBe(true);expect(hasEntry("not-a-real-slug")).toBe(false);diff --git a/docs/tsconfig.json b/docs/tsconfig.jsonindex 618162ffa9..edf50a2d56 100644--- a/docs/tsconfig.json+++ b/docs/tsconfig.json@@ -1,7 +1,7 @@{"extends": "@carbon/config/tsconfig/nextjs.json","compilerOptions": {- "baseUrl": ".",+ "strict": false,"paths": {"@/*": ["./*"],"collections/*": ["./.source/*"]diff --git a/package.json b/package.jsonindex afd3b4799a..54035e50bf 100755--- a/package.json+++ b/package.json@@ -2,21 +2,32 @@"name": "carbon","devDependencies": {"@biomejs/biome": "2.5.15",+ "@carbon/api": "workspace:*","@lingui/cli": "catalog:",+ "@opentelemetry/semantic-conventions": "1.40.0","@react-router/dev": "catalog:",+ "@react-router/remix-routes-option-adapter": "catalog:","@types/aws-lambda": "8.10.164","@types/node": "catalog:",- "@typescript/native-preview": "catalog:","cli-table3": "^0.6.5",+ "cookie": "catalog:","csv-parse": "5.6.0",+ "dompurify": "catalog:","execa": "^8.0.1",+ "fast-uri": "3.1.8",+ "fdir": "6.5.0","linguito": "^0.5.2","lint-staged": "16.4.0",+ "nanoid": "catalog:","npm-run-all": "catalog:",+ "react-pdf": "catalog:",+ "remix-flat-routes": "catalog:","rimraf": "catalog:","simple-git-hooks": "2.14.0",+ "sst": "catalog:","supabase": "catalog:","ts-morph": "28.0.0",+ "tsup": "catalog:","tsx": "catalog:","turbo": "2.11.7","typescript": "catalog:",@@ -91,20 +102,6 @@"engines": {"node": ">=24.22.1"},- "dependencies": {- "@carbon/api": "workspace:*",- "@opentelemetry/semantic-conventions": "1.40.0",- "@react-router/remix-routes-option-adapter": "catalog:",- "cookie": "catalog:",- "dompurify": "catalog:",- "fast-uri": "3.1.8",- "fdir": "6.5.0",- "nanoid": "catalog:",- "react-pdf": "catalog:",- "remix-flat-routes": "catalog:",- "sst": "catalog:",- "tsup": "catalog:"- },"optionalDependencies": {"@rollup/rollup-linux-x64-gnu": "4.60.1"},diff --git a/packages/account/package.json b/packages/account/package.jsonindex 768ad2805b..a57ee1ab20 100644--- a/packages/account/package.json+++ b/packages/account/package.json@@ -10,7 +10,6 @@},"dependencies": {"@carbon/auth": "workspace:*",- "@carbon/database": "workspace:*","@carbon/files": "workspace:*","@carbon/form": "workspace:*","@carbon/logger": "workspace:*",@@ -18,7 +17,6 @@"@carbon/query": "workspace:*","@carbon/react": "workspace:*","@carbon/utils": "workspace:*",- "@lingui/core": "catalog:","@lingui/react": "catalog:","@simplewebauthn/browser": "^13.3.0","react": "catalog:",@@ -30,6 +28,8 @@},"devDependencies": {"@carbon/config": "workspace:*",+ "@carbon/database": "workspace:*",+ "@lingui/core": "catalog:","@types/react": "catalog:","rimraf": "catalog:","typescript": "catalog:"@@ -37,6 +37,6 @@"scripts": {"clean": "rimraf .turbo node_modules dist","lint": "biome lint --write ",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"}}diff --git a/packages/api/package.json b/packages/api/package.jsonindex 2bd4ad24b5..6beae1d5dd 100644--- a/packages/api/package.json+++ b/packages/api/package.json@@ -19,23 +19,23 @@"clean": "rimraf .turbo node_modules dist","lint": "biome lint --write ","test": "vitest run --passWithNoTests",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"dependencies": {"@carbon/auth": "workspace:*",- "@carbon/database": "workspace:*",- "@carbon/kv": "workspace:*","@carbon/logger": "workspace:*","@carbon/utils": "workspace:*",- "@orpc/client": "catalog:",- "@orpc/contract": "catalog:",- "@orpc/openapi-client": "catalog:",- "@supabase/supabase-js": "catalog:","zod": "catalog:"},"devDependencies": {"@carbon/config": "workspace:*",+ "@carbon/database": "workspace:*",+ "@carbon/kv": "workspace:*",+ "@orpc/client": "catalog:",+ "@orpc/contract": "catalog:","@orpc/openapi": "catalog:",+ "@orpc/openapi-client": "catalog:",+ "@supabase/supabase-js": "catalog:","tsx": "catalog:","typescript": "catalog:","vitest": "catalog:"diff --git a/packages/auth/package.json b/packages/auth/package.jsonindex 3b7aad30f2..9c3e6fcabb 100644--- a/packages/auth/package.json+++ b/packages/auth/package.json@@ -5,10 +5,13 @@"@carbon/utils": "workspace:*","@simplewebauthn/types": "^12.0.0","@types/react": "catalog:",+ "dompurify": "catalog:",+ "nanoid": "catalog:","sst": "catalog:","tsup": "catalog:","typescript": "catalog:",- "vitest": "catalog:"+ "vitest": "catalog:",+ "zustand": "catalog:"},"exports": {".": "./src/index.ts",@@ -54,7 +57,7 @@"clean": "rimraf .turbo node_modules","lint": "biome lint --fix","test": "vitest run",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"sideEffects": false,"version": "0.0.0",@@ -64,13 +67,10 @@"@carbon/kv": "workspace:*","@carbon/lib": "workspace:*","@carbon/logger": "workspace:*",- "react-email": "catalog:","@simplewebauthn/server": "^13.3.2","botid": "catalog:","cookie": "catalog:",- "dompurify": "catalog:","jose": "catalog:",- "nanoid": "catalog:",- "zustand": "catalog:"+ "react-email": "catalog:"}}diff --git a/packages/auth/src/lib/oauth-state.server.test.ts b/packages/auth/src/lib/oauth-state.server.test.tsindex ed027f1972..f7fbf02af7 100644--- a/packages/auth/src/lib/oauth-state.server.test.ts+++ b/packages/auth/src/lib/oauth-state.server.test.ts@@ -2,21 +2,31 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--vi.mock("../config/env", () => ({- AUTH_COOKIE_SUFFIX: undefined,- CarbonEdition: "Community",- DOMAIN: "localhost",- SESSION_SECRET: "test-session-secret"-}));-+import {+ afterAll,+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi+} from "vitest";import {consumeOAuthState,issueOAuthState,issueOAuthStates} from "./oauth-state.server";+// The module reads its configuration once, at import.+vi.hoisted(() => {+ vi.stubEnv("DOMAIN", "localhost");+ vi.stubEnv("CARBON_EDITION", "");+ vi.stubEnv("AUTH_COOKIE_SUFFIX", "");+ vi.stubEnv("SESSION_SECRET", "test-session-secret");+});++afterAll(() => vi.unstubAllEnvs());+/** The cookie value (name=value) from a Set-Cookie header, as a browser sends it. */function cookieHeader(setCookie: string) {return setCookie.split(";")[0]!;diff --git a/packages/auth/src/lib/supabase/client.test.ts b/packages/auth/src/lib/supabase/client.test.tsindex e666477723..e331fa6b75 100644--- a/packages/auth/src/lib/supabase/client.test.ts+++ b/packages/auth/src/lib/supabase/client.test.ts@@ -2,15 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { afterEach, describe, expect, it, vi } from "vitest";--// Env is validated at import time (getEnv throws on missing required vars), so we-// stub the config module rather than requiring a full environment in the test run.-vi.mock("../../config/env", () => ({- SUPABASE_ANON_KEY: "sb_publishable_anon",- SUPABASE_INTERNAL_URL: "http://supabase.internal.test",- SUPABASE_URL: "http://supabase.test"-}));+import { afterAll, afterEach, describe, expect, it, vi } from "vitest";++// The module reads its configuration once, at import.+vi.hoisted(() => {+ vi.stubEnv("SUPABASE_ANON_KEY", "sb_publishable_anon");+ vi.stubEnv("SUPABASE_INTERNAL_URL", "http://supabase.internal.test");+ vi.stubEnv("SUPABASE_URL", "http://supabase.test");+});++afterAll(() => vi.unstubAllEnvs());const waitEnded = vi.fn();const startSpan = vi.fn((_name: string, _attributes: object) => waitEnded);diff --git a/packages/auth/src/raw.d.ts b/packages/auth/src/raw.d.tsindex 32d81aa69a..4ac9612f5f 100644--- a/packages/auth/src/raw.d.ts+++ b/packages/auth/src/raw.d.ts@@ -3,7 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.// `?raw` text imports are resolved by the consuming app's Vite build (ERP / MES).-// This package is typechecked with tsgo, which doesn't know Vite's `?raw` suffix,+// This package is typechecked with tsc, which doesn't know Vite's `?raw` suffix,// so declare the module shape here. Used by `services/self-signup.server.ts`.declare module "*?raw" {const content: string;diff --git a/packages/auth/src/services/api-key-cache.test.ts b/packages/auth/src/services/api-key-cache.test.tsindex 4b87f78442..7ffa32e883 100644--- a/packages/auth/src/services/api-key-cache.test.ts+++ b/packages/auth/src/services/api-key-cache.test.ts@@ -2,46 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { beforeEach, describe, expect, it, vi } from "vitest";--// Same simulation preamble as auth-redis-resilience.test.ts: @carbon/kv is wrapped-// in withResilience(), so reads/writes resolve `null` instead of throwing when-// Redis is unreachable.-vi.mock("@carbon/kv", () => ({- redis: {- get: vi.fn().mockResolvedValue(null),- set: vi.fn().mockResolvedValue(null),- del: vi.fn().mockResolvedValue(null),- getdel: vi.fn().mockResolvedValue(null)- }-}));--// Env is validated at import time (getEnv throws on missing required vars), so we-// stub the config module rather than requiring a full environment in the test run.-vi.mock("../config/env", () => ({- DOMAIN: "localhost",- ERP_URL: "http://localhost:3000",- MES_URL: "http://localhost:3001",- VERCEL_URL: "",- CarbonEdition: "Community",- REFRESH_ACCESS_TOKEN_THRESHOLD: 60,- SESSION_KEY: "auth",- SESSION_MAX_AGE: 60 * 60 * 24 * 7,- SESSION_SECRET: "test-session-secret"-}));--const db = vi.hoisted(() => ({ single: vi.fn() }));--vi.mock("../lib/supabase/client.server", () => {- const chain: Record<string, unknown> = {};- chain.from = vi.fn(() => chain);- chain.select = vi.fn(() => chain);- chain.eq = vi.fn(() => chain);- chain.single = db.single;- return { getCarbonServiceRole: vi.fn(() => chain) };-});--import { redis } from "@carbon/kv";+import {+ afterAll,+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi+} from "vitest";import {type ApiKeyRecord,apiKeyCacheKey,@@ -50,11 +19,32 @@ import {hashApiKey} from "./api-key.server";-const mockRedis = redis as unknown as {- get: ReturnType<typeof vi.fn>;- set: ReturnType<typeof vi.fn>;- del: ReturnType<typeof vi.fn>;-};+// The module reads its configuration once, at import.+vi.hoisted(() => {+ vi.stubEnv("SUPABASE_URL", "http://supabase.test");+ vi.stubEnv("SUPABASE_ANON_KEY", "anon-key");+ vi.stubEnv("SUPABASE_SERVICE_ROLE_KEY", "service-role-key");+});++// Redis as an in-memory map that keeps each entry's TTL. With `down` set it+// behaves as @carbon/kv's withResilience() does: every call resolves null.+const kv = vi.hoisted(() => ({+ entries: new Map<string, { value: string; ttl: number }>(),+ down: false+}));+vi.mock("@carbon/kv", () => ({+ redis: {+ get: async (key: string) =>+ kv.down ? null : (kv.entries.get(key)?.value ?? null),+ set: async (key: string, value: string, _ex: "EX", ttl: number) => {+ if (kv.down) return null;+ kv.entries.set(key, { value, ttl });+ return "OK";+ },+ del: async (key: string) =>+ kv.down ? null : Number(kv.entries.delete(key))+ }+}));const ROW: ApiKeyRecord = {id: "key1",@@ -70,68 +60,96 @@ const ROW: ApiKeyRecord = {const KEY = "crbn_test_key";const CACHE_KEY = apiKeyCacheKey(hashApiKey(KEY));+// PostgREST's answer to the apiKey lookup, and how many lookups reached it.+const db = {+ reads: 0,+ respond: (): Response => json(ROW)+};+const json = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" }+ });+beforeEach(() => {- vi.clearAllMocks();- mockRedis.get.mockResolvedValue(null);- mockRedis.set.mockResolvedValue("OK");- mockRedis.del.mockResolvedValue(1);- db.single.mockResolvedValue({ data: ROW, error: null });+ kv.entries.clear();+ kv.down = false;+ db.reads = 0;+ db.respond = () => json(ROW);+ vi.stubGlobal("fetch", async (input: RequestInfo | URL) => {+ const url = new URL(input instanceof Request ? input.url : String(input));+ if (url.pathname !== "/rest/v1/apiKey") return json({}, 404);+ db.reads++;+ return db.respond();+ });});+afterEach(() => vi.unstubAllGlobals());++afterAll(() => vi.unstubAllEnvs());+describe("getApiKeyRecord", () => {- it("cache miss: one DB read, then writes the record with a 30s TTL", async () => {- const record = await getApiKeyRecord(KEY);- expect(record).toEqual(ROW);- expect(db.single).toHaveBeenCalledTimes(1);- expect(mockRedis.set).toHaveBeenCalledWith(- CACHE_KEY,- JSON.stringify(ROW),- "EX",- 30- );+ it("reads the database on a miss and caches the record for 30 seconds", async () => {+ expect(await getApiKeyRecord(KEY)).toEqual(ROW);+ expect(db.reads).toBe(1);+ expect(kv.entries.get(CACHE_KEY)).toEqual({+ value: JSON.stringify(ROW),+ ttl: 30+ });});- it("cache hit: returns the cached record with zero DB reads", async () => {- mockRedis.get.mockResolvedValue(JSON.stringify(ROW));- const record = await getApiKeyRecord(KEY);- expect(record).toEqual(ROW);- expect(db.single).not.toHaveBeenCalled();+ it("serves a cached record without reading the database", async () => {+ kv.entries.set(CACHE_KEY, { value: JSON.stringify(ROW), ttl: 30 });++ expect(await getApiKeyRecord(KEY)).toEqual(ROW);+ expect(db.reads).toBe(0);});- it("unknown key: returns null, caches the negative, and serves it without the DB", async () => {- db.single.mockResolvedValue({- data: null,- error: { code: "PGRST116", message: "no rows" }- });+ it("caches an unknown key as a negative and serves it without the database", async () => {+ db.respond = () =>+ json(+ { code: "PGRST116", message: "no rows", details: null, hint: null },+ 406+ );+expect(await getApiKeyRecord(KEY)).toBeNull();- expect(db.single).toHaveBeenCalledTimes(1);- expect(mockRedis.set).toHaveBeenCalledWith(CACHE_KEY, "null", "EX", 30);+ expect(kv.entries.get(CACHE_KEY)).toEqual({ value: "null", ttl: 30 });- mockRedis.get.mockResolvedValue("null");expect(await getApiKeyRecord(KEY)).toBeNull();- expect(db.single).toHaveBeenCalledTimes(1);+ expect(db.reads).toBe(1);});- it("lookup failure: does not cache the null, so a blip cannot 401 a valid key", async () => {- db.single.mockResolvedValue({- data: null,- error: { code: "57P01", message: "terminating connection" }- });+ // A blip must not reject a valid key for the whole TTL.+ it("does not cache the null from a failed lookup", async () => {+ db.respond = () =>+ json(+ {+ code: "57P01",+ message: "terminating connection",+ details: null,+ hint: null+ },+ 500+ );+expect(await getApiKeyRecord(KEY)).toBeNull();- expect(mockRedis.set).not.toHaveBeenCalled();+ expect(kv.entries.size).toBe(0);});- it("Redis down (reads and writes resolve null): falls through to the DB without throwing", async () => {- mockRedis.get.mockResolvedValue(null);- mockRedis.set.mockResolvedValue(null);+ it("falls through to the database when Redis is down", async () => {+ kv.down = true;+await expect(getApiKeyRecord(KEY)).resolves.toEqual(ROW);- expect(db.single).toHaveBeenCalledTimes(1);+ expect(db.reads).toBe(1);});});describe("bustApiKeyCache", () => {it("deletes the cache entry for the key hash", async () => {+ kv.entries.set(apiKeyCacheKey("abc"), { value: "null", ttl: 30 });+await bustApiKeyCache("abc");- expect(mockRedis.del).toHaveBeenCalledWith("apikey:auth:abc");++ expect(kv.entries.has(apiKeyCacheKey("abc"))).toBe(false);});});diff --git a/packages/auth/src/services/auth-redis-resilience.test.ts b/packages/auth/src/services/auth-redis-resilience.test.tsindex 833bb62ca5..ea18a4916d 100644--- a/packages/auth/src/services/auth-redis-resilience.test.ts+++ b/packages/auth/src/services/auth-redis-resilience.test.ts@@ -2,143 +2,101 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { beforeEach, describe, expect, it, vi } from "vitest";--// ── Redis-down simulation ─────────────────────────────────────────────────-// PR #1083 wraps the @carbon/kv client in withResilience(): reads/writes resolve-// `null` instead of throwing when Redis is unreachable. These tests prove the-// auth path stays safe under that condition — every hardened function either-// falls through to a safe path or fails closed, and none throw / reject.-vi.mock("@carbon/kv", () => ({- redis: {- get: vi.fn().mockResolvedValue(null),- set: vi.fn().mockResolvedValue(null),- del: vi.fn().mockResolvedValue(null),- getdel: vi.fn().mockResolvedValue(null)- }-}));--// Env is validated at import time (getEnv throws on missing required vars), so we-// stub the config module rather than requiring a full environment in the test run.-vi.mock("../config/env", () => ({- AUTH_COOKIE_SUFFIX: undefined,- DOMAIN: "localhost",- ERP_URL: "http://localhost:3000",- MES_URL: "http://localhost:3001",- VERCEL_URL: "",- CarbonEdition: "Community",- REFRESH_ACCESS_TOKEN_THRESHOLD: 60,- SESSION_KEY: "auth",- SESSION_MAX_AGE: 60 * 60 * 24 * 7,- SESSION_SECRET: "test-session-secret"-}));--// Heavy / side-effectful dependencies of the modules under test.-vi.mock("@carbon/lib/email.server", () => ({- sendEmail: vi.fn().mockResolvedValue({ error: null })-}));-vi.mock("@carbon/documents/email", () => ({- VerificationEmail: vi.fn(() => null)-}));-vi.mock("react-email", () => ({- render: vi.fn().mockResolvedValue("<html>code</html>")-}));-vi.mock("@simplewebauthn/server", () => ({- generateAuthenticationOptions: vi.fn(),- generateRegistrationOptions: vi.fn(),- verifyAuthenticationResponse: vi.fn(),- verifyRegistrationResponse: vi.fn()-}));-vi.mock("../lib/supabase/client.server", () => ({- getCarbonServiceRole: vi.fn(() => ({}))-}));-// ./users backs both users.server (getClaims/makePermissionsFromClaims) and-// session.server (getPermissionCacheKey). getClaims returns a healthy DB result so-// getUserClaims can prove the Redis-miss → DB fallback path.-vi.mock("./users", () => ({- getClaims: vi.fn().mockResolvedValue({ data: [{}], error: null }),- getPermissionCacheKey: (userId: string) => `permissions:${userId}`,- makePermissionsFromClaims: vi.fn(() => ({- permissions: { parts: { view: [], create: [], update: [], delete: [] } },- role: "employee"- }))-}));-// session.server imports these siblings; they pull in supabase/env so we stub them.-vi.mock("./auth.server", () => ({- makeAuthSession: vi.fn(),- refreshAccessToken: vi.fn(),- verifyAuthSession: vi.fn()-}));-vi.mock("./company.server", () => ({- setCompanyId: vi.fn(() => "companyId=cookie")-}));-vi.mock("./mfa.server", () => ({- getTotpFactors: vi.fn().mockResolvedValue([]),- userHasVerifiedTotpFactor: vi.fn().mockResolvedValue(false),- verifyTotpChallenge: vi.fn().mockResolvedValue(null)-}));--import { redis } from "@carbon/kv";-import { sendEmail } from "@carbon/lib/email.server";+import {+ afterAll,+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi+} from "vitest";import type { AuthSession } from "../types";import {- getAndDeleteAuthChallenge,- getAndDeleteRegistrationChallenge-} from "./passkey.server";-import { setAuthSession, updateCompanySession } from "./session.server";+ getAuthSession,+ setAuthSession,+ updateCompanySession+} from "./session.server";import { getUserClaims } from "./users.server";import { sendVerificationCode, verifyEmailCode } from "./verification.server";+// The module reads its configuration once, at import.+vi.hoisted(() => {+ vi.stubEnv("DOMAIN", "localhost");+ vi.stubEnv("CARBON_EDITION", "");+ vi.stubEnv("AUTH_COOKIE_SUFFIX", "");+ vi.stubEnv("CONTROLLED_ENVIRONMENT", "");+ vi.stubEnv("SESSION_SECRET", "test-session-secret");+ vi.stubEnv("SUPABASE_URL", "http://supabase.test");+ vi.stubEnv("SUPABASE_ANON_KEY", "anon-key");+ vi.stubEnv("SUPABASE_SERVICE_ROLE_KEY", "service-role-key");+});++// Redis is down: @carbon/kv's withResilience() resolves every call to null+// instead of throwing.+const redisDown = vi.hoisted(() => ({+ get: async () => null,+ set: async (): Promise<string | null> => null,+ del: async () => null+}));+vi.mock("@carbon/kv", () => ({ redis: redisDown }));++// Outbound mail is a network boundary.+const sendEmail = vi.hoisted(() => vi.fn());+vi.mock("@carbon/lib/email.server", () => ({ sendEmail }));++// The database answers get_claims for a plain employee.+const fakeDatabase = async (input: RequestInfo | URL) => {+ const url = new URL(input instanceof Request ? input.url : String(input));+ if (url.pathname !== "/rest/v1/rpc/get_claims") {+ return new Response("{}", { status: 404 });+ }+ return new Response(+ JSON.stringify({ role: "employee", parts_view: ["company-1"] }),+ { headers: { "Content-Type": "application/json" } }+ );+};+beforeEach(() => {- // clearAllMocks resets call history but keeps the "Redis down" (→ null)- // implementations declared in the vi.mock factory above.- vi.clearAllMocks();+ sendEmail.mockReset();+ vi.stubGlobal("fetch", fakeDatabase);});-describe("auth Redis-down resilience", () => {- it("[case 1] getUserClaims falls through to the DB when redis.get is null", async () => {- const claims = await getUserClaims("user-1", "company-1");+afterEach(() => vi.unstubAllGlobals());- // Cache miss (Redis down) → DB lookup → correct claims, no throw.- expect(redis.get).toHaveBeenCalledWith("permissions:user-1");- expect(claims).toMatchObject({ role: "employee" });- // Best-effort cache write was attempted but its null return didn't abort.- expect(redis.set).toHaveBeenCalled();- });+afterAll(() => vi.unstubAllEnvs());- it("[case 2] sendVerificationCode returns false without throwing when redis.set fails", async () => {- // A genuine Redis failure that escapes fail-soft (e.g. a throw) is caught and- // reported as an unsendable code rather than crashing the request.- vi.mocked(redis.set).mockRejectedValueOnce(new Error("redis down"));+// Every auth path that touches Redis either falls through to a safe path or+// fails closed when Redis is down; none throws.+describe("auth with Redis down", () => {+ it("reads claims from the database when the permission cache is unreachable", async () => {+ await expect(getUserClaims("user-1", "company-1")).resolves.toEqual({+ role: "employee",+ permissions: {+ parts: { view: ["company-1"], create: [], update: [], delete: [] }+ }+ });+ });+ it("does not send a verification email it could not store the code for", async () => {await expect(sendVerificationCode("[email protected]")).resolves.toBe(false);+ expect(sendEmail).not.toHaveBeenCalled();});- it("[case 2b] sendVerificationCode fails closed (returns false, no email) when redis.set resolves null", async () => {- // Under withResilience, a Redis-down `set` resolves null (not a throw). The code- // must NOT send an unverifiable email in that case — it returns false without- // ever calling sendEmail.+ it("reports a verification code as unsendable when the store throws", async () => {+ vi.spyOn(redisDown, "set").mockRejectedValueOnce(new Error("redis down"));+await expect(sendVerificationCode("[email protected]")).resolves.toBe(false);expect(sendEmail).not.toHaveBeenCalled();});- it("[case 3] verifyEmailCode returns false (fail-closed) when redis.get is null", async () => {+ it("refuses a verification code it cannot look up", async () => {await expect(verifyEmailCode("[email protected]", "123456")).resolves.toBe(false);});- it("[case 4] getAndDeleteRegistrationChallenge returns null when redis.getdel is null", async () => {- await expect(- getAndDeleteRegistrationChallenge("user-1")- ).resolves.toBeNull();- });-- it("[case 5] getAndDeleteAuthChallenge returns null when redis.getdel is null", async () => {- await expect(getAndDeleteAuthChallenge("challenge-1")).resolves.toBeNull();- });-- it("[case 6] updateCompanySession still returns a session cookie when redis.del is null", async () => {+ it("still switches the session's company when the cache bust fails", async () => {const authSession: AuthSession = {accessToken: "access",refreshToken: "refresh",@@ -149,25 +107,24 @@ describe("auth Redis-down resilience", () => {expiresIn: 3600,expiresAt: 9_999_999_999};+ const cookieOf = (setCookie: string) =>+ new Request("http://localhost/", {+ headers: { Cookie: setCookie.split(";")[0] ?? "" }+ });- // Mint a real signed cookie via the module's own storage, then feed it back.- const setCookie = await setAuthSession(new Request("http://localhost/"), {+ const signedIn = await setAuthSession(new Request("http://localhost/"), {authSession});- const cookiePair = setCookie.split(";")[0] ?? "";- const request = new Request("http://localhost/", {- headers: { Cookie: cookiePair }- });-- const cookie = await updateCompanySession(- request,+ const switched = await updateCompanySession(+ cookieOf(signedIn),"new-company","new-group");- // Cache invalidation was attempted (fire-and-forget) and the null return was benign.- expect(redis.del).toHaveBeenCalledWith("permissions:user-1");- expect(typeof cookie).toBe("string");- expect(cookie.length).toBeGreaterThan(0);+ expect(await getAuthSession(cookieOf(switched))).toEqual({+ ...authSession,+ companyId: "new-company",+ companyGroupId: "new-group"+ });});});diff --git a/packages/auth/src/services/auth.server.ts b/packages/auth/src/services/auth.server.tsindex 4afa02fe55..772076afb6 100644--- a/packages/auth/src/services/auth.server.ts+++ b/packages/auth/src/services/auth.server.ts@@ -25,8 +25,11 @@ import {SUPABASE_ANON_KEY,VERCEL_URL} from "../config/env";-import { getCarbon } from "../lib/supabase";-import { getCarbonAPIKeyClient, getCarbonClient } from "../lib/supabase/client";+import {+ getCarbon,+ getCarbonAPIKeyClient,+ getCarbonClient+} from "../lib/supabase/client";import {getCarbonServiceRole,requestFetchdiff --git a/packages/auth/src/services/bot-protection.test.ts b/packages/auth/src/services/bot-protection.test.tsindex dc45622476..2b19255a21 100644--- a/packages/auth/src/services/bot-protection.test.ts+++ b/packages/auth/src/services/bot-protection.test.ts@@ -17,7 +17,6 @@ vi.mock("../config/env", () => env);const checkBotId = vi.hoisted(() => vi.fn());vi.mock("botid/server", () => ({ checkBotId }));-vi.mock("./auth-events.server", () => ({ logAuthEvent: vi.fn() }));async function load(overrides: Partial<typeof env>) {Object.assign(env, {diff --git a/packages/auth/src/services/company-plan-cache.test.ts b/packages/auth/src/services/company-plan-cache.test.tsindex 323b480ac8..ed409646b1 100644--- a/packages/auth/src/services/company-plan-cache.test.ts+++ b/packages/auth/src/services/company-plan-cache.test.ts@@ -2,17 +2,17 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { describe, expect, it, vi } from "vitest";+import { afterAll, describe, expect, it, vi } from "vitest";-// Import-safety only: the module reads env and builds clients at import time.-vi.mock("@carbon/auth", () => ({- CarbonEdition: "cloud",- DOMAIN: "localhost"-}));+// Import-safety only: the module builds a Supabase client and a Redis+// connection at import.+vi.hoisted(() => {+ vi.stubEnv("SUPABASE_URL", "http://supabase.test");+ vi.stubEnv("SUPABASE_ANON_KEY", "anon-key");+});vi.mock("@carbon/kv", () => ({ redis: {} }));-vi.mock("../lib/supabase/client.server", () => ({- getCarbonServiceRole: vi.fn()-}));++afterAll(() => vi.unstubAllEnvs());import { planIdFromCache } from "./company.server";diff --git a/packages/auth/src/services/company.server.ts b/packages/auth/src/services/company.server.tsindex d1f18738ea..0d002b4578 100644--- a/packages/auth/src/services/company.server.ts+++ b/packages/auth/src/services/company.server.ts@@ -2,12 +2,12 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { CarbonEdition, DOMAIN } from "@carbon/auth";import { redis } from "@carbon/kv";import { getLogger } from "@carbon/logger";import { oncePerRead } from "@carbon/logger/middleware.server";import { companyPlanCacheKey, Edition, isInternalEmail } from "@carbon/utils";import * as cookie from "cookie";+import { CarbonEdition, DOMAIN } from "../config/env";import { getCarbonServiceRole } from "../lib/supabase/client.server";import { authCookieName, getCookieDomain } from "../utils/cookie";diff --git a/packages/auth/src/services/console-pin.server.test.ts b/packages/auth/src/services/console-pin.server.test.tsindex b9fd03dcd6..a2fe1a1d8b 100644--- a/packages/auth/src/services/console-pin.server.test.ts+++ b/packages/auth/src/services/console-pin.server.test.ts@@ -2,27 +2,34 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--vi.mock("../config/env", () => ({- CarbonEdition: "Community",- CONTROLLED_ENVIRONMENT: false,- DOMAIN: "localhost",- SESSION_IDLE_LOCK_MS: 15 * 60 * 1000,- SESSION_SECRET: "test-session-secret"-}));--// Import-safety only: these tests exercise the cookie (real react-router-// signing); the database re-validation in `resolveConsolePinIn` is not faked.-vi.mock("../lib/supabase/client.server", () => ({- getCarbonServiceRole: vi.fn()-}));-+import {+ afterAll,+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi+} from "vitest";import {readConsolePinInCookieUnverified,setConsolePinIn} from "./console-pin.server";+// The module reads its configuration once, at import, and builds a Supabase+// client there.+vi.hoisted(() => {+ vi.stubEnv("DOMAIN", "localhost");+ vi.stubEnv("CARBON_EDITION", "");+ vi.stubEnv("AUTH_COOKIE_SUFFIX", "");+ vi.stubEnv("CONTROLLED_ENVIRONMENT", "");+ vi.stubEnv("SESSION_SECRET", "test-session-secret");+ vi.stubEnv("SUPABASE_URL", "http://supabase.test");+ vi.stubEnv("SUPABASE_ANON_KEY", "anon-key");+});++afterAll(() => vi.unstubAllEnvs());+const companyId = "company-1";const terminal = "terminal-user";const operator = {diff --git a/packages/auth/src/services/deactivate-employee.test.ts b/packages/auth/src/services/deactivate-employee.test.tsindex d5cb8cff2b..507686795f 100644--- a/packages/auth/src/services/deactivate-employee.test.ts+++ b/packages/auth/src/services/deactivate-employee.test.ts@@ -2,49 +2,30 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";+import { deactivateEmployee } from "./users.server";-// Same simulation preamble as the sibling auth tests: @carbon/kv is wrapped in-// withResilience(), and env is validated at import time, so both are stubbed-// rather than requiring Redis and a full environment in the test run.-const { redisDel } = vi.hoisted(() => ({- redisDel: vi.fn().mockResolvedValue(null)-}));+// Import-safety: the module builds a Supabase client at import.+vi.hoisted(() => {+ vi.stubEnv("SUPABASE_URL", "http://supabase.test");+ vi.stubEnv("SUPABASE_ANON_KEY", "anon-key");+});+afterAll(() => vi.unstubAllEnvs());++// Redis as an in-memory map.+const kv = vi.hoisted(() => new Map<string, string>());vi.mock("@carbon/kv", () => ({redis: {- get: vi.fn().mockResolvedValue(null),- set: vi.fn().mockResolvedValue(null),- del: redisDel,- getdel: vi.fn().mockResolvedValue(null)+ get: async (key: string) => kv.get(key) ?? null,+ set: async (key: string, value: string) => {+ kv.set(key, value);+ return "OK";+ },+ del: async (key: string) => Number(kv.delete(key))}}));-vi.mock("../config/env", () => ({- RESEND_DOMAIN: "test.dev",- DOMAIN: "localhost",- ERP_URL: "http://localhost:3000",- MES_URL: "http://localhost:3001",- VERCEL_URL: "",- CarbonEdition: "Community",- REFRESH_ACCESS_TOKEN_THRESHOLD: 60,- SESSION_KEY: "auth",- SESSION_MAX_AGE: 60 * 60 * 24 * 7,- SESSION_SECRET: "test-session-secret",- SUPABASE_URL: "http://localhost:54321",- SUPABASE_INTERNAL_URL: "http://localhost:54321",- SUPABASE_ANON_KEY: "test-anon-key",- SUPABASE_SERVICE_ROLE_KEY: "test-service-role-key",- SUPABASE_JWT_SECRET: "test-jwt-secret"-}));--vi.mock("./auth-events.server", () => ({- logRoleChange: vi.fn(),- logPermissionChange: vi.fn()-}));--import { deactivateEmployee } from "./users.server";-const USER = "usr_1";const COMPANY = "cmp_1";const OTHER_COMPANY = "cmp_2";@@ -88,7 +69,7 @@ function makeClient(reads: Record<string, unknown>) {beforeEach(() => {ops = [];- redisDel.mockClear();+ kv.clear();});describe("deactivateEmployee", () => {@@ -104,8 +85,7 @@ describe("deactivateEmployee", () => {it("keeps the employeeJob row so org placement survives", async () => {await deactivateEmployee(client(), USER, COMPANY);- // Regression guard: deleting employeeJob here made deactivation lossy —- // title, start date, department, shift, manager, location, tags and custom+ // Deleting employeeJob made deactivation lossy: title, start date, department, shift, manager, location, tags and custom// fields cannot be reconstructed when the person is re-invited.expect(ops.filter((o) => o.table === "employeeJob")).toEqual([]);});@@ -130,12 +110,14 @@ describe("deactivateEmployee", () => {});it("invalidates the cached claims itself, for callers that skip deactivateUser", async () => {+ kv.set(`permissions:${USER}`, "{}");+await deactivateEmployee(client(), USER, COMPANY);// requirePermissions reads this cache (1h TTL) before the database, and the// create*Account rollbacks call this function directly rather than through// deactivateUser — so the invalidation has to live here.- expect(redisDel).toHaveBeenCalledWith(`permissions:${USER}`);+ expect(kv.has(`permissions:${USER}`)).toBe(false);});it("strips only the deactivating company from the permission map", async () => {diff --git a/packages/auth/src/services/mfa-session.test.ts b/packages/auth/src/services/mfa-session.test.tsindex a77540022b..f00a3991de 100644--- a/packages/auth/src/services/mfa-session.test.ts+++ b/packages/auth/src/services/mfa-session.test.ts@@ -2,80 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--// ── Isolation mocks ───────────────────────────────────────────────────────-// session.server's siblings pull in supabase/env at module load; stub them so-// the cookie/session logic under test runs against the real react-router-// session storage only.-vi.mock("@carbon/kv", () => ({- redis: {- get: vi.fn().mockResolvedValue(null),- set: vi.fn().mockResolvedValue(null),- del: vi.fn().mockResolvedValue(null)- }-}));--vi.mock("../config/env", () => ({- AUTH_COOKIE_SUFFIX: undefined,- DOMAIN: "localhost",- CarbonEdition: "Community",- CONTROLLED_ENVIRONMENT: false,- REFRESH_ACCESS_TOKEN_THRESHOLD: 60,- SESSION_ABSOLUTE_MAX_MS: 12 * 60 * 60 * 1000,- SESSION_IDLE_LOCK_MS: 15 * 60 * 1000,- SESSION_KEY: "auth",- SESSION_MAX_AGE: 60 * 60 * 24 * 7,- SESSION_SECRET: "test-session-secret"-}));--vi.mock("./auth.server", () => ({- makeAuthSession: vi.fn(- (- supabaseSession: any,- companyId: string,- companyGroupId: string,- options?: { mfaVerified?: boolean }- ) =>- supabaseSession- ? {- accessToken: supabaseSession.access_token,- refreshToken: supabaseSession.refresh_token,- userId: supabaseSession.user.id,- email: supabaseSession.user.email,- companyId,- companyGroupId,- expiresIn: 3000,- expiresAt: supabaseSession.expires_at,- ...(options?.mfaVerified ? { mfaVerified: true } : {})- }- : null- ),- refreshAccessToken: vi.fn(),- verifyAuthSession: vi.fn().mockResolvedValue(true),- logAuthEvent: vi.fn()-}));--vi.mock("./company.server", () => ({- setCompanyId: vi.fn(() => "companyId=cookie")-}));--vi.mock("./mfa.server", () => ({- getTotpFactors: vi.fn().mockResolvedValue([]),- userHasVerifiedTotpFactor: vi.fn().mockResolvedValue(false),- verifyTotpChallenge: vi.fn().mockResolvedValue(null)-}));--vi.mock("./users", () => ({- getPermissionCacheKey: (userId: string) => `permissions:${userId}`-}));--import type { AuthSession } from "../types";import {- getTotpFactors,- userHasVerifiedTotpFactor,- verifyTotpChallenge-} from "./mfa.server";+ afterAll,+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi+} from "vitest";+import type { AuthSession } from "../types";import {completeMfaChallenge,getPendingMfaSession,@@ -84,12 +20,112 @@ import {setPendingMfaSession} from "./session.server";+// The module reads its configuration once, at import.+vi.hoisted(() => {+ vi.stubEnv("DOMAIN", "localhost");+ vi.stubEnv("CARBON_EDITION", "");+ vi.stubEnv("AUTH_COOKIE_SUFFIX", "");+ vi.stubEnv("CONTROLLED_ENVIRONMENT", "");+ vi.stubEnv("SESSION_SECRET", "test-session-secret");+ vi.stubEnv("SUPABASE_URL", "http://supabase.test");+ vi.stubEnv("SUPABASE_ANON_KEY", "anon-key");+ vi.stubEnv("SUPABASE_SERVICE_ROLE_KEY", "service-role-key");+});++// Redis as an in-memory map.+const kv = vi.hoisted(() => new Map<string, string>());+vi.mock("@carbon/kv", () => ({+ redis: {+ get: async (key: string) => kv.get(key) ?? null,+ set: async (key: string, value: string) => {+ kv.set(key, value);+ return "OK";+ },+ del: async (key: string) => Number(kv.delete(key))+ }+}));++// GoTrue takes only a UUID as a user id.+const USER_ID = "8f7c1e5a-3b2d-4c6e-9a1f-0d2e4b6c8a10";+const VALID_CODE = "123456";const FUTURE_EXPIRES_AT = 4102444800; // far enough that isExpiringSoon is false+// An access token GoTrue's client can decode; without `exp` it counts as+// expired, so seeding a client with it refreshes first.+const b64 = (value: object) =>+ Buffer.from(JSON.stringify(value)).toString("base64url");+const ACCESS_TOKEN = `${b64({ alg: "HS256", typ: "JWT" })}.${b64({ sub: USER_ID })}.${b64({ signature: true })}`;++const user = { id: USER_ID, email: "[email protected]" };++// GoTrue, answered over a stubbed fetch. `factors` is the user's enrolled+// factors; a challenge accepts only VALID_CODE and then issues AAL2 tokens.+const gotrue = {+ factors: [] as { id: string; factor_type: string; status: string }[],+ paths: [] as string[]+};+const verifiedTotp = [+ { id: "factor_1", factor_type: "totp", status: "verified" }+];++const fakeGoTrue = async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = new URL(input instanceof Request ? input.url : String(input));+ gotrue.paths.push(url.pathname);+ const json = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" }+ });+ const session = (access_token: string, refresh_token: string) => ({+ access_token,+ refresh_token,+ token_type: "bearer",+ expires_in: 3600,+ expires_at: FUTURE_EXPIRES_AT,+ user+ });+ switch (url.pathname) {+ case "/auth/v1/token":+ return json(session("aal1-access", "aal1-refresh"));+ case "/auth/v1/user":+ return json(user);+ case `/auth/v1/admin/users/${USER_ID}/factors`:+ return json(gotrue.factors);+ case "/auth/v1/factors/factor_1/challenge":+ return json({+ id: "challenge_1",+ type: "totp",+ expires_at: FUTURE_EXPIRES_AT+ });+ case "/auth/v1/factors/factor_1/verify": {+ const { code } = JSON.parse(String(init?.body));+ return code === VALID_CODE+ ? json(session("aal2-access", "aal2-refresh"))+ : json(+ { code: "mfa_verification_failed", msg: "Invalid TOTP code" },+ 422+ );+ }+ default:+ return json({}, 404);+ }+};++beforeEach(() => {+ kv.clear();+ gotrue.factors = [];+ gotrue.paths = [];+ vi.stubGlobal("fetch", fakeGoTrue);+});++afterEach(() => vi.unstubAllGlobals());++afterAll(() => vi.unstubAllEnvs());+const makeSession = (overrides: Partial<AuthSession> = {}): AuthSession => ({- accessToken: "access-token",+ accessToken: ACCESS_TOKEN,refreshToken: "refresh-token",- userId: "user_1",+ userId: USER_ID,companyId: "company_1",companyGroupId: "group_1",email: "[email protected]",@@ -109,7 +145,6 @@ describe("pending MFA session", () => {afterEach(() => {vi.useRealTimers();- vi.clearAllMocks();});it("round-trips the parked session and redirectTo", async () => {@@ -122,8 +157,8 @@ describe("pending MFA session", () => {const pending = await getPendingMfaSession(requestWithCookie(cookie));expect(pending?.authSession).toMatchObject({- accessToken: "access-token",- userId: "user_1"+ accessToken: ACCESS_TOKEN,+ userId: USER_ID});expect(pending?.redirectTo).toBe("/x/parts");});@@ -156,35 +191,17 @@ describe("pending MFA session", () => {});describe("completeMfaChallenge", () => {- afterEach(() => {- vi.clearAllMocks();- });-it("fails with no-session when nothing is parked or issued", async () => {const result = await completeMfaChallenge(new Request("http://localhost:3000/mfa", { method: "POST" }),- "123456"+ VALID_CODE);expect(result).toEqual({ success: false, reason: "no-session" });});it("mints an mfaVerified session from a pending challenge", async () => {- vi.mocked(getTotpFactors).mockResolvedValue([- {- id: "factor_1",- friendlyName: "Authenticator app",- status: "verified",- createdAt: "2026-08-01T00:00:00Z"- }- ]);- vi.mocked(verifyTotpChallenge).mockResolvedValue({- access_token: "aal2-access",- refresh_token: "aal2-refresh",- expires_at: FUTURE_EXPIRES_AT,- user: { id: "user_1", email: "[email protected]" }- } as any);-+ gotrue.factors = verifiedTotp;const pendingCookie = await setPendingMfaSession(new Request("http://localhost:3000/callback"),{ authSession: makeSession(), redirectTo: "/x/parts" }@@ -192,13 +209,16 @@ describe("completeMfaChallenge", () => {const result = await completeMfaChallenge(requestWithCookie(pendingCookie),- "123456"+ VALID_CODE);expect(result.success).toBe(true);if (result.success) {- expect(result.authSession.accessToken).toBe("aal2-access");- expect(result.authSession.mfaVerified).toBe(true);+ expect(result.authSession).toMatchObject({+ accessToken: "aal2-access",+ refreshToken: "aal2-refresh",+ mfaVerified: true+ });expect(result.redirectTo).toBe("/x/parts");// The cookie it returns holds the full session and no pending state.expect(@@ -207,22 +227,8 @@ describe("completeMfaChallenge", () => {}});- it("falls back to the issued session when bounced by the re-check", async () => {- vi.mocked(getTotpFactors).mockResolvedValue([- {- id: "factor_1",- friendlyName: null,- status: "verified",- createdAt: "2026-08-01T00:00:00Z"- }- ]);- vi.mocked(verifyTotpChallenge).mockResolvedValue({- access_token: "aal2-access",- refresh_token: "aal2-refresh",- expires_at: FUTURE_EXPIRES_AT,- user: { id: "user_1", email: "[email protected]" }- } as any);-+ it("falls back to the issued session when bounced by the re-check, keeping console mode", async () => {+ gotrue.factors = verifiedTotp;const staleCookie = await setAuthSession(new Request("http://localhost:3000/x"),{ authSession: makeSession({ console: "company_1" }) }@@ -230,28 +236,21 @@ describe("completeMfaChallenge", () => {const result = await completeMfaChallenge(requestWithCookie(staleCookie),- "123456"+ VALID_CODE);expect(result.success).toBe(true);if (result.success) {- expect(result.authSession.mfaVerified).toBe(true);- // Console mode survives the token rotation.- expect(result.authSession.console).toBe("company_1");+ expect(result.authSession).toMatchObject({+ accessToken: "aal2-access",+ mfaVerified: true,+ console: "company_1"+ });}});it("rejects a wrong code", async () => {- vi.mocked(getTotpFactors).mockResolvedValue([- {- id: "factor_1",- friendlyName: null,- status: "verified",- createdAt: "2026-08-01T00:00:00Z"- }- ]);- vi.mocked(verifyTotpChallenge).mockResolvedValue(null);-+ gotrue.factors = verifiedTotp;const pendingCookie = await setPendingMfaSession(new Request("http://localhost:3000/callback"),{ authSession: makeSession() }@@ -264,53 +263,59 @@ describe("completeMfaChallenge", () => {expect(result).toEqual({ success: false, reason: "invalid-code" });});++ it("ignores an unverified factor", async () => {+ gotrue.factors = [+ { id: "factor_1", factor_type: "totp", status: "unverified" }+ ];+ const pendingCookie = await setPendingMfaSession(+ new Request("http://localhost:3000/callback"),+ { authSession: makeSession() }+ );++ const result = await completeMfaChallenge(+ requestWithCookie(pendingCookie),+ VALID_CODE+ );++ expect(result).toEqual({ success: false, reason: "invalid-code" });+ });});describe("requireAuthSession MFA re-check", () => {- afterEach(() => {- vi.clearAllMocks();- });+ const signedIn = (overrides: Partial<AuthSession> = {}) =>+ setAuthSession(new Request("http://localhost:3000/x"), {+ authSession: makeSession(overrides)+ });it("bounces an unverified session when the user has a factor", async () => {- vi.mocked(userHasVerifiedTotpFactor).mockResolvedValue(true);+ gotrue.factors = verifiedTotp;+ const cookie = await signedIn();- const cookie = await setAuthSession(- new Request("http://localhost:3000/x"),- { authSession: makeSession() }+ const thrown = await requireAuthSession(requestWithCookie(cookie)).catch(+ (response: Response) => response);- await expect(- requireAuthSession(requestWithCookie(cookie))- ).rejects.toSatisfy((response: any) => {- expect(response).toBeInstanceOf(Response);- expect(response.status).toBe(302);- expect(response.headers.get("Location")).toContain("/mfa");- return true;- });+ expect(thrown).toBeInstanceOf(Response);+ expect((thrown as Response).status).toBe(302);+ expect((thrown as Response).headers.get("Location")).toMatch(/^\/mfa\?/);});it("passes an mfaVerified session without a factor lookup", async () => {- const cookie = await setAuthSession(- new Request("http://localhost:3000/x"),- { authSession: makeSession({ mfaVerified: true }) }- );+ gotrue.factors = verifiedTotp;+ const cookie = await signedIn({ mfaVerified: true });const session = await requireAuthSession(requestWithCookie(cookie));- expect(session.userId).toBe("user_1");- expect(userHasVerifiedTotpFactor).not.toHaveBeenCalled();+ expect(session.userId).toBe(USER_ID);+ expect(gotrue.paths).toEqual([]);});it("passes an unverified session when the user has no factor", async () => {- vi.mocked(userHasVerifiedTotpFactor).mockResolvedValue(false);-- const cookie = await setAuthSession(- new Request("http://localhost:3000/x"),- { authSession: makeSession() }- );+ const cookie = await signedIn();const session = await requireAuthSession(requestWithCookie(cookie));- expect(session.userId).toBe("user_1");+ expect(session.userId).toBe(USER_ID);});});diff --git a/packages/auth/src/services/mfa.server.ts b/packages/auth/src/services/mfa.server.tsindex 424bd09bb8..968324adcd 100644--- a/packages/auth/src/services/mfa.server.ts+++ b/packages/auth/src/services/mfa.server.ts@@ -7,7 +7,7 @@ import { redis } from "@carbon/kv";import { getLogger } from "@carbon/logger";import { oncePerRead } from "@carbon/logger/middleware.server";import type { AuthSession as SupabaseAuthSession } from "@supabase/supabase-js";-import { getCarbon } from "../lib/supabase";+import { getCarbon } from "../lib/supabase/client";import { getCarbonServiceRole } from "../lib/supabase/client.server";const log = getLogger("auth");diff --git a/packages/auth/src/services/session-timeout.test.ts b/packages/auth/src/services/session-timeout.test.tsindex f4d24ba444..356a57f2d2 100644--- a/packages/auth/src/services/session-timeout.test.ts+++ b/packages/auth/src/services/session-timeout.test.ts@@ -2,76 +2,102 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ afterAll,+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi+} from "vitest";+import type { AuthSession } from "../types";+import {+ flash,+ getSessionFlash,+ isSessionExpiredAbsolute,+ isSessionIdleLocked,+ refreshAuthSession,+ requireAuthSession,+ setAuthSession+} from "./session.server";++// The module reads its configuration once, at import.+vi.hoisted(() => {+ vi.stubEnv("DOMAIN", "localhost");+ vi.stubEnv("CARBON_EDITION", "");+ vi.stubEnv("AUTH_COOKIE_SUFFIX", "");+ vi.stubEnv("CONTROLLED_ENVIRONMENT", "");+ vi.stubEnv("SESSION_SECRET", "test-session-secret");+ vi.stubEnv("SUPABASE_URL", "http://supabase.test");+ vi.stubEnv("SUPABASE_ANON_KEY", "anon-key");+ vi.stubEnv("SUPABASE_SERVICE_ROLE_KEY", "service-role-key");+});-// Isolation mocks — session.server's siblings pull in supabase/env at module-// load; stub them so the cookie/predicate logic under test runs against the-// real react-router session storage only. (Mirrors mfa-session.test.ts.)+// Redis as an in-memory map.+const kv = vi.hoisted(() => new Map<string, string>());vi.mock("@carbon/kv", () => ({redis: {- get: vi.fn().mockResolvedValue(null),- set: vi.fn().mockResolvedValue(null),- del: vi.fn().mockResolvedValue(null)+ get: async (key: string) => kv.get(key) ?? null,+ set: async (key: string, value: string) => {+ kv.set(key, value);+ return "OK";+ },+ del: async (key: string) => Number(kv.delete(key))}}));+// GoTrue takes only a UUID as a user id.+const USER_ID = "8f7c1e5a-3b2d-4c6e-9a1f-0d2e4b6c8a10";+const IDLE_MS = 15 * 60 * 1000;const ABSOLUTE_MS = 12 * 60 * 60 * 1000;-vi.mock("../config/env", () => ({- AUTH_COOKIE_SUFFIX: undefined,- DOMAIN: "localhost",- CarbonEdition: "Community",- CONTROLLED_ENVIRONMENT: false,- REFRESH_ACCESS_TOKEN_THRESHOLD: 60,- SESSION_ABSOLUTE_MAX_MS: 12 * 60 * 60 * 1000,- SESSION_IDLE_LOCK_MS: 15 * 60 * 1000,- SESSION_KEY: "auth",- SESSION_MAX_AGE: 60 * 60 * 24 * 7,- SESSION_SECRET: "test-session-secret"-}));--vi.mock("./auth.server", () => ({- // refreshAccessToken returns a FRESH-minted-looking session (createdAt/lastActiveAt- // = "now"), so the preserve test proves refreshAuthSession restores the originals.- makeAuthSession: vi.fn(),- refreshAccessToken: vi.fn(),- verifyAuthSession: vi.fn().mockResolvedValue(true)-}));--vi.mock("./company.server", () => ({- setCompanyId: vi.fn(() => "companyId=cookie")-}));+// GoTrue, answered over a stubbed fetch: a token refresh mints a fresh+// session, and the admin factor list says whether the user enrolled TOTP.+const gotrue = { hasVerifiedTotp: false };+const fakeGoTrue = async (input: RequestInfo | URL) => {+ const url = new URL(input instanceof Request ? input.url : String(input));+ const json = (body: unknown) =>+ new Response(JSON.stringify(body), {+ headers: { "Content-Type": "application/json" }+ });+ if (url.pathname === "/auth/v1/token") {+ return json({+ access_token: "fresh-access-token",+ refresh_token: "fresh-refresh-token",+ token_type: "bearer",+ expires_in: 3600,+ expires_at: FUTURE_EXPIRES_AT,+ user: { id: USER_ID, email: "[email protected]" }+ });+ }+ if (url.pathname === `/auth/v1/admin/users/${USER_ID}/factors`) {+ return json(+ gotrue.hasVerifiedTotp+ ? [{ id: "factor_1", factor_type: "totp", status: "verified" }]+ : []+ );+ }+ return new Response("{}", { status: 404 });+};-vi.mock("./mfa.server", () => ({- getTotpFactors: vi.fn().mockResolvedValue([]),- userHasVerifiedTotpFactor: vi.fn().mockResolvedValue(false),- verifyTotpChallenge: vi.fn().mockResolvedValue(null)-}));+beforeEach(() => {+ kv.clear();+ gotrue.hasVerifiedTotp = false;+ vi.stubGlobal("fetch", fakeGoTrue);+});-vi.mock("./users", () => ({- getPermissionCacheKey: (userId: string) => `permissions:${userId}`-}));+afterEach(() => vi.unstubAllGlobals());-import type { AuthSession } from "../types";-import { refreshAccessToken } from "./auth.server";-import { userHasVerifiedTotpFactor } from "./mfa.server";-import {- flash,- getSessionFlash,- isSessionExpiredAbsolute,- isSessionIdleLocked,- refreshAuthSession,- requireAuthSession,- setAuthSession-} from "./session.server";+afterAll(() => vi.unstubAllEnvs());const FUTURE_EXPIRES_AT = 4102444800; // far enough that isExpiringSoon is falseconst makeSession = (overrides: Partial<AuthSession> = {}): AuthSession => ({accessToken: "access-token",refreshToken: "refresh-token",- userId: "user_1",+ userId: USER_ID,companyId: "company_1",companyGroupId: "group_1",email: "[email protected]",@@ -93,7 +119,6 @@ describe("session timeout predicates", () => {afterEach(() => {vi.useRealTimers();- vi.clearAllMocks();});describe("isSessionExpiredAbsolute (3.1.11)", () => {@@ -145,7 +170,6 @@ describe("refreshAuthSession preserves session-age clocks", () => {afterEach(() => {vi.useRealTimers();- vi.clearAllMocks();});it("keeps the original createdAt/lastActiveAt across a silent token refresh", async () => {@@ -163,15 +187,12 @@ describe("refreshAuthSession preserves session-age clocks", () => {});- // The refresh rebuild looks freshly-minted (createdAt/lastActiveAt = now).- vi.mocked(refreshAccessToken).mockResolvedValue(- makeSession({ createdAt: Date.now(), lastActiveAt: Date.now() })- );-// POST so refreshAuthSession returns inline rather than throwing a GET redirect.const refreshed = await refreshAuthSession(requestWithCookie(cookie));- // The absolute-cap clock and idle clock are the ORIGINALS, not "now".+ // The new tokens, but the absolute-cap and idle clocks are the ORIGINALS:+ // the rebuilt session would otherwise be stamped "now".+ expect(refreshed.accessToken).toBe("fresh-access-token");expect(refreshed.createdAt).toBe(originalCreatedAt);expect(refreshed.lastActiveAt).toBe(originalLastActiveAt);// Sanity: a session 8h old is not yet absolute-expired, and 2min idle is not locked.@@ -215,8 +236,6 @@ describe("requireAuthSession returns to the requested URL", () => {afterEach(() => {vi.useRealTimers();- vi.clearAllMocks();- vi.mocked(userHasVerifiedTotpFactor).mockResolvedValue(false);});it("after a token refresh", async () => {@@ -224,8 +243,6 @@ describe("requireAuthSession returns to the requested URL", () => {const cookie = await sessionCookie({expiresAt: Math.floor(Date.now() / 1000) + 30});- vi.mocked(refreshAccessToken).mockResolvedValue(makeSession());-const response = await redirectOf(requestWithCookie(cookie, {method: "GET",@@ -246,7 +263,7 @@ describe("requireAuthSession returns to the requested URL", () => {it("after an MFA challenge", async () => {const cookie = await sessionCookie();- vi.mocked(userHasVerifiedTotpFactor).mockResolvedValue(true);+ gotrue.hasVerifiedTotp = true;const response = await redirectOf(requestWithCookie(cookie, {diff --git a/packages/checks/package.json b/packages/checks/package.jsonindex d12b6e661a..395317dd7a 100644--- a/packages/checks/package.json+++ b/packages/checks/package.json@@ -14,18 +14,20 @@"license-headers": "tsx src/scripts/license-headers.ts","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit",+ "typecheck": "tsc --noEmit","workflow-events": "tsx src/scripts/check-workflow-events.ts"},"devDependencies": {"@carbon/config": "workspace:*","@carbon/ee": "workspace:*",+ "@carbon/env": "workspace:*","@types/node": "^22","@types/pg": "8.15.6","pg": "8.20.0","rimraf": "catalog:","tsx": "catalog:","typescript": "catalog:",+ "typescript5": "npm:[email protected]","vitest": "catalog:"}}diff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.jsonindex a9f5fbeb10..f4bcdd085f 100644--- a/packages/checks/src/conformance/baseline.json+++ b/packages/checks/src/conformance/baseline.json@@ -201,7 +201,6 @@"no-legacy-rls::20260817030612_remove-global-permission-wildcard.sql::has_company_permission(","no-legacy-rls::20260817040245_fix-is-claims-admin-permission-key.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/items/items.service.ts::new Date().toISOString().split(\"T\")[0]","no-local-timezone::apps/erp/app/modules/production/production.service.ts::new Date().toISOString().slice(0, 10)","no-local-timezone::apps/erp/app/modules/production/production.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]",@@ -337,7 +336,6 @@"no-raw-rounding::apps/erp/app/components/UploadProgress.tsx::value={`${Math.round(percent)}%`}","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/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)]();","no-raw-rounding::apps/erp/app/modules/documents/documents.service.ts::size = Math.round(converted.data.size / 1024);",@@ -366,12 +364,12 @@"no-raw-rounding::apps/erp/app/modules/production/production.service.ts::const totalJobs = lotSize > 0 ? Math.ceil(totalQuantity / lotSize) : 1;","no-raw-rounding::apps/erp/app/modules/production/production.service.ts::return Math.max(Math.ceil(days), 1);","no-raw-rounding::apps/erp/app/modules/production/production.service.ts::trackingType === \"Batch\" ? 1 : Math.round(Number(job.quantity));",- "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx::` \u00b7 BOM qty ${Math.round(bomLine.quantity)} \u2260 model ${group.count}`}",+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx::` · BOM qty ${Math.round(bomLine.quantity)} ≠ model ${group.count}`}","no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx::bomLine !== undefined && Math.round(bomLine.quantity) !== group.count;",- "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx::if (mm3 >= 1000) return `${(mm3 / 1000).toFixed(1)} cm\u00b3`;",- "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx::return `${mm3.toFixed(0)} mm\u00b3`;",+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx::if (mm3 >= 1000) return `${(mm3 / 1000).toFixed(1)} cm³`;",+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx::return `${mm3.toFixed(0)} mm³`;","no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx::return mm >= 100 ? mm.toFixed(0) : mm.toFixed(1);",- "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx::\u00d7{Math.round(material.quantity)}",+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx::×{Math.round(material.quantity)}","no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx::? Math.max(0, Math.round((solveNow - solveStartedAt) / 1000))","no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx::const solveElapsedLabel = `${Math.floor(solveElapsedSeconds / 60)}:${String(","no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyStepBom.tsx::)}, ${Math.round(color[2] * 255)}, ${color[3]})`",@@ -533,7 +531,7 @@"no-raw-rounding::packages/ee/src/onshape/panel/session-policy.ts::Math.min(PANEL_SESSION_TTL_SECONDS, Math.floor(remainingMs / 1000))","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::? `\u2022 Completed <!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/files/src/common.ts::return `${gb.toFixed(2)} GB`;","no-raw-rounding::packages/files/src/common.ts::return `${mb.toFixed(2)} MB`;",@@ -683,5 +681,42 @@"route-action-shape::apps/erp/app/routes/api+/account.security.ts::.from(\"passkeyCredential\").delete(","route-action-shape::apps/erp/app/routes/api+/account.security.ts::.from(\"passkeyCredential\").update(","route-action-shape::apps/erp/app/routes/api+/passkey.authenticate.verify.ts::.from(\"passkeyCredential\").update(",- "route-action-shape::apps/erp/app/routes/api+/passkey.register.verify.ts::.from(\"passkeyCredential\").insert("+ "route-action-shape::apps/erp/app/routes/api+/passkey.register.verify.ts::.from(\"passkeyCredential\").insert(",+ "test-mocks-own-module::apps/erp/test/release-jobs.test.ts::vi.mock(\"../app/modules/production/production.service\")",+ "test-mocks-own-module::apps/erp/test/release-jobs.test.ts::vi.mock(\"../app/modules/shared/shared.service\")",+ "test-mocks-own-module::apps/erp/test/resources-operations.test.ts::vi.mock(\"../app/modules/shared/shared.service\")",+ "test-mocks-own-module::apps/erp/test/sales-operations.test.ts::vi.mock(\"../app/modules/shared/shared.service\")",+ "test-mocks-own-module::packages/auth/src/lib/sign-in-browser.server.test.ts::vi.doMock(\"../config/env\")",+ "test-mocks-own-module::packages/auth/src/lib/sign-in-browser.server.test.ts::vi.mock(\"../config/env\")",+ "test-mocks-own-module::packages/auth/src/services/bot-protection.test.ts::vi.mock(\"../config/env\")",+ "test-mocks-own-module::packages/ee/src/accounting/providers/xero/entities/__tests__/charge.test.ts::vi.mock(\"../../../../core/utils\")",+ "test-mocks-own-module::packages/ee/src/mcp/server.test.ts::vi.mock(\"../entitlements.server\")",+ "test-mocks-own-module::packages/ee/src/rules/sales/invoice-shipto.test.ts::vi.mock(\"../../plan.server\")",+ "test-mocks-own-module::packages/ee/src/sso/sso.server.test.ts::vi.mock(\"./verification.server\")",+ "test-mocks-own-module::packages/jobs/src/inngest/functions/integrations/onshape-attach.test.ts::vi.mock(\"../tasks/assembler-client\")",+ "test-mocks-own-module::packages/jobs/src/inngest/functions/notifications/send-email.test.ts::vi.mock(\"../../client\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/batch.test.ts::vi.mock(\"../../db\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/batch.test.ts::vi.mock(\"../actions\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/batch.test.ts::vi.mock(\"./ledger\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/batch.test.ts::vi.mock(\"./log\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/batch.test.ts::vi.mock(\"./owner\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/end-to-end.test.ts::vi.mock(\"../../db\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/end-to-end.test.ts::vi.mock(\"../actions\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/end-to-end.test.ts::vi.mock(\"./ledger\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/end-to-end.test.ts::vi.mock(\"./log\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/end-to-end.test.ts::vi.mock(\"./owner\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/execute.test.ts::vi.mock(\"../../db\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/execute.test.ts::vi.mock(\"../actions\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/execute.test.ts::vi.mock(\"./ledger\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/execute.test.ts::vi.mock(\"./log\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/execute.test.ts::vi.mock(\"./owner\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/manual.test.ts::vi.mock(\"../../db\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/manual.test.ts::vi.mock(\"../actions\")",+ "test-mocks-own-module::packages/jobs/src/workflows/engine/manual.test.ts::vi.mock(\"./owner\")",+ "test-mocks-own-module::packages/kv/src/lease.test.ts::vi.mock(\"./client\")",+ "test-reads-source::apps/erp/test/mcp-manifest-cache-inputs.test.ts::readFileSync(file, \"utf8\")",+ "test-reads-source::apps/erp/test/mcp-manifest-cache-inputs.test.ts::resolveImport(file, fileName)",+ "test-reads-source::docs/content/src/links.test.ts::readFileSync(file, \"utf8\")",+ "test-reads-source::packages/database/src/authz/migration.test.ts::readFileSync( path.join(MIGRATIONS_DIR, securityFixes), \"utf8\" )",+ "test-reads-source::packages/database/src/realtime-tables.test.ts::readFileSync( new URL( \"./event-system/functions/broadcast_table_changes.sql\", import.meta.url ), \"utf8\" )"]diff --git a/packages/checks/src/conformance/deployments-set-required-env.test.ts b/packages/checks/src/conformance/deployments-set-required-env.test.tsnew file mode 100644index 0000000000..bdd9e04842--- /dev/null+++ b/packages/checks/src/conformance/deployments-set-required-env.test.ts@@ -0,0 +1,70 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ DEPLOYMENT_ENV_FILES,+ type DeploymentEnvSources,+ deploymentEnvKeys,+ findDeploymentEnvGaps+} from "./deployments-set-required-env";++const base = (+ overrides: Partial<Record<keyof DeploymentEnvSources, string>> = {}+): DeploymentEnvSources => {+ const contents = {+ sst: `const erp = cluster.addService("CarbonERPService", {+ environment: {+ DOMAIN: process.env.DOMAIN,+ ERP_URL: process.env.ERP_URL,+ },+ });+ const mes = cluster.addService("CarbonMESService", {+ environment: {+ DOMAIN: process.env.DOMAIN,+ },+ });`,+ devEnv: 'lines.push(`DOMAIN=localhost`);\nlines.push("ERP_URL=x");',+ envExample: "SUPABASE_URL=http://localhost\n# COMMENTED=1\n",+ vercel: JSON.stringify({ erp: ["DOMAIN", "ERP_URL"] }),+ ...overrides+ };+ return Object.fromEntries(+ Object.entries(DEPLOYMENT_ENV_FILES).map(([key, file]) => [+ key,+ { file, contents: contents[key as keyof typeof contents] }+ ])+ ) as DeploymentEnvSources;+};++// Stands in for @carbon/env's validation: these two stop startup.+const requires =+ (...names: string[]) =>+ (env: Record<string, string>) =>+ names.filter((name) => !env[name]);++describe("deploymentEnvKeys", () => {+ it("reads each SST service, the local env and each Vercel project", () => {+ expect(+ deploymentEnvKeys(base()).map(({ name, keys }) => [name, keys])+ ).toEqual([+ ["SST CarbonERPService", ["DOMAIN", "ERP_URL"]],+ ["SST CarbonMESService", ["DOMAIN"]],+ ["local crbn up", ["DOMAIN", "ERP_URL", "SUPABASE_URL"]],+ ["Vercel erp", ["DOMAIN", "ERP_URL", "NODE_ENV"]]+ ]);+ });+});++describe("findDeploymentEnvGaps", () => {+ it("accepts a required variable every deployment sets", () => {+ expect(findDeploymentEnvGaps(base(), requires("DOMAIN"))).toEqual([]);+ });++ it("names each deployment that lacks a required variable", () => {+ expect(+ findDeploymentEnvGaps(base(), requires("ERP_URL")).map((v) => v.snippet)+ ).toEqual(["SST CarbonMESService: ERP_URL"]);+ });+});diff --git a/packages/checks/src/conformance/deployments-set-required-env.ts b/packages/checks/src/conformance/deployments-set-required-env.tsnew file mode 100644index 0000000000..59bc185349--- /dev/null+++ b/packages/checks/src/conformance/deployments-set-required-env.ts@@ -0,0 +1,82 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { SourceFile, Violation } from "../check";++export const DEPLOYMENTS_SET_REQUIRED_ENV = "deployments-set-required-env";++export const DEPLOYMENT_ENV_FILES = {+ sst: "sst.config.ts",+ devEnv: "packages/dev/src/env.ts",+ envExample: ".env.example",+ // Names only, from `vercel env ls production` plus the team's shared+ // variables. Add a name here when someone adds it in Vercel.+ vercel: "packages/env/src/vercel-production.json"+} as const;++export type DeploymentEnvSources = Record<+ keyof typeof DEPLOYMENT_ENV_FILES,+ SourceFile+>;++type Deployment = { name: string; file: string; keys: string[] };++/** The variable names each real deployment sets, read from the file that sets them. */+export function deploymentEnvKeys(sources: DeploymentEnvSources): Deployment[] {+ const { sst, devEnv, envExample, vercel } = sources;+ const services = [...sst.contents.matchAll(/environment: \{/g)].map(+ (env, i) => {+ const start = (env.index ?? 0) + env[0].length;+ const owner = [+ ...sst.contents.slice(0, start).matchAll(/addService\(\s*"([^"]+)"/g)+ ].at(-1)?.[1];+ const block = sst.contents.slice(start).split("\n },")[0] ?? "";+ return {+ name: `SST ${owner ?? `service ${i + 1}`}`,+ file: sst.file,+ keys: [...block.matchAll(/^\s+([A-Z0-9_]+):/gm)].map(+ (m) => m[1] as string+ )+ };+ }+ );+ const local = {+ name: "local crbn up",+ file: devEnv.file,+ keys: [+ ...devEnv.contents.matchAll(/[`"]([A-Z0-9_]+)=/g),+ ...envExample.contents.matchAll(/^([A-Z0-9_]+)=/gm)+ ].map((m) => m[1] as string)+ };+ const projects = Object.entries(+ JSON.parse(vercel.contents) as Record<string, string[]>+ ).map(([project, keys]) => ({+ name: `Vercel ${project}`,+ file: vercel.file,+ // Vercel itself adds NODE_ENV at runtime.+ keys: [...keys, "NODE_ENV"]+ }));+ return [...services, local, ...projects];+}++/**+ * A variable that stops startup when missing must already be set by every+ * deployment, or adding it takes production down. `missingRequired` is+ * `@carbon/env`'s validation: the names it reports as errors for an env.+ */+export function findDeploymentEnvGaps(+ sources: DeploymentEnvSources,+ missingRequired: (env: Record<string, string>) => string[]+): Violation[] {+ return deploymentEnvKeys(sources).flatMap(({ name, file, keys }) =>+ missingRequired(Object.fromEntries(keys.map((key) => [key, "set"]))).map(+ (variable) => ({+ file,+ line: 0,+ snippet: `${name}: ${variable}`,+ message: `${variable} is required at startup but ${name} does not set it; set it there first, or make it optional`+ })+ )+ );+}diff --git a/packages/checks/src/conformance/event-ignored-columns.test.ts b/packages/checks/src/conformance/event-ignored-columns.test.tsnew file mode 100644index 0000000000..548db4d9fb--- /dev/null+++ b/packages/checks/src/conformance/event-ignored-columns.test.ts@@ -0,0 +1,46 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { findIgnoredColumnDrift } from "./event-ignored-columns";++const auditConfig = {+ file: "audit.config.ts",+ contents: `export const auditConfig = {+ skipFields: ["updatedAt", "updatedBy", "embedding"],+ retentionDays: 30+} as const;`+};++const fn = (name: string, columns: string | null) => ({+ file: `${name}.sql`,+ contents: `CREATE OR REPLACE FUNCTION public.${name}() RETURNS trigger AS $$+DECLARE+${columns === null ? "" : ` ignored_columns CONSTANT TEXT[] := ARRAY[${columns}];\n`}BEGIN+END;+$$;`+});++const drift = (...functions: ReturnType<typeof fn>[]) =>+ findIgnoredColumnDrift(functions, auditConfig).map((v) => v.file);++describe("findIgnoredColumnDrift", () => {+ it("accepts the same columns in any order, and functions without the list", () => {+ expect(+ drift(+ fn("log_table_changes", "'embedding', 'updatedAt', 'updatedBy'"),+ fn("get_audit_log", null)+ )+ ).toEqual([]);+ });++ it.each([+ ["an extra column", "'updatedAt', 'updatedBy', 'embedding', 'loadedAt'"],+ ["a missing column", "'updatedAt', 'updatedBy'"]+ ])("flags a trigger with %s", (_, columns) => {+ expect(drift(fn("dispatch_event_batch", columns))).toEqual([+ "dispatch_event_batch.sql"+ ]);+ });+});diff --git a/packages/checks/src/conformance/event-ignored-columns.ts b/packages/checks/src/conformance/event-ignored-columns.tsnew file mode 100644index 0000000000..bd222478c8--- /dev/null+++ b/packages/checks/src/conformance/event-ignored-columns.ts@@ -0,0 +1,57 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { SourceFile, Violation } from "../check";++export const EVENT_IGNORED_COLUMNS = "event-ignored-columns";++export const EVENT_FUNCTIONS_DIR =+ "packages/database/src/event-system/functions";+export const AUDIT_CONFIG_FILE = "packages/database/src/audit.config.ts";++/**+ * The event triggers drop an UPDATE that changes only bookkeeping columns+ * before it is queued, broadcast or logged, because the audit diff would+ * discard it anyway (`auditConfig.skipFields`). A column added on one side+ * only makes the triggers and the handler disagree.+ */+export function findIgnoredColumnDrift(+ functions: SourceFile[],+ auditConfig: SourceFile+): Violation[] {+ const skip = /skipFields:\s*\[([^\]]*)\]/.exec(auditConfig.contents)?.[1];+ if (skip === undefined) {+ return [+ {+ file: auditConfig.file,+ line: 0,+ snippet: "skipFields",+ message: "auditConfig.skipFields not found"+ }+ ];+ }+ const expected = [...skip.matchAll(/"([^"]+)"/g)]+ .map((m) => m[1] as string)+ .sort();++ const out: Violation[] = [];+ for (const { file, contents } of functions) {+ const declared =+ /ignored_columns\s+CONSTANT\s+TEXT\[\]\s*:=\s*ARRAY\[([^\]]*)\]/i.exec(+ contents+ );+ if (!declared) continue;+ const columns = [...(declared[1] ?? "").matchAll(/'([^']+)'/g)]+ .map((m) => m[1] as string)+ .sort();+ if (columns.join() === expected.join()) continue;+ out.push({+ file,+ line: contents.slice(0, declared.index).split("\n").length,+ snippet: `ignored_columns ${columns.join(",")}`,+ message: `ignored_columns must equal auditConfig.skipFields (${expected.join(", ")})`+ });+ }+ return out;+}diff --git a/packages/checks/src/conformance/lingui-macro-misuse.test.ts b/packages/checks/src/conformance/lingui-macro-misuse.test.tsnew file mode 100644index 0000000000..96a23c5fa4--- /dev/null+++ b/packages/checks/src/conformance/lingui-macro-misuse.test.ts@@ -0,0 +1,30 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { linguiMacroMisuse } from "./lingui-macro-misuse";++const scan = (contents: string) =>+ linguiMacroMisuse.scan("apps/erp/app/x.tsx", contents).map((v) => v.line);++describe("linguiMacroMisuse", () => {+ it.each([+ ['import { t } from "@lingui/core/macro";'],+ ["import { msg, t } from '@lingui/core/macro';"],+ ["const label = i18n._(msg`Scrap`);"],+ ["const label = _( msg`Scrap`);"],+ ["const label = t(msg({ message: 'Scrap' }));"]+ ])("flags %s", (source) => {+ expect(scan(source)).toEqual([1]);+ });++ it.each([+ ['import { msg } from "@lingui/core/macro";'],+ ['import { t, Trans, useLingui } from "@lingui/react/macro";'],+ ["const label = i18n._(descriptors[status]);"],+ ["const { t } = useLingui(); const label = t`Scrap`;"]+ ])("accepts %s", (source) => {+ expect(scan(source)).toEqual([]);+ });+});diff --git a/packages/checks/src/conformance/lingui-macro-misuse.ts b/packages/checks/src/conformance/lingui-macro-misuse.tsnew file mode 100644index 0000000000..1877e7523f--- /dev/null+++ b/packages/checks/src/conformance/lingui-macro-misuse.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { ConformanceCheck, Violation } from "../check";++// No `runtimeConfigModule` is configured, so `t` from @lingui/core/macro+// compiles to a call on the global i18n instance, which is never activated:+// it throws "Attempted to call a translation function without setting a+// locale". `msg` from the same module is the right way to build a descriptor.+const CORE_T_IMPORT =+ /import\s*\{[^}]*\bt\b[^}]*\}\s*from\s*["']@lingui\/core\/macro["']/g;+// `i18n._(msg`Scrap`)` is the long way round to `t`Scrap``. Rendering a+// descriptor built elsewhere, `i18n._(descriptor)`, is fine and not matched.+const UNWRAPPED_MSG = /[._]\(\s*msg`|\bt\(\s*msg\(/g;++export const linguiMacroMisuse: ConformanceCheck = {+ id: "lingui-macro-misuse",+ description:+ "Translate with useLingui().t / <Trans>; never the global t, never i18n._(msg`...`)",+ provenance: {+ deprecates: "t from @lingui/core/macro, i18n._(msg`...`)",+ replacedBy:+ "useLingui().t or <Trans> from @lingui/react/macro (.claude/rules/i18n-lingui-system.md)",+ since: "2026-10-25"+ },+ scan(file: string, contents: string): Violation[] {+ const at = (index = 0) => contents.slice(0, index).split("\n").length;+ return [+ ...[...contents.matchAll(CORE_T_IMPORT)].map((m) => ({+ file,+ line: at(m.index),+ snippet: 'import { t } from "@lingui/core/macro"',+ message:+ "t from @lingui/core/macro calls the global i18n instance, which is never activated; use useLingui().t from @lingui/react/macro"+ })),+ ...[...contents.matchAll(UNWRAPPED_MSG)].map((m) => ({+ file,+ line: at(m.index),+ snippet: m[0],+ message: "Use t`...` instead of unwrapping a literal msg`...`"+ }))+ ];+ }+};diff --git a/packages/checks/src/conformance/list-select-covers-columns.test.ts b/packages/checks/src/conformance/list-select-covers-columns.test.tsnew file mode 100644index 0000000000..c10e792dd5--- /dev/null+++ b/packages/checks/src/conformance/list-select-covers-columns.test.ts@@ -0,0 +1,82 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ findUnselectedListColumns,+ LIST_TABLES+} from "./list-select-covers-columns";++const PARTS_TABLE = LIST_TABLES.PARTS_LIST_COLUMNS as string;++const service = (constants: Record<string, string>) => ({+ file: "apps/erp/app/modules/items/items.service.ts",+ contents: Object.entries(constants)+ .map(([name, list]) => `const ${name} =\n "${list}" as const;`)+ .join("\n")+});++const table = (body: string) => ({ file: PARTS_TABLE, contents: body });++// Every other mapped constant, defined and with an empty table, so a case+// only reports what it is about.+const others = () => {+ const rest = Object.entries(LIST_TABLES).filter(+ ([name]) => name !== "PARTS_LIST_COLUMNS"+ );+ return {+ services: [service(Object.fromEntries(rest.map(([name]) => [name, "id"])))],+ tables: rest.map(([, file]) => ({ file, contents: "" }))+ };+};++const snippets = (partsList: string | null, partsTable: string) => {+ const { services, tables } = others();+ const constants: Record<string, string> =+ partsList === null ? {} : { PARTS_LIST_COLUMNS: partsList };+ return findUnselectedListColumns(+ [...services, service(constants)],+ [...tables, table(partsTable)]+ ).map((v) => v.snippet);+};++describe("findUnselectedListColumns", () => {+ it("accepts a table whose accessorKeys are all selected", () => {+ expect(+ snippets(+ "id,name,customFields",+ `accessorKey: "id", accessorKey: "name", accessorKey: "customFields->>abc", useCustomColumns`+ )+ ).toEqual([]);+ });++ it("flags an accessorKey the select dropped", () => {+ expect(snippets("id", `accessorKey: "id", accessorKey: "mpn"`)).toEqual([+ "PARTS_LIST_COLUMNS lacks mpn"+ ]);+ });++ it("flags custom columns rendered without selecting customFields", () => {+ expect(snippets("id", `accessorKey: "id", useCustomColumns`)).toEqual([+ "PARTS_LIST_COLUMNS lacks customFields"+ ]);+ });++ it("flags a new list constant with no table mapped", () => {+ const { services, tables } = others();+ expect(+ findUnselectedListColumns(+ [+ ...services,+ service({ PARTS_LIST_COLUMNS: "id", KITS_LIST_COLUMNS: "id" })+ ],+ [...tables, table("")]+ ).map((v) => v.snippet)+ ).toEqual(["KITS_LIST_COLUMNS"]);+ });++ it("flags a mapped constant that no service defines any more", () => {+ expect(snippets(null, "")).toEqual(["PARTS_LIST_COLUMNS"]);+ });+});diff --git a/packages/checks/src/conformance/list-select-covers-columns.ts b/packages/checks/src/conformance/list-select-covers-columns.tsnew file mode 100644index 0000000000..ac265b6453--- /dev/null+++ b/packages/checks/src/conformance/list-select-covers-columns.ts@@ -0,0 +1,106 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { SourceFile, Violation } from "../check";++export const LIST_SELECT_COVERS_COLUMNS = "list-select-covers-columns";++const UI = "apps/erp/app/modules";++/**+ * The view-backed list endpoints select an explicit column list (so Postgres+ * prunes the views' unused computed columns), and each list table exports the+ * columns it declares. The narrowed select narrows the row type, but the CSV+ * export (`Table/components/Download.tsx`) reads `row[accessorKey]` untyped:+ * an accessorKey the select dropped exports blank, and nothing else fails.+ *+ * Each `*_LIST_COLUMNS` constant names the table that renders its rows.+ * Not covered: `meta.exportValue` / `exportOnlyColumn` read arbitrary fields.+ */+export const LIST_TABLES: Record<string, string> = {+ PARTS_LIST_COLUMNS: `${UI}/items/ui/Parts/PartsTable.tsx`,+ MATERIALS_LIST_COLUMNS: `${UI}/items/ui/Materials/MaterialsTable.tsx`,+ TOOLS_LIST_COLUMNS: `${UI}/items/ui/Tools/ToolsTable.tsx`,+ CONSUMABLES_LIST_COLUMNS: `${UI}/items/ui/Consumables/ConsumablesTable.tsx`,+ SERVICES_LIST_COLUMNS: `${UI}/items/ui/Services/ServicesTable.tsx`,+ PURCHASE_ORDERS_LIST_COLUMNS: `${UI}/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx`,+ QUOTES_LIST_COLUMNS: `${UI}/sales/ui/Quotes/QuotesTable.tsx`,+ SALES_ORDERS_LIST_COLUMNS: `${UI}/sales/ui/SalesOrder/SalesOrdersTable.tsx`,+ PURCHASE_INVOICES_LIST_COLUMNS: `${UI}/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx`,+ SALES_INVOICES_LIST_COLUMNS: `${UI}/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx`+};++const LIST_CONSTANT = /const ([A-Z_]+_LIST_COLUMNS) =\s*"([^"]*)"/g;++const lineAt = (contents: string, index = 0) =>+ contents.slice(0, index).split("\n").length;++/** Every list table's accessorKeys against the columns its endpoint selects. */+export function findUnselectedListColumns(+ services: SourceFile[],+ tables: SourceFile[]+): Violation[] {+ const out: Violation[] = [];+ const tableByFile = new Map(tables.map((t) => [t.file, t]));+ const found = new Set<string>();++ for (const service of services) {+ for (const match of service.contents.matchAll(LIST_CONSTANT)) {+ const [, constant = "", list = ""] = match;+ found.add(constant);+ const tablePath = LIST_TABLES[constant];+ const table = tablePath ? tableByFile.get(tablePath) : undefined;+ if (!table) {+ out.push({+ file: service.file,+ line: lineAt(service.contents, match.index),+ snippet: constant,+ message: tablePath+ ? `${tablePath} not found; update LIST_TABLES in list-select-covers-columns.ts`+ : `Add ${constant} and the table that renders it to LIST_TABLES in list-select-covers-columns.ts`+ });+ continue;+ }+ const selected = new Set(list.split(","));+ for (const key of table.contents.matchAll(/accessorKey:\s*"([^"]+)"/g)) {+ const column = key[1] ?? "";+ // Custom-field columns are keyed `customFields->>{id}`; the+ // `customFields` column itself is what has to be selected.+ if (column.startsWith("customFields->>") || selected.has(column))+ continue;+ out.push({+ file: table.file,+ line: lineAt(table.contents, key.index),+ snippet: `${constant} lacks ${column}`,+ message: `accessorKey "${column}" is not in ${constant}, so it exports blank in the CSV download`+ });+ }+ if (+ table.contents.includes("useCustomColumns") &&+ !selected.has("customFields")+ ) {+ out.push({+ file: table.file,+ line: lineAt(+ table.contents,+ table.contents.indexOf("useCustomColumns")+ ),+ snippet: `${constant} lacks customFields`,+ message: `The table renders custom columns but ${constant} does not select customFields`+ });+ }+ }+ }++ for (const constant of Object.keys(LIST_TABLES)) {+ if (found.has(constant)) continue;+ out.push({+ file: "packages/checks/src/conformance/list-select-covers-columns.ts",+ line: 0,+ snippet: constant,+ message: `${constant} is not defined in any module service; update LIST_TABLES`+ });+ }+ return out;+}diff --git a/packages/checks/src/conformance/no-legacy-rls.test.ts b/packages/checks/src/conformance/no-legacy-rls.test.tsindex 5687ec376a..638c73ef11 100644--- a/packages/checks/src/conformance/no-legacy-rls.test.ts+++ b/packages/checks/src/conformance/no-legacy-rls.test.ts@@ -19,10 +19,4 @@ describe("noLegacyRls", () => {const v = noLegacyRls.scan("p.sql", sql);expect(v).toHaveLength(0);});-- it("records provenance pointing at the RLS refactor migration", () => {- expect(noLegacyRls.provenance.since).toBe(- "20250201181148_rls-refactor.sql"- );- });});diff --git a/packages/checks/src/conformance/no-local-timezone.test.ts b/packages/checks/src/conformance/no-local-timezone.test.tsindex d605882dcf..17c2e654e8 100644--- a/packages/checks/src/conformance/no-local-timezone.test.ts+++ b/packages/checks/src/conformance/no-local-timezone.test.ts@@ -75,10 +75,4 @@ describe("noLocalTimezone", () => {"const d = datetime.today(await getCompanyTimeZone(client, companyId)).toString();";expect(noLocalTimezone.scan("f.ts", ts)).toHaveLength(0);});-- it("records provenance pointing at the company-timezone migration", () => {- expect(noLocalTimezone.provenance.since).toBe(- "20260805020925_company-timezone.sql"- );- });});diff --git a/packages/checks/src/conformance/provider-role-backfilled.test.ts b/packages/checks/src/conformance/provider-role-backfilled.test.tsnew file mode 100644index 0000000000..7ac90ed640--- /dev/null+++ b/packages/checks/src/conformance/provider-role-backfilled.test.ts@@ -0,0 +1,85 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { findProviderRoleDrift } from "./provider-role-backfilled";++const config = (id: string, role?: string) => ({+ file: `packages/ee/src/${id}/config.tsx`,+ contents: `export const X = defineIntegration({+ name: "X",+ id: "${id}",${role ? `\n providerRole: "${role}" as const,` : ""}+ active: true+});`+});++const migration = (file: string, sql: string) => ({ file, contents: sql });++const drift = (...args: Parameters<typeof findProviderRoleDrift>) =>+ findProviderRoleDrift(...args).map((v) => v.snippet);++describe("findProviderRoleDrift", () => {+ it("accepts roles set by IN lists and by equality, across migrations", () => {+ expect(+ drift(+ [+ config("xero", "accounting"),+ config("quickbooks", "accounting"),+ config("sense", "oee")+ ],+ [+ migration(+ "1_role.sql",+ `UPDATE "integration" SET "providerRole" = 'accounting'+ WHERE id IN ('xero', 'quickbooks')+ AND "providerRole" IS DISTINCT FROM 'accounting';`+ ),+ migration(+ "2_oee.sql",+ `UPDATE "integration" SET "providerRole" = 'oee'+ WHERE "id" = 'sense' AND "providerRole" IS DISTINCT FROM 'oee';`+ )+ ]+ )+ ).toEqual([]);+ });++ it("flags a declared role that no migration stored", () => {+ expect(drift([config("netsuite", "accounting")], [])).toEqual([+ "netsuite: accounting declared, NULL stored"+ ]);+ });++ it("reads the latest migration's role, not the first", () => {+ expect(+ drift(+ [config("ramp", "accounting")],+ [+ migration(+ "1.sql",+ `UPDATE "integration" SET "providerRole" = 'accounting' WHERE id = 'ramp';`+ ),+ migration(+ "2.sql",+ `UPDATE "integration" SET "providerRole" = 'spend' WHERE id = 'ramp';`+ )+ ]+ )+ ).toEqual(["ramp: accounting declared, spend stored"]);+ });++ it("flags a stored role whose config declares none", () => {+ expect(+ drift(+ [config("ramp")],+ [+ migration(+ "1.sql",+ `UPDATE "integration" SET "providerRole" = 'spend' WHERE id = 'ramp';`+ )+ ]+ )+ ).toEqual(["ramp: spend stored, none declared"]);+ });+});diff --git a/packages/checks/src/conformance/provider-role-backfilled.ts b/packages/checks/src/conformance/provider-role-backfilled.tsnew file mode 100644index 0000000000..7cd4ad272c--- /dev/null+++ b/packages/checks/src/conformance/provider-role-backfilled.ts@@ -0,0 +1,75 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { SourceFile, Violation } from "../check";++export const PROVIDER_ROLE_BACKFILLED = "provider-role-backfilled";++/**+ * `providerRole` is declared twice by necessity: on the integration's+ * `config.tsx` (`packages/ee/src/<id>/`), which the app reads, and on the+ * `integration` row, which the `companyIntegration_single_active_role` trigger+ * reads. The trigger returns early on NULL, so a descriptor whose role no+ * migration set fails as "no enforcement", not as an error.+ *+ * Replays every `UPDATE "integration" SET "providerRole" = …` in migration+ * order and compares the result with the descriptors, both ways.+ */+export function findProviderRoleDrift(+ configs: SourceFile[],+ migrations: SourceFile[]+): Violation[] {+ const declared = new Map<+ string,+ { role: string; file: string; line: number }+ >();+ for (const { file, contents } of configs) {+ const role = /providerRole:\s*"(\w+)"/.exec(contents);+ const id = /\n\s*id:\s*"([^"]+)"/.exec(contents);+ if (!role?.[1] || !id?.[1]) continue;+ declared.set(id[1], {+ role: role[1],+ file,+ line: contents.slice(0, role.index).split("\n").length+ });+ }++ const stored = new Map<string, { role: string | null; file: string }>();+ for (const { file, contents } of migrations) {+ for (const update of contents.matchAll(+ /UPDATE\s+(?:public\.)?"?integration"?\s+SET\s+"providerRole"\s*=\s*(?:'(\w+)'|NULL)\s+WHERE\s+([^;]*);/gi+ )) {+ const where = update[2] ?? "";+ const list =+ /"?id"?\s+IN\s*\(([^)]*)\)/i.exec(where)?.[1] ??+ /"?id"?\s*=\s*('[^']+')/i.exec(where)?.[1] ??+ "";+ for (const id of list.matchAll(/'([^']+)'/g)) {+ stored.set(id[1] ?? "", { role: update[1] ?? null, file });+ }+ }+ }++ const out: Violation[] = [];+ for (const [id, { role, file, line }] of declared) {+ const row = stored.get(id)?.role ?? null;+ if (row === role) continue;+ out.push({+ file,+ line,+ snippet: `${id}: ${role} declared, ${row ?? "NULL"} stored`,+ message: `No migration sets integration "${id}" to providerRole '${role}', so the one-active-per-role trigger does not guard it; add UPDATE "integration" SET "providerRole" = '${role}' WHERE id = '${id}'`+ });+ }+ for (const [id, { role, file }] of stored) {+ if (role === null || declared.has(id)) continue;+ out.push({+ file,+ line: 0,+ snippet: `${id}: ${role} stored, none declared`,+ message: `Integration "${id}" has providerRole '${role}' in the database but its config declares none`+ });+ }+ return out;+}diff --git a/packages/checks/src/conformance/scheduled-sql-constants.test.ts b/packages/checks/src/conformance/scheduled-sql-constants.test.tsnew file mode 100644index 0000000000..b81b5f1efc--- /dev/null+++ b/packages/checks/src/conformance/scheduled-sql-constants.test.ts@@ -0,0 +1,73 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ findScheduledSqlDrift,+ SCHEDULED_WORK_CHECKS+} from "./scheduled-sql-constants";++const [digest, retention] = SCHEDULED_WORK_CHECKS as [+ (typeof SCHEDULED_WORK_CHECKS)[number],+ (typeof SCHEDULED_WORK_CHECKS)[number]+];++const sources = (threshold = 5) => [+ {+ file: digest.constants,+ contents: `export const DIGEST_THRESHOLD = ${threshold};\nexport const DIGEST_MIN_AGE_MIN = 60;`+ },+ {+ file: retention.constants,+ contents: `export const STALE_RUN_HOURS = 24;+export const FULL_DETAIL_DAYS = 7;+export const COMPACT_DETAIL_DAYS = 30;+export const RUN_HEADER_DAYS = 90;+export const TERMINAL = ["Succeeded", "Failed"] as const;`+ }+];++const digestSql = (+ total: number+) => `CREATE OR REPLACE FUNCTION util.notification_digest_has_work()+RETURNS boolean AS $$+ SELECT EXISTS (SELECT 1 WHERE "createdAt" < now() - interval '60 minutes' AND c.total >= ${total})+$$;`;++const retentionSql = `CREATE OR REPLACE FUNCTION util.workflow_run_retention_has_work()+RETURNS boolean AS $$+ SELECT now() - interval '24 hours', interval '7 days', interval '30 days',+ interval '90 days', "status" IN ('Succeeded', 'Failed')+$$;`;++const drift = (migrations: string[], threshold?: number) =>+ findScheduledSqlDrift(+ migrations.map((contents, i) => ({ file: `${i}.sql`, contents })),+ sources(threshold)+ ).map((v) => v.snippet);++describe("findScheduledSqlDrift", () => {+ it("accepts SQL that repeats every constant", () => {+ expect(drift([digestSql(5), retentionSql])).toEqual([]);+ });++ it("flags a constant changed in TypeScript only", () => {+ expect(drift([digestSql(5), retentionSql], 10)).toEqual([+ "util.notification_digest_has_work: c.total >= {DIGEST_THRESHOLD}"+ ]);+ });++ it("reads the newest definition, so a later migration's change counts", () => {+ expect(drift([digestSql(5), retentionSql, digestSql(10)], 10)).toEqual([]);+ expect(drift([digestSql(10), retentionSql, digestSql(5)], 10)).toEqual([+ "util.notification_digest_has_work: c.total >= {DIGEST_THRESHOLD}"+ ]);+ });++ it("flags a function no migration defines", () => {+ expect(drift([retentionSql])).toEqual([+ "util.notification_digest_has_work"+ ]);+ });+});diff --git a/packages/checks/src/conformance/scheduled-sql-constants.ts b/packages/checks/src/conformance/scheduled-sql-constants.tsnew file mode 100644index 0000000000..532488344c--- /dev/null+++ b/packages/checks/src/conformance/scheduled-sql-constants.ts@@ -0,0 +1,109 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { SourceFile, Violation } from "../check";++export const SCHEDULED_SQL_CONSTANTS = "scheduled-sql-constants";++const SCHEDULED = "packages/jobs/src/inngest/functions/scheduled";++/**+ * pg_cron wakes a scheduled function only when its `util.*_has_work()` says a+ * run would do something, and that SQL repeats the function's constants. A+ * constant changed on one side only either wakes the function for nothing or+ * leaves work undone. `{NAME}` is the constant's value; a string array is+ * written as SQL literals, `'a', 'b'`.+ */+export const SCHEDULED_WORK_CHECKS = [+ {+ fn: "util.notification_digest_has_work",+ constants: `${SCHEDULED}/notification-digest.ts`,+ expected: [+ "c.total >= {DIGEST_THRESHOLD}",+ "interval '{DIGEST_MIN_AGE_MIN} minutes'"+ ]+ },+ {+ fn: "util.workflow_run_retention_has_work",+ constants: `${SCHEDULED}/workflow-run-retention.ts`,+ expected: [+ "interval '{STALE_RUN_HOURS} hours'",+ "interval '{FULL_DETAIL_DAYS} days'",+ "interval '{COMPACT_DETAIL_DAYS} days'",+ "interval '{RUN_HEADER_DAYS} days'",+ "IN ({TERMINAL})"+ ]+ }+];++/** `export const NAME = 5` and `export const NAME = ["a", "b"] as const`. */+function constantsOf(contents: string): Map<string, string> {+ const out = new Map<string, string>();+ for (const m of contents.matchAll(+ /export const (\w+)\s*=\s*(-?\d+(?:\.\d+)?|\[[^\]]*\])/g+ )) {+ const value = m[2] ?? "";+ out.set(+ m[1] ?? "",+ value.startsWith("[")+ ? [...value.matchAll(/"([^"]*)"/g)].map((s) => `'${s[1]}'`).join(", ")+ : value+ );+ }+ return out;+}++/** The newest `CREATE OR REPLACE FUNCTION <fn>(` body in migration order. */+function newestDefinition(fn: string, migrations: SourceFile[]) {+ const marker = `CREATE OR REPLACE FUNCTION ${fn}(`;+ for (const { file, contents } of [...migrations].reverse()) {+ const start = contents.lastIndexOf(marker);+ if (start === -1) continue;+ const end = contents.indexOf("$$;", start);+ return { file, body: contents.slice(start, end === -1 ? undefined : end) };+ }+ return null;+}++export function findScheduledSqlDrift(+ migrations: SourceFile[],+ sources: SourceFile[]+): Violation[] {+ const out: Violation[] = [];+ for (const { fn, constants, expected } of SCHEDULED_WORK_CHECKS) {+ const source = sources.find((s) => s.file === constants);+ const definition = newestDefinition(fn, migrations);+ if (!source || !definition) {+ out.push({+ file: source ? constants : "packages/database/supabase/migrations",+ line: 0,+ snippet: fn,+ message: source+ ? `No migration defines ${fn}`+ : `${constants} not found; update SCHEDULED_WORK_CHECKS`+ });+ continue;+ }+ const values = constantsOf(source.contents);+ for (const template of expected) {+ const missing = [...template.matchAll(/\{(\w+)\}/g)]+ .map((m) => m[1] as string)+ .filter((name) => !values.has(name));+ const text = template.replace(+ /\{(\w+)\}/g,+ (_, name: string) => values.get(name) ?? ""+ );+ if (missing.length === 0 && definition.body.includes(text)) continue;+ out.push({+ file: definition.file,+ line: 0,+ snippet: `${fn}: ${template}`,+ message: missing.length+ ? `${missing.join(", ")} not exported from ${constants}`+ : `${fn} must contain ${text} to match ${constants}; redefine it in a new migration`+ });+ }+ }+ return out;+}diff --git a/packages/checks/src/conformance/service-fn-file.ts b/packages/checks/src/conformance/service-fn-file.tsindex c94ad7c9b9..ab68a784d1 100644--- a/packages/checks/src/conformance/service-fn-file.ts+++ b/packages/checks/src/conformance/service-fn-file.ts@@ -2,7 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import ts from "typescript";+import ts from "typescript5";import type { ConformanceCheck, Violation } from "../check";/**diff --git a/packages/checks/src/conformance/stamp-matches-columns.ts b/packages/checks/src/conformance/stamp-matches-columns.tsindex 1c8cec3089..03971a47ec 100644--- a/packages/checks/src/conformance/stamp-matches-columns.ts+++ b/packages/checks/src/conformance/stamp-matches-columns.ts@@ -2,7 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import ts from "typescript";+import ts from "typescript5";import type { SourceFile, Violation } from "../check";export const STAMP_MATCHES_COLUMNS = "stamp-matches-columns";diff --git a/packages/checks/src/conformance/test-mocks-own-module.test.ts b/packages/checks/src/conformance/test-mocks-own-module.test.tsnew file mode 100644index 0000000000..cb51c41b37--- /dev/null+++ b/packages/checks/src/conformance/test-mocks-own-module.test.ts@@ -0,0 +1,37 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { testMocksOwnModule } from "./test-mocks-own-module";++const scan = (contents: string) =>+ testMocksOwnModule.scan("apps/erp/app/x.test.ts", contents);++describe("testMocksOwnModule", () => {+ it.each([+ ['vi.mock("./x.service")', 'vi.mock("./x.service")'],+ ["vi.mock('../../db', () => ({}))", 'vi.mock("../../db")'],+ ["vi.doMock(`~/modules/items`)", 'vi.doMock("~/modules/items")'],+ ['vi.mock(import("./client"), () => ({}))', 'vi.mock("./client")']+ ])("flags %s", (source, snippet) => {+ expect(scan(source).map((v) => v.snippet)).toEqual([snippet]);+ });++ it("accepts mocks of packages and node built-ins", () => {+ expect(+ scan(`vi.mock("@carbon/auth/client.server");+vi.mock("node:fs");+vi.mock("@lingui/core/macro", () => ({}));`)+ ).toEqual([]);+ });++ it("reports the line of each mock", () => {+ expect(+ scan(`import { vi } from "vitest";+vi.mock("./a");++vi.mock("./b");`).map((v) => v.line)+ ).toEqual([2, 4]);+ });+});diff --git a/packages/checks/src/conformance/test-mocks-own-module.ts b/packages/checks/src/conformance/test-mocks-own-module.tsnew file mode 100644index 0000000000..9940b36431--- /dev/null+++ b/packages/checks/src/conformance/test-mocks-own-module.ts@@ -0,0 +1,32 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { ConformanceCheck, Violation } from "../check";++// A test that mocks its own module's neighbours pins the wiring between them:+// it passes while the rule is wrong and fails when the code is reorganised.+// Package specifiers (`@carbon/...`, `node:...`) are not matched here.+const OWN_MODULE_MOCK =+ /\bvi\.(mock|doMock)\(\s*(?:import\(\s*)?(["'`])((?:\.{1,2}|~)\/[^"'`]*)\2/g;++export const testMocksOwnModule: ConformanceCheck = {+ id: "test-mocks-own-module",+ description: "Tests do not vi.mock a first-party module by relative path",+ provenance: {+ deprecates:+ "vi.mock of ./, ../ or ~/ modules to reach the logic under test",+ replacedBy:+ "a pure function tested by value, or a database test (.claude/rules/testing.md)",+ since: "2026-10-25"+ },+ scan(file: string, contents: string): Violation[] {+ return [...contents.matchAll(OWN_MODULE_MOCK)].map((match) => ({+ file,+ line: contents.slice(0, match.index).split("\n").length,+ snippet: `vi.${match[1]}("${match[3]}")`,+ message:+ "Do not mock our own modules; extract the decision into a pure function and test it by value (.claude/rules/testing.md → Mocks)"+ }));+ }+};diff --git a/packages/checks/src/conformance/test-reads-source.test.ts b/packages/checks/src/conformance/test-reads-source.test.tsnew file mode 100644index 0000000000..e9be7c1eaa--- /dev/null+++ b/packages/checks/src/conformance/test-reads-source.test.ts@@ -0,0 +1,86 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { testReadsSource } from "./test-reads-source";++const lines = (contents: string) =>+ testReadsSource.scan("x.test.ts", contents).map((v) => v.line);++describe("testReadsSource", () => {+ it.each([+ [+ "a migration read by literal path",+ `const sql = readFileSync("../supabase/migrations/2026_x.sql", "utf8");`+ ],+ [+ "a source file through a URL",+ `const s = readFileSync(new URL("../utils/a.ts", import.meta.url), "utf8");`+ ],+ [+ "a path held in a constant",+ `const MIGRATION = join(__dirname, "../x.sql");+const sql = readFileSync(MIGRATION, "utf8");`+ ],+ [+ "a file from a loop over a migrations directory",+ `const DIR = new URL("../migrations/", import.meta.url);+for (const name of readdirSync(DIR)) {+ readFileSync(new URL(name, DIR), "utf8");+}`+ ],+ [+ "a read helper called with a source path",+ `const read = (p: string) => readFileSync(new URL(p, root), "utf8");+read("sst.config.ts");`+ ],+ [+ "a walk filtered to source extensions",+ `const exts = new Set([".ts", ".tsx"]);+files.filter((f) => /bad/.test(readFileSync(f, "utf8")));`+ ],+ ["a ?raw import of SQL", `import sql from "./fn.sql?raw";`],+ [+ "an import.meta.glob of source as raw text",+ `const all = import.meta.glob("./**/*.ts", { query: "?raw" });`+ ]+ ])("flags %s", (_, contents) => {+ expect(lines(contents).length).toBeGreaterThan(0);+ });++ it.each([+ [+ "a JSON fixture",+ `const data = JSON.parse(readFileSync(join(__dirname, "fixture.json"), "utf8"));`+ ],+ [+ "a binary fixture",+ `const pdf = () => readFile(join(__dirname, "__fixtures__", "sample.pdf"));`+ ],+ [+ "a file the test wrote to a temp dir",+ `const dir = mkdtempSync(join(tmpdir(), "x-"));+writeFileSync(join(dir, "types.ts"), "x");+expect(readFileSync(join(dir, "types.ts"), "utf8")).toBe("x");`+ ],+ [+ "a module imported as code",+ `const modules = import.meta.glob("../app/modules/*/*.service.ts");`+ ],+ [+ "a directory listing that is not the migrations",+ `const names = readdirSync(join(ROOT, "packages"));`+ ]+ ])("accepts %s", (_, contents) => {+ expect(lines(contents)).toEqual([]);+ });++ it("reports the line of the read", () => {+ expect(+ lines(`import { readFileSync } from "node:fs";++const sql = readFileSync("./a.sql", "utf8");`)+ ).toEqual([3]);+ });+});diff --git a/packages/checks/src/conformance/test-reads-source.ts b/packages/checks/src/conformance/test-reads-source.tsnew file mode 100644index 0000000000..5a4e86e7c0--- /dev/null+++ b/packages/checks/src/conformance/test-reads-source.ts@@ -0,0 +1,186 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { ConformanceCheck, Violation } from "../check";++// A test that regexes source or migration text is a change detector: an+// applied migration never changes, a later one can redefine the object, and a+// reformat breaks it. packages/checks is the one place such a rule belongs,+// where it has a baseline and runs over every file.+const MESSAGE =+ "Tests do not read .sql/.ts/.tsx text; test the behaviour, or make the rule a conformance check in packages/checks (.claude/rules/testing.md)";++// A string literal naming source: `.sql`/`.ts`/`.tsx` at its end (a path or an+// extension filter), or the migrations directory.+const SOURCE_LITERAL =+ /["'`][^"'`\n]*\.(?:sql|tsx?)["'`]|["'`][^"'`\n]*\bmigrations\b[^"'`\n]*["'`]/;+// Directory walks filtered by a source extension: `endsWith(".ts")`,+// `/\.tsx?$/`, `new Set([".ts", ".tsx"])`.+const SOURCE_FILTER =+ /["'`]\.(?:sql|tsx?)["'`]|\/[^/\n]*\\\.(?:sql|tsx?)\??\$\//;+const TEMP_DIR = /\b(?:mkdtemp|mkdtempSync|tmpdir)\b/;+const RAW_IMPORT =+ /\bimport\b[^;]*?["'`][^"'`\n]*\.(?:sql|tsx?)\?raw["'`]|import\.meta\.glob\([^)]*\.(?:sql|tsx?)["'`][^)]*(?:\?raw|["']raw["'])/g;+const READ_CALL = /\b(readFileSync|readFile|readdirSync|readdir)\s*\(/g;+const DECLARATION =+ /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?:(?::[^=;]+)?=|\s+of\b)|\bfunction\s+([A-Za-z_$][\w$]*)\s*\(/g;++const lineOf = (contents: string, index: number) =>+ contents.slice(0, index).split("\n").length;++/** Index just past the bracket that closes the one at `open`, skipping strings. */+function closeOf(text: string, open: number): number {+ let depth = 0;+ for (let i = open; i < text.length; i++) {+ const c = text[i];+ if (c === '"' || c === "'" || c === "`") {+ const end = text.indexOf(c, i + 1);+ i = end === -1 ? text.length : end;+ } else if (c === "(" || c === "[" || c === "{") depth++;+ else if (c === ")" || c === "]" || c === "}") {+ depth--;+ if (depth === 0) return i + 1;+ }+ }+ return text.length;+}++/** Text of a declaration's initializer or body: up to `;` at depth 0. */+function initializerAt(text: string, start: number): string {+ let depth = 0;+ const limit = Math.min(text.length, start + 4000);+ for (let i = start; i < limit; i++) {+ const c = text[i];+ if (c === '"' || c === "'" || c === "`") {+ const end = text.indexOf(c, i + 1);+ i = end === -1 ? limit : end;+ } else if (c === "(" || c === "[" || c === "{") depth++;+ else if (c === ")" || c === "]" || c === "}") {+ depth--;+ if (depth < 0) return text.slice(start, i);+ } else if (c === ";" && depth === 0) return text.slice(start, i);+ }+ return text.slice(start, limit);+}++/** What each declared name holds, for following a path through variables. */+function declarations(contents: string): Map<string, string> {+ const out = new Map<string, string>();+ for (const match of contents.matchAll(DECLARATION)) {+ const name = match[1] ?? match[2];+ if (!name || out.has(name)) continue;+ const start = (match.index ?? 0) + match[0].length;+ out.set(+ name,+ match[2]+ ? contents.slice(start, closeOf(contents, contents.indexOf("{", start)))+ : initializerAt(contents, start)+ );+ }+ return out;+}++/** The text plus everything the names in it hold, a few levels deep. */+function context(text: string, decls: Map<string, string>): string {+ const seen = new Set<string>();+ let out = text;+ let frontier = text;+ for (let depth = 0; depth < 4 && frontier; depth++) {+ let next = "";+ for (const [name] of frontier.matchAll(/[A-Za-z_$][\w$]*/g)) {+ const held = decls.get(name);+ if (held === undefined || seen.has(name)) continue;+ seen.add(name);+ next += `\n${held}`;+ }+ out += next;+ frontier = next;+ }+ return out;+}++export const testReadsSource: ConformanceCheck = {+ id: "test-reads-source",+ description: "Tests do not read source or migration text",+ provenance: {+ deprecates:+ "vitest files that readFileSync / ?raw-import .sql, .ts or .tsx and regex them",+ replacedBy:+ "behaviour tests, database tests, or a packages/checks conformance check (.claude/rules/testing.md)",+ since: "2026-10-25"+ },+ scan(file: string, contents: string): Violation[] {+ const violations: Violation[] = [];+ const report = (index: number, snippet: string) =>+ violations.push({+ file,+ line: lineOf(contents, index),+ snippet: snippet.replace(/\s+/g, " ").slice(0, 120),+ message: MESSAGE+ });++ for (const match of contents.matchAll(RAW_IMPORT)) {+ report(match.index ?? 0, match[0]);+ }++ const decls = declarations(contents);+ // A local helper that reads (`const read = (p) => readFileSync(...)`) is+ // a read call too, so its call sites are judged by their arguments.+ const readers = [...decls]+ .filter(([, held]) => /\b(?:readFileSync|readFile)\s*\(/.test(held))+ .map(([name]) => name);+ const calls = [...contents.matchAll(READ_CALL)].map((m) => ({+ fn: m[1] as string,+ index: m.index ?? 0,+ open: (m.index ?? 0) + m[0].length - 1,+ helper: false+ }));+ for (const name of readers) {+ for (const m of contents.matchAll(+ new RegExp(`(?<![\\w$.])${name.replace("$", "\\$")}\\s*\\(`, "g")+ )) {+ const index = m.index ?? 0;+ // Skip the declaration itself (`function read(` / `const read = (`).+ if (+ /\bfunction\s+$/.test(contents.slice(Math.max(0, index - 10), index))+ )+ continue;+ calls.push({+ fn: name,+ index,+ open: index + m[0].length - 1,+ helper: true+ });+ }+ }++ const namesSourceAnywhere =+ (SOURCE_LITERAL.test(contents) || SOURCE_FILTER.test(contents)) &&+ !TEMP_DIR.test(contents);++ for (const { fn, index, open, helper } of calls.sort(+ (a, b) => a.index - b.index+ )) {+ const args = contents.slice(open, closeOf(contents, open));+ const held = context(args, decls);+ if (TEMP_DIR.test(held)) continue;+ const isListing = fn === "readdirSync" || fn === "readdir";+ const namesSource = isListing+ ? /["'`][^"'`\n]*\bmigrations\b/.test(held)+ : SOURCE_LITERAL.test(held);+ // The path is a callback or loop parameter, so the variables cannot say+ // what it reads; a file that names source paths and reads one it does+ // not name is reading those.+ // A helper's own read is judged inside it; its call sites only by+ // the path they pass.+ const unnamedRead =+ !isListing &&+ !helper &&+ namesSourceAnywhere &&+ !/["'`][^"'`\n]*\.\w+["'`]/.test(held);+ if (namesSource || unnamedRead) report(index, `${fn}${args}`);+ }+ return violations;+ }+};diff --git a/packages/checks/src/index.ts b/packages/checks/src/index.tsindex 1d5761866e..de78f9a7de 100644--- a/packages/checks/src/index.ts+++ b/packages/checks/src/index.ts@@ -13,6 +13,7 @@ export { findClobbers, objectRefs } from "./clobber";export { edgeFunctionAuthorizesCaller } from "./conformance/edge-function-authorizes-caller";export { indexRedirectBeforeLoaders } from "./conformance/index-redirect-before-loaders";export { journalStatusFilter } from "./conformance/journal-status-filter";+export { linguiMacroMisuse } from "./conformance/lingui-macro-misuse";export { moduleShape } from "./conformance/module-shape";export { noDbClientInService } from "./conformance/no-db-client-in-service";export { noDefaultOnEffects } from "./conformance/no-default-on-effects";@@ -34,6 +35,8 @@ export { noZeroConcurrency } from "./conformance/no-zero-concurrency";export { routeActionShape } from "./conformance/route-action-shape";export { serviceFnFile } from "./conformance/service-fn-file";export { spdxLicenseHeader } from "./conformance/spdx-license-header";+export { testMocksOwnModule } from "./conformance/test-mocks-own-module";+export { testReadsSource } from "./conformance/test-reads-source";export {type Invariant,type InvariantResult,@@ -60,6 +63,7 @@ export {STRUCTURE_CHECKS,scanAll,scanModules,+ TEST_CHECKS,TS_CHECKS} from "./run";export { loadDbTableColumns } from "./sources/db-columns";@@ -70,4 +74,5 @@ export {} from "./sources/license-files";export { loadModules, modulesDir } from "./sources/modules";export { loadServerFiles } from "./sources/server-files";+export { loadTestFiles } from "./sources/test-files";export { loadTypescriptFiles } from "./sources/typescript";diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.tsindex 3e0ec61a28..31c9af9723 100644--- a/packages/checks/src/run.ts+++ b/packages/checks/src/run.ts@@ -4,6 +4,7 @@import { readdirSync } from "node:fs";import { join } from "node:path";+import { validateEnv } from "@carbon/env/validate";import { keyOf, loadBaseline } from "./baseline";import type {ConformanceCheck,@@ -12,17 +13,30 @@ import type {StructureCheck,Violation} from "./check";+import {+ DEPLOYMENTS_SET_REQUIRED_ENV,+ findDeploymentEnvGaps+} from "./conformance/deployments-set-required-env";import {DOCUMENT_SEQUENCE_SYNCED,findUnsyncedDocumentSequences} from "./conformance/document-sequence-synced";import { edgeFunctionAuthorizesCaller } from "./conformance/edge-function-authorizes-caller";+import {+ EVENT_IGNORED_COLUMNS,+ findIgnoredColumnDrift+} from "./conformance/event-ignored-columns";import {FUNCTION_REDEFINITION_KEEPS_CHANGES,findDroppedFunctionChanges} from "./conformance/function-redefinition-keeps-changes";import { indexRedirectBeforeLoaders } from "./conformance/index-redirect-before-loaders";import { journalStatusFilter } from "./conformance/journal-status-filter";+import { linguiMacroMisuse } from "./conformance/lingui-macro-misuse";+import {+ findUnselectedListColumns,+ LIST_SELECT_COVERS_COLUMNS+} from "./conformance/list-select-covers-columns";import { moduleShape } from "./conformance/module-shape";import {MANAGED_FUNCTION_SETS,@@ -61,7 +75,15 @@ import { noUnroundedTrackedQuantity } from "./conformance/no-unrounded-tracked-qimport { noUnscopedKyselyWrite } from "./conformance/no-unscoped-kysely-write";import { noViewWithoutInvoker } from "./conformance/no-view-without-invoker";import { noZeroConcurrency } from "./conformance/no-zero-concurrency";+import {+ findProviderRoleDrift,+ PROVIDER_ROLE_BACKFILLED+} from "./conformance/provider-role-backfilled";import { routeActionShape } from "./conformance/route-action-shape";+import {+ findScheduledSqlDrift,+ SCHEDULED_SQL_CONSTANTS+} from "./conformance/scheduled-sql-constants";import { serviceFnFile } from "./conformance/service-fn-file";import {findUndeclaredSideEffectImports,@@ -72,6 +94,15 @@ import {findStampColumnMismatches,STAMP_MATCHES_COLUMNS} from "./conformance/stamp-matches-columns";+import { testMocksOwnModule } from "./conformance/test-mocks-own-module";+import { testReadsSource } from "./conformance/test-reads-source";+import {+ loadDeploymentEnvSources,+ loadEventFunctionSources,+ loadIntegrationConfigs,+ loadListSources,+ loadScheduledConstantSources+} from "./sources/cross-file";import { loadDbTableColumns } from "./sources/db-columns";import { loadDocumentSequenceSources } from "./sources/document-sequences";import { loadEdgeFunctions } from "./sources/edge-functions";@@ -84,6 +115,7 @@ import {} from "./sources/modules";import { loadServerFiles } from "./sources/server-files";import { loadSideEffectPackages } from "./sources/side-effect-packages";+import { loadTestFiles } from "./sources/test-files";import {loadTypescriptFiles,REQUEST_HANDLING_ROOTS,@@ -123,6 +155,12 @@ export const TS_CHECKS: ConformanceCheck[] = [journalStatusFilter];+/** Checks that run over git-tracked vitest files (apps, packages, scripts, docs). */+export const TEST_CHECKS: ConformanceCheck[] = [+ testReadsSource,+ testMocksOwnModule+];+/** Checks that run once per edge function, over all of its .ts files. */export const EDGE_FUNCTION_CHECKS: ConformanceCheck[] = [edgeFunctionAuthorizesCaller@@ -181,6 +219,9 @@ export function loadManagedFunctions(root: string): ManagedFunction[] {/** Every finding across the real migrations (text) + modules (structure) + server TS + app TS + edge functions + license headers under `root`. */export function collectFindings(root: string = repoRoot()): Finding[] {+ const migrations = loadSqlFiles(migrationsDir(root));+ const listSources = loadListSources(root);+ const eventSources = loadEventFunctionSources(root);return [...scanAll(loadSqlFiles(migrationsDir(root)), [...CONFORMANCE_CHECKS,@@ -198,7 +239,8 @@ export function collectFindings(root: string = repoRoot()): Finding[] {...scanAll(loadTypescriptFiles(root, REQUEST_HANDLING_ROOTS), [noRawForwardedHeaders,noInterpolatedErrorLog,- noRawRedirect+ noRawRedirect,+ linguiMacroMisuse]),...scanAll(loadTypescriptFiles(root), [noRawOrSearch,@@ -218,19 +260,37 @@ export function collectFindings(root: string = repoRoot()): Finding[] {...findUnsyncedDocumentSequences(loadDocumentSequenceSources(root)).map((violation) => ({ checkId: DOCUMENT_SEQUENCE_SYNCED, violation })),- ...findDroppedFunctionChanges(loadSqlFiles(migrationsDir(root))).map(- (violation) => ({- checkId: FUNCTION_REDEFINITION_KEEPS_CHANGES,- violation- })- ),+ ...findDroppedFunctionChanges(migrations).map((violation) => ({+ checkId: FUNCTION_REDEFINITION_KEEPS_CHANGES,+ violation+ })),...findStampColumnMismatches(loadModuleServerFiles(root),loadDbTableColumns(root)).map((violation) => ({ checkId: STAMP_MATCHES_COLUMNS, violation })),...findUndeclaredSideEffectImports(loadSideEffectPackages(root)).map((violation) => ({ checkId: SIDE_EFFECT_IMPORT_DECLARED, violation })- )+ ),+ ...scanAll(loadTestFiles(root), TEST_CHECKS),+ ...findUnselectedListColumns(listSources.services, listSources.tables).map(+ (violation) => ({ checkId: LIST_SELECT_COVERS_COLUMNS, violation })+ ),+ ...findProviderRoleDrift(loadIntegrationConfigs(root), migrations).map(+ (violation) => ({ checkId: PROVIDER_ROLE_BACKFILLED, violation })+ ),+ ...findIgnoredColumnDrift(+ eventSources.functions,+ eventSources.auditConfig+ ).map((violation) => ({ checkId: EVENT_IGNORED_COLUMNS, violation })),+ ...findScheduledSqlDrift(+ migrations,+ loadScheduledConstantSources(root)+ ).map((violation) => ({ checkId: SCHEDULED_SQL_CONSTANTS, violation })),+ ...findDeploymentEnvGaps(loadDeploymentEnvSources(root), (env) =>+ validateEnv(env)+ .problems.filter((p) => p.level === "error")+ .map((p) => p.name)+ ).map((violation) => ({ checkId: DEPLOYMENTS_SET_REQUIRED_ENV, violation }))];}diff --git a/packages/checks/src/scripts-lib.test.ts b/packages/checks/src/scripts-lib.test.tsnew file mode 100644index 0000000000..f1a7f82033--- /dev/null+++ b/packages/checks/src/scripts-lib.test.ts@@ -0,0 +1,169 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// The root `scripts/lib` helpers belong to no package. They are tested here+// because this package's tests never cache, so an edit under scripts/ is seen.+import { describe, expect, it } from "vitest";+import {+ sortRelationships,+ stripPerTenantTables,+ validateDatabaseUrl+} from "../../../scripts/lib/generate-db-types";+import { readLocalScriptConfig } from "../../../scripts/lib/local-script-config";+import { normalizeSwaggerSchema } from "../../../scripts/lib/swagger-schema";++describe("validateDatabaseUrl", () => {+ it.each(["localhost", "127.0.0.1", "[::1]"])(+ "accepts a local PostgreSQL host %s",+ (host) => {+ const url = `postgresql://example:synthetic@${host}:5432/example`;+ expect(validateDatabaseUrl(url)).toBe(url);+ }+ );++ it.each([+ undefined,+ " ",+ "not-a-database-url",+ "postgresql://localhost:[email protected]/example",+ "postgresql://example:[email protected]/example",+ "postgresql://example:[email protected]/localhost",+ "http://example:synthetic-secret@localhost/example",+ "postgresql://example:synthetic-secret@localhost/example?host=example.com",+ "postgresql://example:synthetic-secret@localhost/example?hostaddr=192.0.2.1"+ ])("refuses %s without echoing it", (url) => {+ // The message lands in public run logs, so it must not carry the URL.+ expect(() => validateDatabaseUrl(url)).toThrow(+ expect.objectContaining({+ message: expect.not.stringMatching(/synthetic-secret|example\.com/)+ })+ );+ });+});++describe("stripPerTenantTables", () => {+ const table = (name: string) =>+ [` ${name}: {`, " Row: {}", " }"].join("\n");++ it("drops per-company tables, quoted ids included, and keeps the static ones", () => {+ const source = [+ table("searchIndexRegistry"),+ table("searchIndex_dal7910g60gg2egcfj40"),+ table('"searchIndex_accttest-08e7f74786d6-company"'),+ table('"auditLog_accttest-08e7f74786d6-company"'),+ table("auditLogArchive")+ ].join("\n");+ expect(stripPerTenantTables(source)).toBe(+ [table("searchIndexRegistry"), table("auditLogArchive")].join("\n")+ );+ });+});++describe("sortRelationships", () => {+ const block = (entries: string[]) =>+ [+ " x: {",+ " Relationships: [",+ ...entries,+ " ]",+ " }"+ ].join("\n");+ const entry = (column: string, last = false) =>+ [+ " {",+ ' foreignKeyName: "x_fkey"',+ ` columns: ["${column}"]`,+ " isOneToOne: false",+ ' referencedRelation: "country"',+ ' referencedColumns: ["code"]',+ last ? " }" : " },"+ ].join("\n");++ it("orders a Relationships block the same whatever order Postgres listed it in", () => {+ const sorted = block([+ entry("customerCountryCode"),+ entry("supplierCountryCode", true)+ ]);+ const unsorted = block([+ entry("supplierCountryCode"),+ entry("customerCountryCode", true)+ ]);+ // Every entry but the last keeps its trailing comma.+ expect(sortRelationships(unsorted)).toBe(sorted);+ expect(sortRelationships(sorted)).toBe(sorted);+ });++ it("leaves an empty block alone", () => {+ const empty = " Relationships: []\n }";+ expect(sortRelationships(empty)).toBe(empty);+ });+});++describe("normalizeSwaggerSchema", () => {+ const pk = "This is a Primary Key.<pk/>";+ const fk =+ "This is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>";+ // PostgREST puts the `partners` primary-key note on whichever alias of+ // partner.id it meets first, which differs between databases.+ const schema = (pkOn: "id" | "supplierLocationId") => ({+ definitions: {+ partners: {+ properties: {+ id: {+ description: `Original id documentation.\n\nNote:\n${pkOn === "id" ? `${pk}\n` : ""}${fk}`+ },+ supplierLocationId: {+ description: `Alias documentation.\n\nNote:\n${pkOn === "supplierLocationId" ? `${pk}\n` : ""}${fk}`+ }+ }+ },+ unrelated: { properties: { id: { description: `Leave: ${pk}` } } }+ }+ });++ it("pins the primary-key note to id whichever alias carried it", () => {+ expect(normalizeSwaggerSchema(schema("supplierLocationId"))).toEqual(+ schema("id")+ );+ expect(normalizeSwaggerSchema(schema("id"))).toEqual(schema("id"));+ });++ it("keeps the note on the alias when id has no Note block to receive it", () => {+ const input = schema("supplierLocationId");+ input.definitions.partners.properties.id.description = "No note here.";+ expect(normalizeSwaggerSchema(input)).toEqual(input);+ });++ it("does not modify its input", () => {+ const input = schema("supplierLocationId");+ normalizeSwaggerSchema(input);+ expect(input).toEqual(schema("supplierLocationId"));+ });+});++describe("readLocalScriptConfig", () => {+ it("returns only the requested values", () => {+ expect(+ readLocalScriptConfig(["A_TEST_KEY", "B_TEST_KEY"], {+ A_TEST_KEY: "a",+ B_TEST_KEY: "b",+ C_TEST_KEY: "ignored"+ })+ ).toEqual({ A_TEST_KEY: "a", B_TEST_KEY: "b" });+ });++ it("names the missing and blank keys without disclosing configured values", () => {+ let message = "";+ try {+ readLocalScriptConfig(["A_TEST_KEY", "B_TEST_KEY", "C_TEST_KEY"], {+ A_TEST_KEY: "private-value-sentinel",+ B_TEST_KEY: " "+ });+ } catch (error) {+ message = (error as Error).message;+ }+ expect(message).toMatch(/: B_TEST_KEY, C_TEST_KEY\./);+ expect(message).not.toContain("private-value-sentinel");+ });+});diff --git a/packages/checks/src/smoke.test.ts b/packages/checks/src/smoke.test.tsdeleted file mode 100644index 61d4e37f01..0000000000--- a/packages/checks/src/smoke.test.ts+++ /dev/null@@ -1,11 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { describe, expect, it } from "vitest";--describe("@carbon/checks", () => {- it("runs", () => {- expect(true).toBe(true);- });-});diff --git a/packages/checks/src/sources/cross-file.ts b/packages/checks/src/sources/cross-file.tsnew file mode 100644index 0000000000..9337afa1c8--- /dev/null+++ b/packages/checks/src/sources/cross-file.ts@@ -0,0 +1,83 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { existsSync, readdirSync, readFileSync } from "node:fs";+import { join } from "node:path";+import type { SourceFile } from "../check";+import {+ DEPLOYMENT_ENV_FILES,+ type DeploymentEnvSources+} from "../conformance/deployments-set-required-env";+import {+ AUDIT_CONFIG_FILE,+ EVENT_FUNCTIONS_DIR+} from "../conformance/event-ignored-columns";+import { LIST_TABLES } from "../conformance/list-select-covers-columns";+import { SCHEDULED_WORK_CHECKS } from "../conformance/scheduled-sql-constants";+import { loadModules, modulesDir } from "./modules";++// The files the cross-file checks compare, read once here so each check+// stays a pure function of its inputs.++const read = (root: string, file: string): SourceFile => ({+ file,+ contents: readFileSync(join(root, file), "utf8")+});++const readIfPresent = (root: string, files: string[]): SourceFile[] =>+ files+ .filter((file) => existsSync(join(root, file)))+ .map((f) => read(root, f));++/** Every module's `<m>.service.ts`, and the list tables `LIST_TABLES` names. */+export function loadListSources(root: string) {+ return {+ services: readIfPresent(+ root,+ loadModules(modulesDir(root)).map(+ ({ name }) => `apps/erp/app/modules/${name}/${name}.service.ts`+ )+ ),+ tables: readIfPresent(root, Object.values(LIST_TABLES))+ };+}++/** Each integration descriptor: `packages/ee/src/<id>/config.ts(x)`. */+export function loadIntegrationConfigs(root: string): SourceFile[] {+ const dir = "packages/ee/src";+ return readdirSync(join(root, dir), { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .flatMap(({ name }) =>+ readIfPresent(root, [+ `${dir}/${name}/config.tsx`,+ `${dir}/${name}/config.ts`+ ])+ );+}++export function loadEventFunctionSources(root: string) {+ return {+ functions: readdirSync(join(root, EVENT_FUNCTIONS_DIR))+ .filter((file) => file.endsWith(".sql"))+ .sort()+ .map((file) => read(root, `${EVENT_FUNCTIONS_DIR}/${file}`)),+ auditConfig: read(root, AUDIT_CONFIG_FILE)+ };+}++export function loadScheduledConstantSources(root: string): SourceFile[] {+ return readIfPresent(+ root,+ SCHEDULED_WORK_CHECKS.map(({ constants }) => constants)+ );+}++export function loadDeploymentEnvSources(root: string): DeploymentEnvSources {+ return Object.fromEntries(+ Object.entries(DEPLOYMENT_ENV_FILES).map(([key, file]) => [+ key,+ read(root, file)+ ])+ ) as DeploymentEnvSources;+}diff --git a/packages/checks/src/sources/test-files.ts b/packages/checks/src/sources/test-files.tsnew file mode 100644index 0000000000..199499d074--- /dev/null+++ b/packages/checks/src/sources/test-files.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { execFileSync } from "node:child_process";+import { existsSync, readFileSync } from "node:fs";+import { join } from "node:path";+import type { SourceFile } from "../check";++// packages/checks is left out: it is the one package whose tests read source+// and migration text, by design.+const TEST_PATHSPECS = [+ ...["apps", "packages", "scripts", "docs/content"].flatMap((dir) => [+ `:(glob)${dir}/**/*.test.ts`,+ `:(glob)${dir}/**/*.test.tsx`+ ]),+ ":(exclude)packages/checks/**"+];++/**+ * Every git-tracked vitest file, repo-relative and sorted. Tracked only, so+ * node_modules and build output never appear; a tracked file deleted from the+ * working tree is skipped.+ */+export function loadTestFiles(root: string): SourceFile[] {+ const out = execFileSync(+ "git",+ ["ls-files", "--cached", "-z", "--", ...TEST_PATHSPECS],+ { cwd: root, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }+ );+ return out+ .split("\0")+ .filter((path) => path.length > 0 && existsSync(join(root, path)))+ .sort()+ .map((path) => ({+ file: path,+ contents: readFileSync(join(root, path), "utf8")+ }));+}diff --git a/packages/database/package.json b/packages/database/package.jsonindex de4fba547b..7a630ba29e 100644--- a/packages/database/package.json+++ b/packages/database/package.json@@ -2,14 +2,17 @@"name": "@carbon/database","devDependencies": {"@carbon/config": "workspace:*",- "@supabase/supabase-js": "catalog:",+ "@supabase/postgrest-js": "catalog:","@types/node": "20.19.39","@types/pg": "8.15.6","@types/uuid": "8.3.4",- "dotenv": "16.3.1",- "libpg-query": "18.1.5",+ "cookie": "catalog:",+ "dompurify": "catalog:",+ "kysely-supabase": "0.2.1","npm-run-all": "catalog:",+ "react-pdf": "catalog:","rimraf": "catalog:",+ "sst": "catalog:","supabase": "catalog:","tsup": "catalog:","tsx": "catalog:",@@ -88,23 +91,20 @@"lint": "biome lint --write ","test": "vitest run","test:watch": "vitest",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"sideEffects": false,"version": "0.0.0","dependencies": {"@internationalized/date": "catalog:","@jitl/quickjs-singlefile-browser-release-sync": "0.32.0",- "@supabase/postgrest-js": "catalog:",- "cookie": "catalog:",- "dompurify": "catalog:",+ "@supabase/supabase-js": "catalog:",+ "dotenv": "16.3.1","kysely": "catalog:",- "kysely-supabase": "0.2.1",+ "libpg-query": "18.1.5","nanoid": "catalog:","pg": "8.20.0","quickjs-emscripten-core": "0.32.0",- "react-pdf": "catalog:",- "sst": "catalog:","sucrase": "3.35.1","zod": "catalog:"}diff --git a/packages/database/src/build-payment-journal.test.ts b/packages/database/src/build-payment-journal.test.tsindex 4bc16d9113..ce75fc7f21 100644--- a/packages/database/src/build-payment-journal.test.ts+++ b/packages/database/src/build-payment-journal.test.ts@@ -13,20 +13,74 @@ import {} from "./build-payment-journal.ts";import { round } from "./precision.ts";-for (const isAR of [true, false]) {- it(`${isAR ? "AR" : "AP"} multiple target rates preserve per-invoice relief, signed FX and decoded GL balance`, () => {+type Input = Parameters<typeof buildPaymentJournal>[0];+type AccountClass = "Asset" | "Liability" | "Expense" | "Revenue";++const base = (overrides: Partial<Input> = {}): Input => ({+ paymentId: "payment",+ companyId: "company",+ isAR: true,+ cashIn: true,+ totalAmount: 0,+ exchangeRate: 1,+ bankAccount: "bank",+ journalLineReference: "reference",+ applications: [],+ newOnAccountBase: 0,+ accounts: {+ controlAccountId: "today-control",+ discountAccountId: "discount",+ writeOffAccountId: "writeoff",+ fxGainAccountId: "fxgain",+ fxLossAccountId: "fxloss"+ },+ ...overrides+});++const amountOf = (+ result: ReturnType<typeof buildPaymentJournal>,+ accountId: string+) => result.lines.find((line) => line.accountId === accountId)?.amount;++// Decode storage independently by account class: a natural-signed sum or the+// builder's own running total cannot prove GL balance once a liability is in+// the entry.+const decodedDebitTotal = (+ result: ReturnType<typeof buildPaymentJournal>,+ classes: Record<string, AccountClass>+) =>+ round(+ result.lines.reduce((sum, line) => {+ const accountClass = classes[line.accountId];+ if (!accountClass)+ throw new Error(`Unexpected account ${line.accountId}`);+ return (+ sum ++ (accountClass === "Asset" || accountClass === "Expense"+ ? line.amount+ : -line.amount)+ );+ }, 0)+ );++it.each([true, false])(+ "multiple target rates preserve per-invoice relief, signed FX and GL balance (isAR=%s)",+ (isAR) => {// Document cash 88 + 55 is worth base 143 at the payment's rate of 1.// Target A: 88 / 1.1 = 80 principal + 15 discount + 5 write-off = 100.// Target B: 55 / 0.8 = 68.75 principal + 3 discount + 2 write-off = 73.75.- // AR realizes +8 and -13.75; AP has the opposite gains/losses.+ // AR realizes +8 and -13.75 (net loss 5.75); AP has the opposite.+ const target = (id: string) => ({+ targetSalesInvoiceId: isAR ? id : null,+ targetPurchaseInvoiceId: isAR ? null : id,+ targetControlAccountId: `control-${id}`,+ sourceExchangeRate: 1,+ sourcePaymentId: null+ });const applications: PaymentJournalApplicationInput[] = [{- targetSalesInvoiceId: isAR ? "invoice-a" : null,- targetPurchaseInvoiceId: isAR ? null : "invoice-a",- targetControlAccountId: "original-control-a",+ ...target("a"),targetExchangeRate: 1.1,- sourceExchangeRate: 1,- sourcePaymentId: null,sourceAmount: 88,appliedAmount: 80,discountAmount: 15,@@ -34,12 +88,8 @@ for (const isAR of [true, false]) {fxGainLossAmount: isAR ? 8 : -8},{- targetSalesInvoiceId: isAR ? "invoice-b" : null,- targetPurchaseInvoiceId: isAR ? null : "invoice-b",- targetControlAccountId: "original-control-b",+ ...target("b"),targetExchangeRate: 0.8,- sourceExchangeRate: 1,- sourcePaymentId: null,sourceAmount: 55,appliedAmount: 68.75,discountAmount: 3,@@ -47,361 +97,165 @@ for (const isAR of [true, false]) {fxGainLossAmount: isAR ? -13.75 : 13.75}];- const result = buildPaymentJournal({- paymentId: "payment",- companyId: "company",- isAR,- cashIn: isAR,- totalAmount: 143,- exchangeRate: 1,- bankAccount: "bank",- journalLineReference: "reference",- applications,- newOnAccountBase: 0,- accounts: {- controlAccountId: "today-control",- discountAccountId: "discount",- writeOffAccountId: "writeoff",- fxGainAccountId: "fxgain",- fxLossAccountId: "fxloss"- }- });+ const result = buildPaymentJournal(+ base({ isAR, cashIn: isAR, totalAmount: 143, applications })+ );- for (const [index, application] of applications.entries()) {- const target = index === 0 ? "invoice-a" : "invoice-b";- const expectedRelief = index === 0 ? 100 : 73.75;- const lines = result.lines.filter(- (line) => line.documentLineReference === target- );- const control = lines.find(- (line) => line.accountId === application.targetControlAccountId- );- if (!control) throw new Error(`Missing original control for ${target}`);- // Natural-balance storage decreases both AR assets and AP liabilities.- expect(control.amount).toEqual(-expectedRelief);- expect(-control.amount).toEqual(- round(- application.appliedAmount +- application.discountAmount +- application.writeOffAmount- )- );- expect(- lines.find((line) => line.accountId === "discount")?.amount- ).toEqual(- isAR ? application.discountAmount : -application.discountAmount- );- expect(- lines.find((line) => line.accountId === "writeoff")?.amount- ).toEqual(application.writeOffAmount);- expect(round(expectedRelief + control.amount)).toEqual(0);- }- expect(- result.lines.find((line) => line.accountId === "bank")?.amount- ).toEqual(isAR ? 143 : -143);+ const linesFor = (id: string) =>+ result.lines+ .filter((line) => line.documentLineReference === id)+ .map((line) => [line.accountId, line.amount]);+ // Natural-balance storage decreases both AR assets and AP liabilities;+ // each invoice is relieved on its ORIGINAL control account.+ expect(linesFor("a")).toEqual(+ expect.arrayContaining([+ ["control-a", -100],+ ["discount", isAR ? 15 : -15],+ ["writeoff", 5]+ ])+ );+ expect(linesFor("b")).toEqual(+ expect.arrayContaining([+ ["control-b", -73.75],+ ["discount", isAR ? 3 : -3],+ ["writeoff", 2]+ ])+ );+ expect(amountOf(result, "bank")).toEqual(isAR ? 143 : -143);expect(result.totalFxImpact).toEqual(isAR ? -5.75 : 5.75);- expect(- result.lines.find(- (line) => line.accountId === (isAR ? "fxloss" : "fxgain")- )?.amount- ).toEqual(5.75);- expect(- !result.lines.some((line) => line.accountId === "today-control")- ).toBeTruthy();+ expect(amountOf(result, isAR ? "fxloss" : "fxgain")).toEqual(5.75);+ expect(amountOf(result, "today-control")).toBeUndefined();- // Decode storage independently by account class; a natural-signed sum- // or the builder's returned running total alone cannot prove GL balance.- const classes: Record<- string,- "Asset" | "Liability" | "Expense" | "Revenue"- > = {- bank: "Asset",- "original-control-a": isAR ? "Asset" : "Liability",- "original-control-b": isAR ? "Asset" : "Liability",- discount: "Expense",- writeoff: isAR ? "Expense" : "Revenue",- fxgain: "Revenue",- fxloss: "Expense"- };- const debitSigned = result.lines.reduce((sum, line) => {- const accountClass = classes[line.accountId];- expect(accountClass, `Unexpected account ${line.accountId}`).toBeTruthy();- return (- sum +- (accountClass === "Asset" || accountClass === "Expense"- ? line.amount- : -line.amount)- );- }, 0);- expect(round(debitSigned)).toEqual(0);- expect(result.signedDebitTotal).toEqual(0);- });-}--// Direction of cash and ledger side are independent. A Disbursement to a-// CUSTOMER is an AR refund (cash out, receivable restored); a Receipt from a-// SUPPLIER is an AP refund. `payment_party_check` permits both, the composer-// stages them, and the docs describe them as supported — post-payment must not-// refuse them.-for (const isAR of [true, false]) {- it(`${isAR ? "AR" : "AP"} refund posts cash on the opposite side of its ledger`, () => {- const result = buildPaymentJournal({- paymentId: "payment",- companyId: "company",- isAR,- // The refund case: cash moves the opposite way to the normal flow.- cashIn: !isAR,- totalAmount: 40,- exchangeRate: 1,- bankAccount: "bank",- journalLineReference: "reference",- applications: [- {- targetMemoId: "memo-a",- targetControlAccountId: "original-control",- targetExchangeRate: 1,- sourceExchangeRate: 1,- sourcePaymentId: null,- sourceAmount: 40,- appliedAmount: 40,- discountAmount: 0,- writeOffAmount: 0,- fxGainLossAmount: 0- }- ],- newOnAccountBase: 0,- accounts: {- controlAccountId: "today-control",- discountAccountId: "discount",- writeOffAccountId: "writeoff",- fxGainAccountId: "fxgain",- fxLossAccountId: "fxloss"- }- });-- // An AR refund pays cash OUT, so the bank asset falls; an AP refund- // receives cash back, so it rises. This is the axis `cashIn` owns.+ const control = isAR ? "Asset" : "Liability";expect(- result.lines.find((line) => line.accountId === "bank")?.amount- ).toEqual(isAR ? -40 : 40);- // The ledger side is the axis `isAR` owns: the refund restores the- // original control account rather than relieving it.- expect(- result.lines.find((line) => line.accountId === "original-control")?.amount- ).toEqual(40);- const classes: Record<- string,- "Asset" | "Liability" | "Expense" | "Revenue"- > = {- bank: "Asset",- "original-control": isAR ? "Asset" : "Liability"- };- const debitSigned = result.lines.reduce((sum, line) => {- const accountClass = classes[line.accountId];- expect(accountClass, `Unexpected account ${line.accountId}`).toBeTruthy();- return (- sum +- (accountClass === "Asset" || accountClass === "Expense"- ? line.amount- : -line.amount)- );- }, 0);- expect(round(debitSigned)).toEqual(0);+ decodedDebitTotal(result, {+ bank: "Asset",+ "control-a": control,+ "control-b": control,+ discount: "Expense",+ writeoff: isAR ? "Expense" : "Revenue",+ fxgain: "Revenue",+ fxloss: "Expense"+ })+ ).toEqual(0);expect(result.signedDebitTotal).toEqual(0);- });-}+ }+);// A customer DEPOSIT — a Receipt referencing a sales order or rental agreement// — is the customer's money held against that document. Its unapplied cash is// a liability on the prepayment account (2110), never on-account receivable// credit; applying it later releases 2110 against the invoice; and a-// Disbursement carrying the same reference refunds it from 2110. Across the-// three, 2110 nets to zero and receivables never carry the deposit itself.-const depositAccounts = {- controlAccountId: "today-control",- discountAccountId: "discount",- writeOffAccountId: "writeoff",- fxGainAccountId: "fxgain",- fxLossAccountId: "fxloss"-};-const depositClasses: Record<- string,- "Asset" | "Liability" | "Expense" | "Revenue"-> = {+// Disbursement carrying the same reference refunds it from 2110.+const depositClasses: Record<string, AccountClass> = {bank: "Asset",prepayment: "Liability","original-control": "Asset","today-control": "Asset"};-// Decode storage independently by account class, as the tests above do: a-// natural-signed sum cannot prove GL balance once a liability is in the entry.-const decodedDebitTotal = (result: ReturnType<typeof buildPaymentJournal>) =>- round(- result.lines.reduce((sum, line) => {- const accountClass = depositClasses[line.accountId];- expect(accountClass, `Unexpected account ${line.accountId}`).toBeTruthy();- return (- sum +- (accountClass === "Asset" || accountClass === "Expense"- ? line.amount- : -line.amount)- );- }, 0)- );it("deposit receipt holds its unapplied cash on the prepayment account, not receivables", () => {- const result = buildPaymentJournal({- paymentId: "deposit",- companyId: "company",- isAR: true,- cashIn: true,- totalAmount: 3000,- exchangeRate: 1,- bankAccount: "bank",- journalLineReference: "reference",- applications: [],- newOnAccountBase: 3000,- accounts: depositAccounts,- isDeposit: true,- depositAccountId: "prepayment"- });- expect(- result.lines.find((line) => line.accountId === "bank")?.amount- ).toEqual(3000);- const held = result.lines.find((line) => line.accountId === "prepayment");- if (!held) throw new Error("Missing prepayment line");+ const result = buildPaymentJournal(+ base({+ totalAmount: 3000,+ newOnAccountBase: 3000,+ isDeposit: true,+ depositAccountId: "prepayment"+ })+ );+ expect(amountOf(result, "bank")).toEqual(3000);// A credit to a liability is stored positive: 3,000 owed back to the customer.- expect(held.amount).toEqual(3000);- expect(held.description).toEqual(CUSTOMER_DEPOSIT_DESCRIPTION);expect(- !result.lines.some((line) => line.accountId === "today-control")- ).toBeTruthy();- expect(decodedDebitTotal(result)).toEqual(0);+ result.lines.find((line) => line.accountId === "prepayment")+ ).toMatchObject({ amount: 3000, description: CUSTOMER_DEPOSIT_DESCRIPTION });+ expect(amountOf(result, "today-control")).toBeUndefined();+ expect(decodedDebitTotal(result, depositClasses)).toEqual(0);expect(result.signedDebitTotal).toEqual(0);});it("applying a deposit to an invoice releases the prepayment account against receivables", () => {- // A zero-cash receipt funded by the posted deposit (sourcePaymentId), the- // existing prior-credit path; the driver read the deposit's own journal line- // and marked the source as a deposit on the prepayment account.- const result = buildPaymentJournal({- paymentId: "application",- companyId: "company",- isAR: true,- cashIn: true,- totalAmount: 0,- exchangeRate: 1,- bankAccount: "bank",- journalLineReference: "reference",- applications: [- {- targetSalesInvoiceId: "invoice",- targetControlAccountId: "original-control",- sourcePaymentId: "deposit",- sourceControlAccountId: "prepayment",- sourceIsDeposit: true,- sourceAmount: 500,- appliedAmount: 500,- discountAmount: 0,- writeOffAmount: 0,- targetExchangeRate: 1,- sourceExchangeRate: 1,- fxGainLossAmount: 0- }- ],- newOnAccountBase: 0,- accounts: depositAccounts,- isDeposit: false,- depositAccountId: "prepayment"- });- const released = result.lines.find((line) => line.accountId === "prepayment");- if (!released) throw new Error("Missing prepayment release");+ // A zero-cash receipt funded by the posted deposit (sourcePaymentId), with+ // the source marked as a deposit on the prepayment account.+ const result = buildPaymentJournal(+ base({+ paymentId: "application",+ applications: [+ {+ targetSalesInvoiceId: "invoice",+ targetControlAccountId: "original-control",+ sourcePaymentId: "deposit",+ sourceControlAccountId: "prepayment",+ sourceIsDeposit: true,+ sourceAmount: 500,+ appliedAmount: 500,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1,+ sourceExchangeRate: 1,+ fxGainLossAmount: 0+ }+ ],+ isDeposit: false,+ depositAccountId: "prepayment"+ })+ );// A debit to a liability is stored negative: 500 less owed back.- expect(released.amount).toEqual(-500);- expect(released.description).toEqual(CUSTOMER_DEPOSIT_APPLIED_DESCRIPTION);expect(- result.lines.find((line) => line.accountId === "original-control")?.amount- ).toEqual(-500);- expect(!result.lines.some((line) => line.accountId === "bank")).toBeTruthy();- expect(- !result.lines.some((line) => line.accountId === "today-control")- ).toBeTruthy();- expect(decodedDebitTotal(result)).toEqual(0);+ result.lines.find((line) => line.accountId === "prepayment")+ ).toMatchObject({+ amount: -500,+ description: CUSTOMER_DEPOSIT_APPLIED_DESCRIPTION+ });+ expect(amountOf(result, "original-control")).toEqual(-500);+ expect(amountOf(result, "bank")).toBeUndefined();+ expect(amountOf(result, "today-control")).toBeUndefined();+ expect(decodedDebitTotal(result, depositClasses)).toEqual(0);expect(result.signedDebitTotal).toEqual(0);});it("refunding a deposit is a customer Disbursement that debits the prepayment account", () => {- const result = buildPaymentJournal({- paymentId: "refund",- companyId: "company",- isAR: true,- cashIn: false,- totalAmount: 2500,- exchangeRate: 1,- bankAccount: "bank",- journalLineReference: "reference",- applications: [],- newOnAccountBase: 2500,- accounts: depositAccounts,- isDeposit: true,- depositAccountId: "prepayment"- });+ const result = buildPaymentJournal(+ base({+ cashIn: false,+ totalAmount: 2500,+ newOnAccountBase: 2500,+ isDeposit: true,+ depositAccountId: "prepayment"+ })+ );+ expect(amountOf(result, "bank")).toEqual(-2500);expect(- result.lines.find((line) => line.accountId === "bank")?.amount- ).toEqual(-2500);- const refunded = result.lines.find((line) => line.accountId === "prepayment");- if (!refunded) throw new Error("Missing prepayment line");- expect(refunded.amount).toEqual(-2500);- expect(refunded.description).toEqual(CUSTOMER_DEPOSIT_DESCRIPTION);+ result.lines.find((line) => line.accountId === "prepayment")+ ).toMatchObject({ amount: -2500, description: CUSTOMER_DEPOSIT_DESCRIPTION });// Never restored to receivables: the customer was not owed on account.- expect(- !result.lines.some((line) => line.accountId === "today-control")- ).toBeTruthy();- expect(decodedDebitTotal(result)).toEqual(0);+ expect(amountOf(result, "today-control")).toBeUndefined();+ expect(decodedDebitTotal(result, depositClasses)).toEqual(0);expect(result.signedDebitTotal).toEqual(0);});it("a receipt without a document reference keeps its remainder on receivables", () => {- const result = buildPaymentJournal({- paymentId: "payment",- companyId: "company",- isAR: true,- cashIn: true,- totalAmount: 3000,- exchangeRate: 1,- bankAccount: "bank",- journalLineReference: "reference",- applications: [],- newOnAccountBase: 3000,- accounts: depositAccounts,- isDeposit: false,- depositAccountId: "prepayment"- });- expect(- result.lines.find((line) => line.accountId === "today-control")?.amount- ).toEqual(-3000);- expect(- !result.lines.some((line) => line.accountId === "prepayment")- ).toBeTruthy();- expect(decodedDebitTotal(result)).toEqual(0);+ const result = buildPaymentJournal(+ base({+ totalAmount: 3000,+ newOnAccountBase: 3000,+ isDeposit: false,+ depositAccountId: "prepayment"+ })+ );+ expect(amountOf(result, "today-control")).toEqual(-3000);+ expect(amountOf(result, "prepayment")).toBeUndefined();+ expect(decodedDebitTotal(result, depositClasses)).toEqual(0);});it("a deposit refuses to post without a prepayment account", () => {expect(() =>- buildPaymentJournal({- paymentId: "deposit",- companyId: "company",- isAR: true,- cashIn: true,- totalAmount: 3000,- exchangeRate: 1,- bankAccount: "bank",- journalLineReference: "reference",- applications: [],- newOnAccountBase: 3000,- accounts: depositAccounts,- isDeposit: true,- depositAccountId: null- })+ buildPaymentJournal(+ base({+ totalAmount: 3000,+ newOnAccountBase: 3000,+ isDeposit: true,+ depositAccountId: null+ })+ )).toThrow(CUSTOMER_DEPOSIT_DESCRIPTION);});diff --git a/packages/database/src/datasets/wipe.test.ts b/packages/database/src/datasets/wipe.test.tsindex 6685266617..bae3cc754d 100644--- a/packages/database/src/datasets/wipe.test.ts+++ b/packages/database/src/datasets/wipe.test.ts@@ -15,13 +15,11 @@ import { wipeCompanyBusinessData } from "./wipe.ts";function stubCtx(counts: { partners?: number; charges?: number; reimbursements?: number } = {}) {- const journalSourceTypes: string[] = [];const client = {- query: async (sql: string, params?: unknown[]) => {+ query: async (sql: string) => {// The journal walk NAMES the reimbursement table in a subquery, so it has// to be matched before the guard counts below.if (sql.includes("FROM journal j")) {- journalSourceTypes.push(...((params?.[1] as string[]) ?? []));// No journals to void — the pass returns before writing anything.return { rows: [] };}@@ -37,10 +35,7 @@ function stubCtx(throw new Error("wipe-continued-past-the-guards");}} as unknown as PoolClient;- return {- ctx: { client, companyId: "co_1" } as unknown as Ctx,- journalSourceTypes- };+ return { client, companyId: "co_1" } as unknown as Ctx;}describe("assertWipeable", () => {@@ -49,26 +44,16 @@ describe("assertWipeable", () => {// and does not honour app.sync_in_progress, so without this guard the// template apply aborted mid-wipe on a raw trigger error — and the row// cannot be walked back to Draft the way an invoice can.- const { ctx } = stubCtx({ reimbursements: 3 });+ const ctx = stubCtx({ reimbursements: 3 });await expect(wipeCompanyBusinessData(ctx)).rejects.toThrow("3 posted or voided reimbursement(s)");});it("proceeds when every reimbursement is still Draft", async () => {- const { ctx } = stubCtx({ reimbursements: 0 });+ const ctx = stubCtx({ reimbursements: 0 });await expect(wipeCompanyBusinessData(ctx)).rejects.toThrow("wipe-continued-past-the-guards");});});--describe("reverseDocumentJournals", () => {- it("counts Reimbursement among the document journal sources", async () => {- const { ctx, journalSourceTypes } = stubCtx();- await expect(wipeCompanyBusinessData(ctx)).rejects.toThrow(- "wipe-continued-past-the-guards"- );- expect(journalSourceTypes).toContain("Reimbursement");- });-});diff --git a/packages/database/src/event-dispatch.test.ts b/packages/database/src/event-dispatch.test.tsdeleted file mode 100644index 10b5ecfe5b..0000000000--- a/packages/database/src/event-dispatch.test.ts+++ /dev/null@@ -1,66 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";-import { describe, expect, it } from "vitest";-import { auditConfig } from "./audit.config";--// Every trigger function that drops an UPDATE touching only bookkeeping columns.-const files = [- "dispatch_event_batch",- "broadcast_table_changes",- "broadcast_user_changes",- "broadcast_reference_changes",- "log_table_changes",- "log_user_changes"-].map((name) => `event-system/functions/${name}.sql`);--describe.each(files)("%s", (file) => {- const sql = readFileSync(- fileURLToPath(new URL(file, import.meta.url)),- "utf8"- );-- // The trigger drops an UPDATE that changes only these columns before it is- // queued or broadcast, because the audit diff would discard it. A skip field- // added on one side only makes the triggers and the handler disagree.- it("ignores exactly the columns the audit diff skips", () => {- const declared = sql.match(- /ignored_columns CONSTANT TEXT\[\] := ARRAY\[([^\]]*)\]/- );-- expect(declared, `${file} has no ignored_columns`).not.toBeNull();- const columns = declared![1]!- .split(",")- .map((column) => column.trim().replace(/'/g, ""));- expect(columns.sort()).toEqual([...auditConfig.skipFields].sort());- });-});--describe("dispatch_event_batch recordId", () => {- const read = (name: string) =>- readFileSync(- fileURLToPath(- new URL(`event-system/functions/${name}.sql`, import.meta.url)- ),- "utf8"- );-- // Behaviour is proven against a database, for every evented table, by- // supabase/tests/event-record-id.test.sql. These keep the two edits that- // test depends on from being reverted where no database runs.- it("is built from the whole primary key, not one column of it", () => {- const sql = read("dispatch_event_batch");- expect(sql).toContain("pk_columns := public.get_primary_key_columns(");- expect(sql.match(/''recordId'', %s,/g)).toHaveLength(3);- expect(sql).toContain("IF 'id' = ANY(pk_columns)");- });-- it("reads a unique index's key columns from position 0", () => {- const sql = read("get_primary_key_columns");- expect(sql).toContain("[0:i.indnkeyatts - 1]");- expect(sql).not.toContain("[1:i.indnkeyatts]");- });-});diff --git a/packages/database/src/realtime-tables.test.ts b/packages/database/src/realtime-tables.test.tsindex ed7b0e3eb4..a5aa99f041 100644--- a/packages/database/src/realtime-tables.test.ts+++ b/packages/database/src/realtime-tables.test.ts@@ -20,12 +20,6 @@ it("names each table once, in one list", () => {expect(new Set(all).size).toBe(all.length);});-it("derives each list from the attached broadcast handler", () => {- expect(REALTIME_TABLES).toContain("jobOperation");- expect(REALTIME_REFERENCE_TABLES).toContain("customerType");- expect(REALTIME_USER_TABLES).toEqual(["notification"]);-});-it("lists the ancestor columns broadcast_table_changes adds", () => {const sql = readFileSync(new URL(diff --git a/packages/database/supabase/tests/accounting-shipping-backfill.test.sql b/packages/database/supabase/tests/accounting-shipping-backfill.test.sqldeleted file mode 100644index ba45efc13d..0000000000--- a/packages/database/supabase/tests/accounting-shipping-backfill.test.sql+++ /dev/null@@ -1,315 +0,0 @@--- Shipping-account migration and backfill behavior.--- Run from the repository root against the existing local development database:--- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X \--- -v ON_ERROR_STOP=1 \--- -f packages/database/supabase/tests/accounting-shipping-backfill.test.sql------ Before migration this fails at the first missing-schema assertion. After--- migration it exercises the ACTUAL migration backfill, loaded from its unique--- CLI-generated file; no copied implementation or embedded COMMIT is executed.--- All fixtures use new IDs and the outer transaction always rolls back. A failed--- assertion terminates psql, which also rolls back the open transaction.--\set ON_ERROR_STOP on-BEGIN;-SET LOCAL "app.sync_in_progress" = 'true';-SET LOCAL statement_timeout = '30s';--DO $contract$-BEGIN- ASSERT EXISTS (- SELECT 1 FROM information_schema.columns WHERE table_schema = 'public'- AND table_name = 'accountDefault' AND column_name = 'salesShippingRevenueAccount'- ), 'Schema contract: accountDefault.salesShippingRevenueAccount is missing';- ASSERT (- SELECT count(*) = 2 FROM information_schema.columns WHERE table_schema = 'public'- AND table_name = 'invoiceSettlement' AND column_name IN ('sourcePaymentId', 'sourceAmount')- ), 'Schema contract: invoiceSettlement funding columns are missing';- ASSERT (- SELECT is_generated = 'NEVER' FROM information_schema.columns- WHERE table_schema = 'public' AND table_name = 'invoiceSettlement'- AND column_name = 'fxGainLossAmount'- ), 'Schema contract: fxGainLossAmount must be a server-written snapshot';-END;-$contract$;--CREATE TEMP TABLE accounting_backfill_sql (body text NOT NULL) ON COMMIT DROP;--- Python runs locally through psql, reads only a repository file, and emits one--- CSV field so newlines/quotes survive unchanged. The boundaries deliberately--- exclude all schema DDL and the migration's outer BEGIN/COMMIT.-\copy accounting_backfill_sql FROM PROGRAM 'python3 -c "from pathlib import Path; import csv,sys; paths=list(Path(\"packages/database/supabase/migrations\").glob(\"*_accounting_posting_corrections.sql\")); assert len(paths)==1, \"Expected exactly one accounting posting migration\"; sql=paths[0].read_text(); start=sql.index(\"-- Serialize chart/default resolution\"); end=sql.index(\"COMMENT ON COLUMN\",start); csv.writer(sys.stdout).writerow([sql[start:end]])"' WITH (FORMAT csv)--CREATE FUNCTION pg_temp.run_shipping_backfill() RETURNS void LANGUAGE plpgsql AS $fn$-DECLARE body text;-BEGIN- SELECT s.body INTO STRICT body FROM accounting_backfill_sql s;- -- A real migration commit drops this temporary resolution table. Removing- -- only that scratch table models a fresh retry inside our rollback harness.- DROP TABLE IF EXISTS pg_temp.accounting_shipping_resolution;- EXECUTE body;-END;-$fn$;--CREATE TYPE pg_temp.shipping_fixture AS (- group_id text, company_ids text[], parent_id text, sales_id text-);--CREATE FUNCTION pg_temp.seed_shipping_chart(p_companies integer DEFAULT 1)-RETURNS pg_temp.shipping_fixture LANGUAGE plpgsql AS $fn$-DECLARE- f pg_temp.shipping_fixture;- defaults_json jsonb;-BEGIN- ASSERT p_companies > 0, 'Fixture needs a company';- INSERT INTO "companyGroup" (name, "createdBy")- VALUES ('Shipping harness ' || id(), 'system') RETURNING id INTO f.group_id;- WITH inserted AS (- INSERT INTO "company" (id, name, "companyGroupId", "baseCurrencyCode")- SELECT id(), 'Shipping harness company ' || id(), f.group_id, 'USD'- FROM generate_series(1, p_companies)- RETURNING id- ) SELECT array_agg(id ORDER BY id) INTO f.company_ids FROM inserted;-- INSERT INTO "account" (name, class, "accountType", "incomeBalance", "consolidatedRate",- "isGroup", "companyGroupId", "createdBy")- VALUES ('Revenue', 'Revenue', 'Income', 'Income Statement', 'Average', true,- f.group_id, 'system') RETURNING id INTO f.parent_id;- INSERT INTO "account" (number, name, class, "accountType", "incomeBalance", "consolidatedRate",- "parentId", "companyGroupId", "createdBy")- VALUES ('4010', 'Sales', 'Revenue', 'Income', 'Income Statement', 'Average',- f.parent_id, f.group_id, 'system') RETURNING id INTO f.sales_id;-- -- Unrelated mandatory defaults only need a valid fixture-owned FK; none is- -- posted by these schema/backfill tests. Derive the mandatory columns from the- -- current schema so adding an unrelated default does not require fake seed data.- SELECT jsonb_object_agg(attname, to_jsonb(f.sales_id)) INTO defaults_json- FROM pg_attribute WHERE attrelid = '"accountDefault"'::regclass- AND attnum > 0 AND NOT attisdropped AND attnotnull AND attname <> 'companyId';- INSERT INTO "accountDefault"- SELECT (jsonb_populate_record(NULL::"accountDefault",- defaults_json || jsonb_build_object('companyId', company_id))).*- FROM unnest(f.company_ids) AS company_id;- RETURN f;-END;-$fn$;--CREATE FUNCTION pg_temp.add_revenue_leaf(f pg_temp.shipping_fixture, p_name text, p_number text)-RETURNS text LANGUAGE plpgsql AS $fn$-DECLARE account_id text;-BEGIN- INSERT INTO "account" (number, name, class, "accountType", "incomeBalance", "consolidatedRate",- "parentId", "companyGroupId", "createdBy")- VALUES (p_number, p_name, 'Revenue', 'Income', 'Income Statement', 'Average',- f.parent_id, f.group_id, 'system') RETURNING id INTO account_id;- RETURN account_id;-END;-$fn$;--CREATE FUNCTION pg_temp.expect_backfill_failure(p_message text) RETURNS void LANGUAGE plpgsql AS $fn$-DECLARE actual_message text;-BEGIN- BEGIN- PERFORM pg_temp.run_shipping_backfill();- ASSERT false, 'Expected migration refusal: ' || p_message;- EXCEPTION WHEN raise_exception THEN- GET STACKED DIAGNOSTICS actual_message = MESSAGE_TEXT;- ASSERT position(p_message IN actual_message) > 0,- 'Wrong migration refusal: ' || actual_message;- END;-END;-$fn$;---- Preserve complete existing records, not just counts. Even while all writes--- roll back, the harness refuses to use or modify real company/account defaults.-CREATE TEMP TABLE accounting_original_accounts ON COMMIT DROP AS-SELECT id, to_jsonb(a) AS body FROM "account" a;-CREATE TEMP TABLE accounting_original_defaults ON COMMIT DROP AS-SELECT "companyId", to_jsonb(ad) AS body FROM "accountDefault" ad;--DO $backfill_cases$-DECLARE- f pg_temp.shipping_fixture;- good pg_temp.shipping_fixture;- shipping_id text;- custom_id text;- second_parent text;- before_accounts jsonb;- before_defaults jsonb;-BEGIN- -- A custom SQLSTATE unwinds each successful scenario's fixtures. Assertion- -- errors use P0004 and are never caught as successful test execution.- BEGIN- f := pg_temp.seed_shipping_chart(2);- PERFORM pg_temp.run_shipping_backfill();- SELECT "salesShippingRevenueAccount" INTO shipping_id FROM "accountDefault"- WHERE "companyId" = f.company_ids[1];- ASSERT shipping_id IS NOT NULL AND shipping_id <> f.sales_id, 'Fresh chart: separate shipping account';- ASSERT (SELECT number = '4050' AND name = 'Shipping Revenue' AND class = 'Revenue'- AND "accountType" = 'Income' AND "incomeBalance" = 'Income Statement'- AND "consolidatedRate" = 'Average' AND NOT "isGroup" AND active- AND "parentId" = f.parent_id AND "companyGroupId" = f.group_id- FROM "account" WHERE id = shipping_id), 'Fresh chart: complete revenue leaf under Revenue';- ASSERT (SELECT count(*) = 1 FROM "account" WHERE "companyGroupId" = f.group_id- AND name = 'Shipping Revenue'), 'Shared chart: exactly one shipping leaf';- ASSERT (SELECT bool_and("salesShippingRevenueAccount" = shipping_id)- FROM "accountDefault" WHERE "companyId" = ANY(f.company_ids)), 'Shared chart: same default for both companies';- SELECT jsonb_agg(to_jsonb(a) ORDER BY a.id) INTO before_accounts FROM "account" a WHERE "companyGroupId" = f.group_id;- SELECT jsonb_agg(to_jsonb(ad) ORDER BY "companyId") INTO before_defaults FROM "accountDefault" ad WHERE "companyId" = ANY(f.company_ids);- PERFORM pg_temp.run_shipping_backfill();- ASSERT (SELECT jsonb_agg(to_jsonb(a) ORDER BY a.id) FROM "account" a WHERE "companyGroupId" = f.group_id) = before_accounts,- 'Rerun must preserve all account records';- ASSERT (SELECT jsonb_agg(to_jsonb(ad) ORDER BY "companyId") FROM "accountDefault" ad WHERE "companyId" = ANY(f.company_ids)) = before_defaults,- 'Rerun must preserve defaults including timestamps';- RAISE NOTICE 'PASS fresh/shared chart and exact rerun preservation';- RAISE SQLSTATE 'P9001';- EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;-- BEGIN- f := pg_temp.seed_shipping_chart(2);- shipping_id := pg_temp.add_revenue_leaf(f, 'Shipping Revenue', '4897');- custom_id := pg_temp.add_revenue_leaf(f, 'Customer Freight Recovery', '4801');- UPDATE "accountDefault" SET "salesShippingRevenueAccount" = custom_id WHERE "companyId" = f.company_ids[1];- PERFORM pg_temp.run_shipping_backfill();- ASSERT (SELECT "salesShippingRevenueAccount" = custom_id FROM "accountDefault" WHERE "companyId" = f.company_ids[1]),- 'Populated custom shipping default must be preserved';- ASSERT (SELECT "salesShippingRevenueAccount" = shipping_id FROM "accountDefault" WHERE "companyId" = f.company_ids[2]),- 'Reuse existing custom-number Shipping Revenue leaf';- ASSERT (SELECT number = '4897' FROM "account" WHERE id = shipping_id), 'Reuse must not renumber shipping';- ASSERT (SELECT count(*) = 1 FROM "account" WHERE "companyGroupId" = f.group_id AND name = 'Shipping Revenue'),- 'Reuse must not duplicate shipping';- RAISE NOTICE 'PASS custom default and custom-number leaf preservation';- RAISE SQLSTATE 'P9001';- EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;-- BEGIN- f := pg_temp.seed_shipping_chart();- custom_id := pg_temp.add_revenue_leaf(f, 'Existing account at 4050', '4050');- PERFORM pg_temp.run_shipping_backfill();- ASSERT (SELECT number = '4060' FROM "account" WHERE "companyGroupId" = f.group_id AND name = 'Shipping Revenue'),- 'Occupied 4050: use next free account number';- ASSERT (SELECT number = '4050' AND name = 'Existing account at 4050' FROM "account" WHERE id = custom_id),- 'Occupied 4050: preserve its owner';- RAISE NOTICE 'PASS account-number collision';- RAISE SQLSTATE 'P9001';- EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;-- BEGIN- f := pg_temp.seed_shipping_chart();- INSERT INTO "account" (number, name, class, "accountType", "incomeBalance", "consolidatedRate",- "parentId", "companyGroupId", "createdBy")- SELECT n::text, 'Occupied ' || n, 'Revenue', 'Income', 'Income Statement', 'Average',- f.parent_id, f.group_id, 'system' FROM generate_series(4050, 4990, 10) AS n;- PERFORM pg_temp.expect_backfill_failure('Cannot resolve Shipping Revenue parent/account/number for groups: ' || f.group_id);- ASSERT NOT EXISTS (SELECT 1 FROM "account" WHERE "companyGroupId" = f.group_id AND name = 'Shipping Revenue'),- 'Exhausted range: do not insert an unnumbered shipping account';- RAISE NOTICE 'PASS exhausted number range rejected with group identity';- RAISE SQLSTATE 'P9001';- EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;-- BEGIN- f := pg_temp.seed_shipping_chart();- UPDATE "account" SET name = 'Operating Revenue' WHERE id = f.parent_id;- PERFORM pg_temp.run_shipping_backfill();- ASSERT (SELECT "parentId" = f.parent_id FROM "account" WHERE "companyGroupId" = f.group_id AND name = 'Shipping Revenue'),- 'Renamed Revenue group: use the unique compatible sales parent';- RAISE NOTICE 'PASS renamed parent resolution';- RAISE SQLSTATE 'P9001';- EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;-- BEGIN- f := pg_temp.seed_shipping_chart();- UPDATE "account" SET name = 'Operating Revenue' WHERE id = f.parent_id;- UPDATE "account" SET "parentId" = NULL WHERE id = f.sales_id;- PERFORM pg_temp.expect_backfill_failure('Cannot resolve Shipping Revenue');- RAISE NOTICE 'PASS missing compatible parent rejected';- RAISE SQLSTATE 'P9001';- EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;-- BEGIN- f := pg_temp.seed_shipping_chart(2);- UPDATE "account" SET name = 'Revenue A' WHERE id = f.parent_id;- INSERT INTO "account" (name, class, "accountType", "incomeBalance", "isGroup", "companyGroupId", "createdBy")- VALUES ('Revenue B', 'Revenue', 'Income', 'Income Statement', true, f.group_id, 'system') RETURNING id INTO second_parent;- custom_id := pg_temp.add_revenue_leaf(f, 'Other Sales', '4020');- UPDATE "account" SET "parentId" = second_parent WHERE id = custom_id;- UPDATE "accountDefault" SET "salesAccount" = custom_id WHERE "companyId" = f.company_ids[2];- PERFORM pg_temp.expect_backfill_failure('Cannot resolve Shipping Revenue');- ASSERT NOT EXISTS (SELECT 1 FROM "account" WHERE "companyGroupId" = f.group_id AND name = 'Shipping Revenue'),- 'Ambiguous parents: no orphaned/guessed shipping account';- RAISE NOTICE 'PASS ambiguous sales parents rejected';- RAISE SQLSTATE 'P9001';- EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;-- BEGIN- good := pg_temp.seed_shipping_chart();- f := pg_temp.seed_shipping_chart();- UPDATE "account" SET class = 'Expense' WHERE id = f.parent_id;- SELECT jsonb_agg(to_jsonb(a) ORDER BY a.id) INTO before_accounts FROM "account" a- WHERE "companyGroupId" IN (good.group_id, f.group_id);- SELECT jsonb_agg(to_jsonb(ad) ORDER BY "companyId") INTO before_defaults FROM "accountDefault" ad- WHERE "companyId" = ANY(good.company_ids || f.company_ids);- PERFORM pg_temp.expect_backfill_failure('Cannot resolve Shipping Revenue');- ASSERT (SELECT jsonb_agg(to_jsonb(a) ORDER BY a.id) FROM "account" a- WHERE "companyGroupId" IN (good.group_id, f.group_id)) = before_accounts,- 'One incompatible group must roll back all account changes';- ASSERT (SELECT jsonb_agg(to_jsonb(ad) ORDER BY "companyId") FROM "accountDefault" ad- WHERE "companyId" = ANY(good.company_ids || f.company_ids)) = before_defaults,- 'One incompatible group must roll back all default changes';- RAISE NOTICE 'PASS incompatible canonical parent and multi-group atomic failure';- RAISE SQLSTATE 'P9001';- EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;-- BEGIN- f := pg_temp.seed_shipping_chart();- INSERT INTO "account" (name, class, "accountType", "incomeBalance", "isGroup", "companyGroupId", "createdBy")- VALUES ('Shipping Revenue', 'Revenue', 'Income', 'Income Statement', true, f.group_id, 'system');- PERFORM pg_temp.expect_backfill_failure('Cannot resolve Shipping Revenue');- RAISE NOTICE 'PASS conflicting Shipping Revenue group rejected';- RAISE SQLSTATE 'P9001';- EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;-- BEGIN- f := pg_temp.seed_shipping_chart();- shipping_id := pg_temp.add_revenue_leaf(f, 'Shipping Revenue', '4897');- UPDATE "account" SET "parentId" = NULL WHERE id = shipping_id;- PERFORM pg_temp.expect_backfill_failure('Cannot resolve Shipping Revenue');- RAISE NOTICE 'PASS existing incompatible shipping leaf rejected';- RAISE SQLSTATE 'P9001';- EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;-- BEGIN- f := pg_temp.seed_shipping_chart();- UPDATE "account" SET name = 'Shipping Revenue' WHERE id = f.sales_id;- PERFORM pg_temp.expect_backfill_failure('Cannot resolve Shipping Revenue');- RAISE NOTICE 'PASS shipping candidate cannot equal the sales default';- RAISE SQLSTATE 'P9001';- EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;-- BEGIN- f := pg_temp.seed_shipping_chart();- UPDATE "accountDefault" SET "salesShippingRevenueAccount" = f.sales_id WHERE "companyId" = f.company_ids[1];- PERFORM pg_temp.expect_backfill_failure('Invalid shipping defaults');- RAISE NOTICE 'PASS populated shipping default cannot equal sales';- RAISE SQLSTATE 'P9001';- EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;-- BEGIN- f := pg_temp.seed_shipping_chart();- good := pg_temp.seed_shipping_chart();- custom_id := pg_temp.add_revenue_leaf(good, 'Other group freight', '4801');- UPDATE "accountDefault" SET "salesShippingRevenueAccount" = custom_id WHERE "companyId" = f.company_ids[1];- PERFORM pg_temp.expect_backfill_failure('Invalid shipping defaults for companies: ' || f.company_ids[1]);- RAISE NOTICE 'PASS cross-group shipping default rejected with company identity';- RAISE SQLSTATE 'P9001';- EXCEPTION WHEN SQLSTATE 'P9001' THEN NULL; END;-- ASSERT NOT EXISTS (SELECT 1 FROM accounting_original_accounts original- LEFT JOIN "account" a ON a.id = original.id WHERE to_jsonb(a) IS DISTINCT FROM original.body),- 'Harness must not alter any original accounts';- ASSERT NOT EXISTS (SELECT 1 FROM accounting_original_defaults original- LEFT JOIN "accountDefault" ad ON ad."companyId" = original."companyId" WHERE to_jsonb(ad) IS DISTINCT FROM original.body),- 'Harness must not alter any original defaults';-END;-$backfill_cases$;--ROLLBACK;diff --git a/packages/dev/AGENTS.md b/packages/dev/AGENTS.mdindex 231667597d..bfbadd3a79 100644--- a/packages/dev/AGENTS.md+++ b/packages/dev/AGENTS.md@@ -25,7 +25,7 @@ Developer CLI (`crbn` command) — worktree management, Docker Compose stacks, m```bashpnpm --filter @carbon/dev test # vitest-pnpm --filter @carbon/dev typecheck # tsgo --noEmit+pnpm --filter @carbon/dev typecheck # tsc --noEmitpnpm --filter @carbon/dev smoke # real containers: slots, fresh migrate, up, status, purge (~40 s, needs Docker; run from a worktree with no stack)```diff --git a/packages/dev/package.json b/packages/dev/package.jsonindex c6b6decdcb..1af19569b0 100644--- a/packages/dev/package.json+++ b/packages/dev/package.json@@ -15,7 +15,7 @@"lint": "biome lint --write","test": "vitest run","test:watch": "vitest",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"dependencies": {"@bomb.sh/tab": "^0.0.15",diff --git a/packages/dev/src/env.test.ts b/packages/dev/src/env.test.tsindex f483efce0b..246bdc16e0 100644--- a/packages/dev/src/env.test.ts+++ b/packages/dev/src/env.test.ts@@ -24,187 +24,73 @@ const jwt: JwtCreds = {serviceKey: "test-service-key"};-describe("renderEnv (portless disabled)", () => {- it("emits localhost URLs for app and supabase", () => {- const out = renderEnv({- slug: "feat-x",- ports,- redisDb: 3,- jwt,- portless: false- });- expect(out).toContain("CARBON_WORKTREE=feat-x");- expect(out).toContain("ERP_URL=http://localhost:54005");- expect(out).toContain("MES_URL=http://localhost:54006");- expect(out).toContain("SUPABASE_URL=http://localhost:54001");- expect(out).toContain(- "ONSHAPE_V2_OAUTH_REDIRECT_URL=http://localhost:54005/api/integrations/onshape-v2/oauth"- );- expect(out).not.toContain("PORTLESS_TLD");- });-- it("writes the assembler URL by default, omits it when deselected", () => {- const base = { slug: "s", ports, redisDb: 0, jwt, portless: false };- const withAssembler = renderEnv(base);- expect(withAssembler).toContain(- "ASSEMBLER_SERVICE_URL=http://localhost:54007"- );- expect(withAssembler).toContain("ASSEMBLER_SERVICE_API_KEY=dev-local-key");- // ASSEMBLER_SERVICE_URL is the pipeline's feature flag — when the app- // wasn't selected, the URL must be absent so jobs skip cleanly instead of- // failing against a dead endpoint.- const without = renderEnv({ ...base, includeAssembler: false });- expect(without).not.toContain("ASSEMBLER_SERVICE_URL=");- expect(without).not.toContain("ASSEMBLER_SERVICE_API_KEY=");- });-- it("wires every port into env vars", () => {- const out = renderEnv({- slug: "s",- ports,- redisDb: 0,- jwt,- portless: false- });- expect(out).toContain("PORT_DB=54000");- expect(out).toContain("PORT_API=54001");- expect(out).toContain("PORT_STUDIO=54002");- expect(out).toContain("PORT_INBUCKET=54003");- expect(out).toContain("PORT_INNGEST=54004");- expect(out).toContain("PORT_ERP=54005");- expect(out).toContain("PORT_MES=54006");- expect(out).toContain("PORT_EMAIL=54008");- expect(out).toContain("EMAIL_DEV_PORT=54008");+const base = (overrides: Partial<Parameters<typeof renderEnv>[0]> = {}) =>+ renderEnv({+ slug: "s",+ ports,+ redisDb: 0,+ jwt,+ portless: false,+ ...overrides});- it("places redis db index in REDIS_URL", () => {- const out = renderEnv({- slug: "s",- ports,- redisDb: 7,- jwt,- portless: false- });- expect(out).toMatch(/REDIS_URL=redis:\/\/localhost:\d+\/7/);- });-- it("injects jwt creds verbatim", () => {- const out = renderEnv({- slug: "s",- ports,- redisDb: 0,- jwt,- portless: false- });- expect(out).toContain("SUPABASE_JWT_SECRET=test-secret");- expect(out).toContain("SUPABASE_ANON_KEY=test-anon-key");- expect(out).toContain("SUPABASE_SERVICE_ROLE_KEY=test-service-key");- });-- it("ends with a trailing newline", () => {- const out = renderEnv({- slug: "s",- ports,- redisDb: 0,- jwt,- portless: false- });- expect(out.endsWith("\n")).toBe(true);- });-});--describe("ONSHAPE_V2_OAUTH_REDIRECT_URL #force", () => {- it("leaves a redirect URL pinned in .env to .env", () => {- const out = renderEnv({- slug: "s",- ports,- redisDb: 0,- jwt,- portless: false- });- const dotEnv =- 'ONSHAPE_V2_OAUTH_REDIRECT_URL="https://tunnel.example/api/integrations/onshape-v2/oauth" #force';- expect(omitForcedKeys(out, dotEnv)).not.toContain(- "ONSHAPE_V2_OAUTH_REDIRECT_URL=http://localhost"- );- });-});--describe("renderEnv (portless enabled)", () => {- it("emits portless hostnames for app and supabase", () => {- const out = renderEnv({- slug: "feat-x",- ports,- redisDb: 3,- jwt,+describe("renderEnv", () => {+ it.each([+ {+ portless: false,+ expected: [+ "ERP_URL=http://localhost:54005",+ "MES_URL=http://localhost:54006",+ "SUPABASE_URL=http://localhost:54001",+ "ONSHAPE_V2_OAUTH_REDIRECT_URL=http://localhost:54005/api/integrations/onshape-v2/oauth"+ ]+ },+ {portless: true,- branchPrefix: "feat-x"- });+ expected: [+ "ERP_URL=https://erp.feat-x.dev",+ "MES_URL=https://mes.feat-x.dev",+ "SUPABASE_URL=https://api.feat-x.dev",+ "ONSHAPE_V2_OAUTH_REDIRECT_URL=https://erp.feat-x.dev/api/integrations/onshape-v2/oauth",+ "PORTLESS_TLD=dev"+ ]+ }+ ])("writes the app URLs for portless=$portless", ({ portless, expected }) => {+ const out = base({ slug: "feat-x", portless, branchPrefix: "feat-x" });expect(out).toContain("CARBON_WORKTREE=feat-x");- expect(out).toContain("ERP_URL=https://erp.feat-x.dev");- expect(out).toContain("MES_URL=https://mes.feat-x.dev");- expect(out).toContain("SUPABASE_URL=https://api.feat-x.dev");- expect(out).toContain(- "ONSHAPE_V2_OAUTH_REDIRECT_URL=https://erp.feat-x.dev/api/integrations/onshape-v2/oauth"- );- expect(out).toContain("PORTLESS_TLD=dev");+ for (const line of expected) expect(out).toContain(line);+ if (!portless) expect(out).not.toContain("PORTLESS_TLD");});- it("wires every port into env vars", () => {- const out = renderEnv({- slug: "s",- ports,- redisDb: 0,- jwt,- portless: true,- branchPrefix: "s"- });- expect(out).toContain("PORT_DB=54000");- expect(out).toContain("PORT_API=54001");- expect(out).toContain("PORT_STUDIO=54002");- expect(out).toContain("PORT_INBUCKET=54003");- expect(out).toContain("PORT_INNGEST=54004");- expect(out).toContain("PORT_ERP=54005");- expect(out).toContain("PORT_MES=54006");- expect(out).toContain("PORT_EMAIL=54008");- expect(out).toContain("EMAIL_DEV_PORT=54008");+ it("writes the assembler URL by default, omits it when deselected", () => {+ expect(base()).toContain("ASSEMBLER_SERVICE_URL=http://localhost:54007");+ expect(base()).toContain("ASSEMBLER_SERVICE_API_KEY=dev-local-key");+ // ASSEMBLER_SERVICE_URL is the pipeline's feature flag: with the app+ // deselected, jobs must skip cleanly instead of calling a dead endpoint.+ const without = base({ includeAssembler: false });+ expect(without).not.toContain("ASSEMBLER_SERVICE_URL=");+ expect(without).not.toContain("ASSEMBLER_SERVICE_API_KEY=");});- it("places redis db index in REDIS_URL", () => {- const out = renderEnv({- slug: "s",- ports,- redisDb: 7,- jwt,- portless: true,- branchPrefix: "s"- });+ it("wires ports, the redis db, and the jwt creds in verbatim, ending with a newline", () => {+ const out = base({ redisDb: 7 });+ for (const line of [+ "PORT_DB=54000",+ "PORT_API=54001",+ "PORT_STUDIO=54002",+ "PORT_INBUCKET=54003",+ "PORT_INNGEST=54004",+ "PORT_ERP=54005",+ "PORT_MES=54006",+ "PORT_EMAIL=54008",+ "EMAIL_DEV_PORT=54008",+ "SUPABASE_JWT_SECRET=test-secret",+ "SUPABASE_ANON_KEY=test-anon-key",+ "SUPABASE_SERVICE_ROLE_KEY=test-service-key"+ ]) {+ expect(out).toContain(line);+ }expect(out).toMatch(/REDIS_URL=redis:\/\/localhost:\d+\/7/);- });-- it("injects jwt creds verbatim", () => {- const out = renderEnv({- slug: "s",- ports,- redisDb: 0,- jwt,- portless: true,- branchPrefix: "s"- });- expect(out).toContain("SUPABASE_JWT_SECRET=test-secret");- expect(out).toContain("SUPABASE_ANON_KEY=test-anon-key");- expect(out).toContain("SUPABASE_SERVICE_ROLE_KEY=test-service-key");- });-- it("ends with a trailing newline", () => {- const out = renderEnv({- slug: "s",- ports,- redisDb: 0,- jwt,- portless: true,- branchPrefix: "s"- });expect(out.endsWith("\n")).toBe(true);});});@@ -215,11 +101,16 @@ describe("#force escape hatch", () => {"OPENAI_API_KEY=sk-123","ASSEMBLER_SERVICE_URL=https://xxx.execute-api.us-east-1.amazonaws.com #force","ASSEMBLER_SERVICE_API_KEY=abc # FORCE",+ 'ONSHAPE_V2_OAUTH_REDIRECT_URL="https://tunnel.example/oauth" #force',"# a comment mentioning force","NOT_FORCED=1 # forceful suffix means nothing"].join("\n");expect(forcedKeys(dotEnv)).toEqual(- new Set(["ASSEMBLER_SERVICE_URL", "ASSEMBLER_SERVICE_API_KEY"])+ new Set([+ "ASSEMBLER_SERVICE_URL",+ "ASSEMBLER_SERVICE_API_KEY",+ "ONSHAPE_V2_OAUTH_REDIRECT_URL"+ ]));});@@ -232,10 +123,9 @@ describe("#force escape hatch", () => {const out = omitForcedKeys(content, dotEnv);expect(out).not.toContain("ASSEMBLER_SERVICE_URL=");expect(out).toContain("ASSEMBLER_SERVICE_API_KEY=dev-local-key");- expect(out).toContain("omitted");});- it("no markers -> content untouched", () => {+ it("leaves the content untouched when nothing is forced", () => {const content = "A=1\nB=2";expect(omitForcedKeys(content, "A=1\nB=2")).toBe(content);});diff --git a/packages/documents/AGENTS.md b/packages/documents/AGENTS.mdindex 857a3956f1..81303b836f 100644--- a/packages/documents/AGENTS.md+++ b/packages/documents/AGENTS.md@@ -26,7 +26,7 @@ PDF generation, email templates, ZPL labels, and QR/barcode utilities.```bashpnpm --filter @carbon/documents test # vitest-pnpm --filter @carbon/documents typecheck # tsgo --noEmit+pnpm --filter @carbon/documents typecheck # tsc --noEmitpnpm --filter @carbon/documents build # generates fonts.data.ts```diff --git a/packages/documents/package.json b/packages/documents/package.jsonindex a606134384..764ac39b73 100644--- a/packages/documents/package.json+++ b/packages/documents/package.json@@ -5,22 +5,18 @@"@carbon/env": "workspace:*","@carbon/files": "workspace:*","@carbon/notifications": "workspace:*",- "@carbon/react": "workspace:*","@carbon/utils": "workspace:*",- "@hookform/resolvers": "3.10.0",- "react-email": "catalog:",+ "@internationalized/date": "catalog:","@react-pdf/renderer": "catalog:",- "cookie": "catalog:",- "dompurify": "catalog:",- "nanoid": "catalog:",- "react-icons": "catalog:",+ "react": "catalog:",+ "react-email": "catalog:","react-pdf-tailwind": "2.3.0",- "sst": "catalog:","zod": "catalog:"},"devDependencies": {"@carbon/config": "workspace:*","@carbon/database": "workspace:*",+ "@carbon/react": "workspace:*","@fontsource/inter": "^5.0.0","@fontsource/lato": "^5.0.0","@fontsource/lora": "^5.0.0",@@ -29,13 +25,17 @@"@fontsource/open-sans": "^5.0.0","@fontsource/playfair-display": "^5.0.0","@fontsource/roboto": "^5.0.0",- "@internationalized/date": "catalog:",+ "@hookform/resolvers": "3.10.0","@react-email/ui": "6.11.3","@testing-library/dom": "8.20.1","@types/dompurify": "2.4.0","@types/react": "catalog:",+ "cookie": "catalog:",+ "dompurify": "catalog:",+ "nanoid": "catalog:","postcss": "8.5.29",- "react": "catalog:",+ "react-icons": "catalog:",+ "sst": "catalog:","tsup": "catalog:","typescript": "catalog:","vitest": "catalog:"@@ -56,7 +56,7 @@"email:previews": "node ./scripts/email-dev.mjs ./src/email/previews","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"sideEffects": false,"version": "0.0.0"diff --git a/packages/documents/src/template/template.test.ts b/packages/documents/src/template/template.test.tsindex 5199696a34..f315314bbb 100644--- a/packages/documents/src/template/template.test.ts+++ b/packages/documents/src/template/template.test.ts@@ -4,7 +4,6 @@import { describe, expect, it } from "vitest";import {- ADDABLE_BLOCK_TYPES,BLOCK_META,DEFAULT_SALES_INVOICE_TEMPLATE,documentThemeColors,@@ -90,26 +89,9 @@ describe("block metadata invariants", () => {expect(BLOCK_META[type].removable).toBe(false);}});-- it("only exposes extension blocks in the add menu", () => {- expect(ADDABLE_BLOCK_TYPES).toEqual(["richText", "keyValue", "spacer"]);- for (const type of ADDABLE_BLOCK_TYPES) {- expect(BLOCK_META[type].isBuiltIn).toBe(false);- expect(BLOCK_META[type].removable).toBe(true);- }- });});describe("document settings", () => {- it("includes default settings on the default template", () => {- expect(DEFAULT_SALES_INVOICE_TEMPLATE.settings).toEqual({- fontFamily: "Inter",- showPageNumbers: true,- pageNumberFormat: "pageOfTotal",- showRegistrationLine: true- });- });-it("merges a partial stored settings over defaults", () => {const { settings } = resolveTemplate("salesInvoice", {blocks: [{ id: "summary", type: "summary", visible: true }],@@ -159,8 +141,9 @@ describe("schema validation", () => {expect(() => blockSchema.parse({ id: "x", type: "bogus" })).toThrow();});- it("validates a full template document", () => {- const parsed = documentTemplateSchema.parse(DEFAULT_SALES_INVOICE_TEMPLATE);- expect(parsed.blocks).toHaveLength(7);+ it("accepts the default template unchanged", () => {+ expect(+ documentTemplateSchema.parse(DEFAULT_SALES_INVOICE_TEMPLATE)+ ).toEqual(DEFAULT_SALES_INVOICE_TEMPLATE);});});diff --git a/packages/documents/src/utils/purchase-order.test.ts b/packages/documents/src/utils/purchase-order.test.tsindex 80c2bdcc33..84c3d42d0d 100644--- a/packages/documents/src/utils/purchase-order.test.ts+++ b/packages/documents/src/utils/purchase-order.test.ts@@ -4,10 +4,7 @@import type { Database } from "@carbon/database";import { describe, expect, it } from "vitest";-import {- getLineDescription,- getPurchaseOrderDisplayId-} from "./purchase-order";+import { getLineDescription } from "./purchase-order";type Line = Database["public"]["Views"]["purchaseOrderLines"]["Row"];const line = (overrides: Partial<Line>) =>@@ -60,20 +57,3 @@ describe("getLineDescription", () => {).toBe("SUP-778");});});--// Suffix rules live in revision.test.ts; this pins field mapping only.-describe("getPurchaseOrderDisplayId", () => {- it("reads purchaseOrderId and revisionId off the order", () => {- expect(- getPurchaseOrderDisplayId({ purchaseOrderId: "PO-001042", revisionId: 0 })- ).toBe("PO-001042");- expect(- getPurchaseOrderDisplayId({ purchaseOrderId: "PO-001042", revisionId: 2 })- ).toBe("PO-001042-2");- });-- it("returns an empty string for a missing order", () => {- expect(getPurchaseOrderDisplayId(undefined)).toBe("");- expect(getPurchaseOrderDisplayId(null)).toBe("");- });-});diff --git a/packages/documents/src/utils/quote.test.ts b/packages/documents/src/utils/quote.test.tsdeleted file mode 100644index 072b4ab0b4..0000000000--- a/packages/documents/src/utils/quote.test.ts+++ /dev/null@@ -1,23 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { describe, expect, it } from "vitest";-import { getQuoteDisplayId } from "./quote";--// Suffix rules live in revision.test.ts; this pins field mapping only.-describe("getQuoteDisplayId", () => {- it("reads quoteId and revisionId off the quote", () => {- expect(getQuoteDisplayId({ quoteId: "Q000001", revisionId: 0 })).toBe(- "Q000001"- );- expect(getQuoteDisplayId({ quoteId: "Q000001", revisionId: 2 })).toBe(- "Q000001-2"- );- });-- it("returns an empty string for a missing quote", () => {- expect(getQuoteDisplayId(undefined)).toBe("");- expect(getQuoteDisplayId(null)).toBe("");- });-});diff --git a/packages/ee/package.json b/packages/ee/package.jsonindex 6a9e0bd576..ee6e80251c 100644--- a/packages/ee/package.json+++ b/packages/ee/package.json@@ -66,12 +66,13 @@"dev": "tsup src/index.ts --format esm,cjs --watch --dts --external react","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"dependencies": {"@ai-sdk/openai": "catalog:","@carbon/api": "workspace:*","@carbon/auth": "workspace:*",+ "@carbon/content": "workspace:*","@carbon/database": "workspace:*","@carbon/env": "workspace:*","@carbon/files": "workspace:*",@@ -87,36 +88,35 @@"@modelcontextprotocol/server": "2.3.1","@slack/bolt": "4.4.0","@slack/oauth": "3.0.5",- "@slack/types": "2.20.1","@slack/web-api": "catalog:",- "@supabase/supabase-js": "catalog:","ai": "catalog:","axios": "catalog:",- "cookie": "catalog:",- "dompurify": "catalog:","jose": "catalog:","kysely": "catalog:","nanoid": "catalog:","nodemailer": "10.0.6","react": "catalog:","react-icons": "catalog:",- "react-pdf": "catalog:","react-router": "catalog:",- "sst": "catalog:",- "supabase": "catalog:",- "tsup": "catalog:","zbsearch": "catalog:","zod": "catalog:","zod-form-data": "catalog:"},"devDependencies": {"@carbon/config": "workspace:*",- "@carbon/content": "workspace:*","@logtape/logtape": "catalog:","@logtape/testing": "catalog:","@modelcontextprotocol/client": "2.3.1",+ "@slack/types": "2.20.1",+ "@supabase/supabase-js": "catalog:","@types/nodemailer": "6.4.21","@types/react": "catalog:",+ "cookie": "catalog:",+ "dompurify": "catalog:",+ "react-pdf": "catalog:",+ "sst": "catalog:",+ "supabase": "catalog:",+ "tsup": "catalog:","typescript": "catalog:","vitest": "catalog:"}diff --git a/packages/ee/src/__tests__/provider-role.test.ts b/packages/ee/src/__tests__/provider-role.test.tsdeleted file mode 100644index f9afc47d82..0000000000--- a/packages/ee/src/__tests__/provider-role.test.ts+++ /dev/null@@ -1,78 +0,0 @@-// SPDX-License-Identifier: LicenseRef-Carbon-Commercial-// Carbon Enterprise file, licensed only under the Carbon Commercial License-// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.--import { readdirSync, readFileSync } from "node:fs";-import { join } from "node:path";-import { describe, expect, it } from "vitest";--/**- * `providerRole` is declared in TWO places by necessity: on the integration- * descriptor, where the application reads it, and on the `integration` table,- * where the `companyIntegration_single_active_role` trigger reads it. A- * descriptor declaring a role the migration never backfilled would pass every- * type check and then silently skip the exclusivity guard — the trigger returns- * early when the column is NULL, so the failure mode is "no enforcement", not- * an error.- *- * This reads the declarations out of SOURCE rather than importing them: the- * `@carbon/ee` barrel pulls `@carbon/auth`, which validates the full server env- * at import time, so no test can import it. Scanning the files is what is- * actually available, and it tests the thing that matters — what is declared- * versus what was backfilled.- */--const SRC = join(__dirname, "..");-const MIGRATION = join(- __dirname,- "../../../database/supabase/migrations/20260924133915_integration-provider-role.sql"-);--function declaredRoles(): Record<string, string> {- const roles: Record<string, string> = {};- for (const dir of readdirSync(SRC, { withFileTypes: true })) {- if (!dir.isDirectory()) continue;- for (const file of ["config.tsx", "config.ts"]) {- let source: string;- try {- source = readFileSync(join(SRC, dir.name, file), "utf8");- } catch {- continue;- }- const role = source.match(/providerRole:\s*"(accounting|spend)"/);- const id = source.match(/\n\s*id:\s*"([^"]+)"/);- if (role?.[1] && id?.[1]) roles[id[1]] = role[1];- }- }- return roles;-}--function backfilledRoles(): Record<string, string> {- const sql = readFileSync(MIGRATION, "utf8");- const roles: Record<string, string> = {};- for (const stmt of sql.split(/UPDATE\s+"integration"\s+SET/i).slice(1)) {- const role = stmt.match(/"providerRole"\s*=\s*'(accounting|spend)'/);- if (!role?.[1]) continue;- for (const m of stmt.slice(0, stmt.indexOf(";")).matchAll(/'([a-z-]+)'/g)) {- if (m[1] && m[1] !== role[1]) roles[m[1]] = role[1];- }- }- return roles;-}--describe("providerRole", () => {- it("declares a role for at least the four providers", () => {- const declared = declaredRoles();- expect(declared).toEqual({- xero: "accounting",- quickbooks: "accounting",- rillet: "accounting",- ramp: "spend"- });- });-- it("matches what the migration backfilled onto the registry", () => {- // If these diverge, the trigger silently does not guard the new provider.- expect(declaredRoles()).toEqual(backfilledRoles());- });-});diff --git a/packages/ee/src/accounting/core/card-charge-source.test.ts b/packages/ee/src/accounting/core/card-charge-source.test.tsindex e2021e4ae8..d6e778b0c9 100644--- a/packages/ee/src/accounting/core/card-charge-source.test.ts+++ b/packages/ee/src/accounting/core/card-charge-source.test.ts@@ -4,169 +4,33 @@import { parseAbsolute } from "@internationalized/date";import { describe, expect, it } from "vitest";-import { QboChargeSyncer } from "../providers/quickbooks-online/entities/charge";-import { RilletChargeSyncer } from "../providers/rillet/entities/charge";-import { XeroChargeSyncer } from "../providers/xero/entities/charge";+import { chargeLineDescription, sourceTimestamp } from "./card-charge-source";-describe.each([- ["quickbooks", QboChargeSyncer],- ["xero", XeroChargeSyncer],- ["rillet", RilletChargeSyncer]-] as const)("%s card source", (providerId, Syncer) => {- it("fetches charge headers and supplier mappings in one tenant-scoped query", async () => {- const reads: string[] = [];- const filters: unknown[][] = [];- const rows = ["a", "b"].map((id) => ({- id,- companyId: "company-1",- chargeId: id,- type: "Charge",- status: "Posted",- supplierId: `supplier-${id}`,- supplierExternalId: `remote-${id}`,- merchantName: null,- memo: null,- updatedAt: parseAbsolute("2026-09-09T00:00:00Z", "UTC").toDate()- }));- const database = {- selectFrom(table: string) {- reads.push(table);- const builder = {- select: () => builder,- leftJoin: (_table: string, join: (builder: unknown) => unknown) => {- const clause = {- onRef: (...args: unknown[]) => {- filters.push(args);- return clause;- },- on: (...args: unknown[]) => {- filters.push(args);- return clause;- }- };- join(clause);- return builder;- },- where: (...args: unknown[]) => {- filters.push(args);- return builder;- },- execute: async () => rows,- executeTakeFirst: async () => ({ externalId: "remote" })- };- return builder;- }- };- const syncer = new Syncer({- database: database as never,- companyId: "company-1",- provider: { id: providerId } as never,- entityType: "charge",- config: {- enabled: true,- direction: "push-to-accounting",- owner: "carbon"- }- });- const result = await (- syncer as unknown as {- fetchLocalBatch(- ids: string[]- ): Promise<- Map<- string,- { supplierExternalId: string | null; updatedAt: string | null }- >- >;- }- ).fetchLocalBatch(["a", "b"]);- expect(reads).toHaveLength(1);- expect(filters).toContainEqual(["charge.companyId", "=", "company-1"]);- expect(filters).toContainEqual([- "mapping.companyId",- "=",- "charge.companyId"- ]);- expect(filters).toContainEqual(["mapping.integration", "=", providerId]);- expect(result.get("a")?.supplierExternalId).toBe("remote-a");- expect(result.get("a")?.updatedAt).toBe("2026-09-09T00:00:00.000Z");+// node-postgres hands back a Date although the generated types say string.+describe("sourceTimestamp", () => {+ it("turns a driver Date into an ISO instant", () => {+ const value = parseAbsolute("2026-09-09T00:00:00Z", "UTC").toDate();+ expect(sourceTimestamp(value)).toBe("2026-09-09T00:00:00.000Z");});-});-describe.each([- ["quickbooks", QboChargeSyncer],- ["xero", XeroChargeSyncer]-] as const)("%s charge batch source", (providerId, Syncer) => {- it("reads multi-ID card sources and charge mappings once through the real batch entry point", async () => {- const reads: string[] = [];- const filters: unknown[][] = [];- const database = {- selectFrom(table: string) {- reads.push(table);- const query = {- select: () => query,- selectAll: () => query,- leftJoin: (_table: string, join: (clause: unknown) => unknown) => {- const clause = { onRef: () => clause, on: () => clause };- join(clause);- return query;- },- where: (...args: unknown[]) => {- filters.push(args);- return query;- },- execute: async () =>- table === "charge"- ? ["a", "b"].map((id) => ({- id,- companyId: "company-1",- chargeId: id,- type: "Charge",- status: "Posted",- supplierId: `supplier-${id}`,- supplierExternalId: `remote-${id}`,- merchantName: null,- memo: null,- updatedAt: "2026-09-09T00:00:00Z"- }))- : ["a", "b"].map((entityId) => ({- entityId,- externalId: `remote-${entityId}`,- lastSyncedAt: parseAbsolute(- "2026-09-10T00:00:00Z",- "UTC"- ).toDate()- })),- executeTakeFirst: async () => ({- externalId: "remote",- lastSyncedAt: "2026-09-10T00:00:00Z"- })- };- return query;- }- };- const syncer = new Syncer({- database: database as never,- companyId: "company-1",- provider: { id: providerId } as never,- entityType: "charge",- config: {- enabled: true,- direction: "push-to-accounting",- owner: "carbon"- }- });- const result = await syncer.pushBatchToAccounting(["a", "b"]);- expect(result.results.map((item) => item.status)).toEqual([- "skipped",- "skipped"- ]);- expect(reads.filter((table) => table === "charge")).toHaveLength(1);- expect(- reads.filter((table) => table === "externalIntegrationMapping")- ).toHaveLength(1);- expect(filters).toContainEqual(["entityId", "in", ["a", "b"]]);- expect(filters).toContainEqual(["companyId", "=", "company-1"]);- expect(filters).toContainEqual(["integration", "=", providerId]);+ it.each(["2026-09-09T00:00:00Z", null])("passes %s through", (value) => {+ expect(sourceTimestamp(value)).toBe(value);});});++// Card spend shares one catch-all vendor, so the merchant must lead the line.+describe("chargeLineDescription", () => {+ it.each([+ ["Acme Fuel", "Airfare", "memo", "Acme Fuel"],+ [null, "Airfare", "memo", "Airfare"],+ [null, null, "memo", "memo"],+ [null, null, null, undefined]+ ])(+ "merchant %s, line %s, memo %s → %s",+ (merchantName, description, memo, expected) => {+ expect(+ chargeLineDescription({ merchantName, memo }, { description })+ ).toBe(expected);+ }+ );+});diff --git a/packages/ee/src/accounting/core/card-charge-source.ts b/packages/ee/src/accounting/core/card-charge-source.tsindex 24629552d8..3f3e5cc9ae 100644--- a/packages/ee/src/accounting/core/card-charge-source.ts+++ b/packages/ee/src/accounting/core/card-charge-source.ts@@ -25,7 +25,7 @@ export type CardChargeSource = {};/** node-postgres returns Date objects although generated DB types say string. */-function sourceTimestamp(value: string | Date | null): string | null {+export function sourceTimestamp(value: string | Date | null): string | null {return value instanceof Date? fromDate(value, "UTC").toAbsoluteString(): value;diff --git a/packages/ee/src/accounting/core/fake-database-test-fixture.ts b/packages/ee/src/accounting/core/fake-database-test-fixture.tsnew file mode 100644index 0000000000..9557741af3--- /dev/null+++ b/packages/ee/src/accounting/core/fake-database-test-fixture.ts@@ -0,0 +1,250 @@+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial+// Carbon Enterprise file, licensed only under the Carbon Commercial License+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.++import { ACCOUNT_MAPPING_ENTITY_TYPE } from "./account-mapping";++/**+ * An in-memory stand-in for the Kysely database the accounting syncers take.+ * It keeps rows per table, applies `where` filters, upserts on the conflict+ * columns, and runs `transaction()` (and the raw `SET LOCAL` inside+ * `withTriggersDisabled`) against the same rows, so a test seeds rows and+ * asserts the rows a push left behind. Joins are ignored and `orderBy` is a+ * no-op: it serves the single-table reads and writes the syncers make.+ */++type Row = Record<string, unknown>;+type Filter = (row: Row) => boolean;++/** "m.entityId" → "entityId"; "a.number as accountNumber" → [number, accountNumber]. */+const column = (ref: string) => ref.split(".").pop() as string;+function projection(ref: string): [string, string] {+ const [source, alias] = ref.split(/\s+as\s+/i) as [string, string?];+ return [column(source), alias ?? column(source)];+}++export type FakeDatabase = ReturnType<typeof fakeDatabase>;++export function fakeDatabase(seed: Record<string, Row[]> = {}) {+ const tables: Record<string, Row[]> = {};+ for (const [table, rows] of Object.entries(seed))+ tables[table] = rows.map((row) => ({ ...row }));+ const failures: Record<string, Error[]> = {};+ let nextId = 0;++ // "externalIntegrationMapping as m" → "externalIntegrationMapping"+ const rowsOf = (table: string) =>+ (tables[table.split(/\s+as\s+/i)[0] as string] ??= []);++ /** Throws the next queued failure for a write to `table`, if any. */+ function guard(table: string) {+ const error = failures[table]?.shift();+ if (error) throw error;+ }++ function whereClause(filters: Filter[]) {+ return (ref: string, op: string, value: unknown) => {+ const key = column(ref);+ filters.push((row) => {+ const expected = typeof value === "function" ? subquery(value) : value;+ if (op === "in") return (expected as unknown[]).includes(row[key]);+ if (op === "is") return row[key] == null;+ if (op === "is not") return row[key] != null;+ if (op === "!=" || op === "<>") return row[key] !== expected;+ return row[key] === expected;+ });+ };+ }++ // `where("x", "=", (eb) => eb.selectFrom(...).select("c").where(...))`+ function subquery(build: unknown) {+ const query = (build as (eb: unknown) => { first(): unknown })({+ selectFrom: select+ });+ return query.first();+ }++ function select(table: string) {+ const filters: Filter[] = [];+ let columns: Array<[string, string]> | null = null;+ const matched = () =>+ rowsOf(table)+ .filter((row) => filters.every((f) => f(row)))+ .map((row) =>+ columns+ ? Object.fromEntries(columns.map(([from, to]) => [to, row[from]]))+ : { ...row }+ );+ const builder: any = {+ select(refs: string | string[]) {+ columns = [+ ...(columns ?? []),+ ...(Array.isArray(refs) ? refs : [refs]).map(projection)+ ];+ return builder;+ },+ selectAll: () => builder,+ leftJoin: () => builder,+ innerJoin: () => builder,+ orderBy: () => builder,+ limit: () => builder,+ where(ref: string, op: string, value: unknown) {+ whereClause(filters)(ref, op, value);+ return builder;+ },+ /** First selected value of the first row, for a scalar subquery. */+ first: () => {+ const row = matched()[0];+ return row ? Object.values(row)[0] : undefined;+ },+ execute: async () => matched(),+ executeTakeFirst: async () => matched()[0],+ executeTakeFirstOrThrow: async () => {+ const row = matched()[0];+ if (!row) throw new Error(`no ${table} row`);+ return row;+ }+ };+ return builder;+ }++ function insert(table: string) {+ let values: Row[] = [];+ let conflict: { columns: string[]; patch: Row | null } | null = null;+ const run = async () => {+ guard(table);+ const rows = rowsOf(table);+ return values.map((value) => {+ const existing = conflict+ ? rows.find((row) =>+ conflict!.columns.every((c) => row[c] === value[c])+ )+ : undefined;+ if (existing) {+ if (conflict?.patch) Object.assign(existing, conflict.patch);+ return existing;+ }+ const row = { id: `${table}-${++nextId}`, ...value };+ rows.push(row);+ return row;+ });+ };+ const builder: any = {+ values(value: Row | Row[]) {+ values = Array.isArray(value) ? value : [value];+ return builder;+ },+ onConflict(build: (oc: unknown) => unknown) {+ const target = (columns: string[]) => ({+ doUpdateSet(patch: Row) {+ conflict = { columns, patch };+ },+ doNothing() {+ conflict = { columns, patch: null };+ }+ });+ build({+ columns: target,+ column: (c: string) => target([c])+ });+ return builder;+ },+ returning: () => builder,+ returningAll: () => builder,+ execute: run,+ executeTakeFirst: async () => (await run())[0],+ executeTakeFirstOrThrow: async () => (await run())[0] as Row+ };+ return builder;+ }++ function update(table: string) {+ const filters: Filter[] = [];+ let patch: Row = {};+ const run = async () => {+ guard(table);+ const rows = rowsOf(table).filter((row) => filters.every((f) => f(row)));+ for (const row of rows) Object.assign(row, patch);+ return [{ numUpdatedRows: BigInt(rows.length) }];+ };+ const builder: any = {+ set(value: Row) {+ patch = value;+ return builder;+ },+ where(ref: string, op: string, value: unknown) {+ whereClause(filters)(ref, op, value);+ return builder;+ },+ returning: () => builder,+ execute: run,+ executeTakeFirst: async () => (await run())[0]+ };+ return builder;+ }++ function remove(table: string) {+ const filters: Filter[] = [];+ const builder: any = {+ where(ref: string, op: string, value: unknown) {+ whereClause(filters)(ref, op, value);+ return builder;+ },+ execute: async () => {+ guard(table);+ const rows = rowsOf(table);+ const kept = rows.filter((row) => !filters.every((f) => f(row)));+ const deleted = rows.length - kept.length;+ rows.splice(0, rows.length, ...kept);+ return [{ numDeletedRows: BigInt(deleted) }];+ }+ };+ return builder;+ }++ // What `sql\`…\`.execute(db)` needs: the raw statement is a no-op here.+ const executor = {+ transformQuery: (node: unknown) => node,+ compileQuery: (node: unknown) => ({ query: node, sql: "", parameters: [] }),+ executeQuery: async () => ({ rows: [] })+ };++ const database = {+ selectFrom: select,+ insertInto: insert,+ updateTable: update,+ deleteFrom: remove,+ getExecutor: () => executor,+ transaction: () => ({+ execute: <T>(operation: (tx: unknown) => Promise<T>) =>+ operation(database)+ })+ };++ return {+ /** Pass as the syncer's `database`. */+ database: database as never,+ /** The rows a table holds now. */+ rows: (table: string) => rowsOf(table),+ /** The next write to `table` throws `error`. */+ failNextWrite(table: string, error: Error) {+ (failures[table] ??= []).push(error);+ }+ };+}++/** Account-mapping rows: each Carbon account id → the provider's account code. */+export function accountMappingRows(+ codes: Record<string, string>,+ integration: string,+ companyId = "company-1"+): Row[] {+ return Object.entries(codes).map(([accountId, externalCode]) => ({+ entityType: ACCOUNT_MAPPING_ENTITY_TYPE,+ entityId: accountId,+ integration,+ companyId,+ externalId: `remote-${accountId}`,+ metadata: { externalCode }+ }));+}diff --git a/packages/ee/src/accounting/core/memo-party.test.ts b/packages/ee/src/accounting/core/memo-party.test.tsindex 687b079774..1383ec40a1 100644--- a/packages/ee/src/accounting/core/memo-party.test.ts+++ b/packages/ee/src/accounting/core/memo-party.test.ts@@ -7,301 +7,94 @@ import {type MemoPartyLookup,type MemoPartyRow,memoPartyFromRow,- resolveMemoJournalPartyFromClient,- resolveMemoJournalPartyFromDatabase,resolveMemoPartyFromLookup} from "./memo-party";/**- * A lookup over an in-memory world, recording which reads were made.- *- * `linesByJournalId` is the memo id a journal's OWN lines carry — only the- * ORIGINAL posting journal and its VOID journal have one, which is the whole- * point: `memoByJournalId` holds the `memo.journalId` pointer, and that names+ * A lookup over an in-memory world. `linesByJournalId` is the memo id a+ * journal's OWN lines carry (the original posting journal and its VOID both+ * have one); `memoByJournalId` is the `memo.journalId` pointer, which names* the original only.*/function makeLookup(world: {linesByJournalId?: Record<string, string>;memosById?: Record<string, MemoPartyRow>;memoByJournalId?: Record<string, MemoPartyRow>;-}) {- const reads: string[] = [];- const lookup: MemoPartyLookup = {- async findMemoIdOnJournalLines(journalId) {- reads.push(`lines:${journalId}`);- return world.linesByJournalId?.[journalId] ?? null;- },- async findMemoById(memoId) {- reads.push(`memoById:${memoId}`);- return world.memosById?.[memoId] ?? null;- },- async findMemoByJournalId(journalId) {- reads.push(`memoByJournalId:${journalId}`);- return world.memoByJournalId?.[journalId] ?? null;- }+}): MemoPartyLookup {+ return {+ findMemoIdOnJournalLines: async (journalId) =>+ world.linesByJournalId?.[journalId] ?? null,+ findMemoById: async (memoId) => world.memosById?.[memoId] ?? null,+ findMemoByJournalId: async (journalId) =>+ world.memoByJournalId?.[journalId] ?? null};- return { lookup, reads };}const customerMemo: MemoPartyRow = { customerId: "cust-1", supplierId: null };const supplierMemo: MemoPartyRow = { customerId: null, supplierId: "supp-1" };describe("memoPartyFromRow", () => {- it("reads the party off the memo, and answers null when it has neither", () => {- expect(memoPartyFromRow(customerMemo)).toBe("customer");- expect(memoPartyFromRow(supplierMemo)).toBe("supplier");- expect(memoPartyFromRow({ customerId: null, supplierId: null })).toBeNull();- expect(memoPartyFromRow(null)).toBeNull();+ it.each([+ [customerMemo, "customer"],+ [supplierMemo, "supplier"],+ [{ customerId: null, supplierId: null }, null],+ [null, null]+ ] as const)("reads the party off memo %o as %s", (row, party) => {+ expect(memoPartyFromRow(row)).toBe(party);});});describe("resolveMemoPartyFromLookup", () => {- // The regression. Voiding a memo INSERTS A NEW journal and leaves- // `memo.journalId` on the original, so a void resolves only through the- // journal LINES. Keying on `memo.journalId` alone answered null here, the- // policy parked MEMO_PARTY_UNRESOLVED, and in `journals` mode the void- // never reached the provider.- it("resolves a VOID memo journal for a customer memo", async () => {- const { lookup, reads } = makeLookup({- linesByJournalId: { "journal-void": "memo-1" },- memosById: { "memo-1": customerMemo },- // the pointer names the ORIGINAL journal, never the void- memoByJournalId: { "journal-original": customerMemo }- });-- expect(await resolveMemoPartyFromLookup(lookup, "journal-void")).toBe(- "customer"- );- expect(reads).toEqual(["lines:journal-void", "memoById:memo-1"]);- });-- it("resolves a VOID memo journal for a supplier memo", async () => {- const { lookup } = makeLookup({- linesByJournalId: { "journal-void": "memo-2" },- memosById: { "memo-2": supplierMemo },- memoByJournalId: { "journal-original": supplierMemo }- });-- expect(await resolveMemoPartyFromLookup(lookup, "journal-void")).toBe(- "supplier"- );- });+ // Voiding a memo INSERTS A NEW journal and leaves `memo.journalId` on the+ // original, so a void resolves only through the journal LINES.+ it.each([+ [customerMemo, "customer"],+ [supplierMemo, "supplier"]+ ] as const)(+ "resolves a VOID memo journal through its lines (%o → %s)",+ async (memo, party) => {+ const lookup = makeLookup({+ linesByJournalId: { "journal-void": "memo-1" },+ memosById: { "memo-1": memo },+ memoByJournalId: { "journal-original": memo }+ });+ expect(await resolveMemoPartyFromLookup(lookup, "journal-void")).toBe(+ party+ );+ }+ );- it("still resolves the ORIGINAL posting journal through its lines", async () => {- const { lookup, reads } = makeLookup({+ it("prefers the memo the lines name over the memo.journalId pointer", async () => {+ const lookup = makeLookup({linesByJournalId: { "journal-original": "memo-1" },memosById: { "memo-1": customerMemo },- memoByJournalId: { "journal-original": customerMemo }+ memoByJournalId: { "journal-original": supplierMemo }});-expect(await resolveMemoPartyFromLookup(lookup, "journal-original")).toBe("customer");- // The lines answer first; the `memo.journalId` read is never made.- expect(reads).toEqual(["lines:journal-original", "memoById:memo-1"]);});it("falls back to memo.journalId when the journal's lines carry no memo", async () => {- const { lookup, reads } = makeLookup({- linesByJournalId: {},+ const lookup = makeLookup({memoByJournalId: { "journal-original": supplierMemo }});-expect(await resolveMemoPartyFromLookup(lookup, "journal-original")).toBe("supplier");- expect(reads).toEqual([- "lines:journal-original",- "memoByJournalId:journal-original"- ]);});it("answers null when neither path finds a memo", async () => {- const { lookup } = makeLookup({});- expect(await resolveMemoPartyFromLookup(lookup, "journal-x")).toBeNull();+ expect(+ await resolveMemoPartyFromLookup(makeLookup({}), "journal-x")+ ).toBeNull();});- it("answers null for a memo whose lines resolve an id with no party", async () => {- const { lookup } = makeLookup({+ it("answers null when the lines name a memo with no party", async () => {+ const lookup = makeLookup({linesByJournalId: { "journal-void": "memo-3" },memosById: { "memo-3": { customerId: null, supplierId: null } }});expect(await resolveMemoPartyFromLookup(lookup, "journal-void")).toBeNull();});});--/**- * Minimal chainable Kysely mock. `selectFrom(...).select(...).where(...)*- * [.limit(1)].executeTakeFirst()` resolves from `rowsByTable`; `captured`- * records each query's table and `where` predicates for assertions.- */-function makeDatabase(rowsByTable: Record<string, unknown>) {- const captured: Array<Record<string, unknown>> = [];- const database: any = {- selectFrom(table: string) {- const query: Record<string, unknown> = { table };- captured.push(query);- const builder: any = {- select: () => builder,- where: (column: string, operator: string, value: unknown) => {- query[column] = operator === "=" ? value : `${operator} ${value}`;- return builder;- },- limit: (n: number) => {- query.limit = n;- return builder;- },- executeTakeFirst: async () => rowsByTable[table] ?? undefined- };- return builder;- }- };- return { database, captured };-}--describe("resolveMemoJournalPartyFromDatabase", () => {- it("scopes both reads by companyId and keys the lines read on documentType Memo", async () => {- const { database, captured } = makeDatabase({- journalLine: { documentId: "memo-1" },- memo: customerMemo- });-- expect(- await resolveMemoJournalPartyFromDatabase(database, {- companyId: "company-1",- journalId: "journal-void"- })- ).toBe("customer");-- expect(captured).toEqual([- {- table: "journalLine",- companyId: "company-1",- journalId: "journal-void",- documentType: "Memo",- documentId: "is not null",- limit: 1- },- { table: "memo", companyId: "company-1", id: "memo-1" }- ]);- });-- it("reads memo by journalId, still companyId-scoped, when no line carries a memo", async () => {- const { database, captured } = makeDatabase({ memo: supplierMemo });-- expect(- await resolveMemoJournalPartyFromDatabase(database, {- companyId: "company-1",- journalId: "journal-original"- })- ).toBe("supplier");-- expect(captured[1]).toEqual({- table: "memo",- companyId: "company-1",- journalId: "journal-original"- });- });-});--/**- * Minimal chainable supabase mock, same shape as the one in- * payment-tombstone.test.ts: `from(...).select(...).eq(...)*[.not(...)]- * [.limit(1)].maybeSingle()` resolves `{ data, error }` per table.- */-function makeClient(- resultsByTable: Record<string, { data: unknown; error?: { message: string } }>-) {- const captured: Array<Record<string, unknown>> = [];- const client: any = {- from(table: string) {- const query: Record<string, unknown> = { table };- captured.push(query);- const builder: any = {- select: () => builder,- eq: (column: string, value: unknown) => {- query[column] = value;- return builder;- },- not: (column: string, operator: string, value: unknown) => {- query[column] = `not ${operator} ${value}`;- return builder;- },- limit: (n: number) => {- query.limit = n;- return builder;- },- maybeSingle: async () => {- const result = resultsByTable[table] ?? { data: null };- return { data: result.data, error: result.error ?? null };- }- };- return builder;- }- };- return { client, captured };-}--describe("resolveMemoJournalPartyFromClient", () => {- it("resolves a VOID memo journal through the journal lines, companyId-scoped", async () => {- const { client, captured } = makeClient({- journalLine: { data: { documentId: "memo-1" } },- memo: { data: customerMemo }- });-- expect(- await resolveMemoJournalPartyFromClient(client, {- companyId: "company-1",- journalId: "journal-void"- })- ).toBe("customer");-- expect(captured).toEqual([- {- table: "journalLine",- companyId: "company-1",- journalId: "journal-void",- documentType: "Memo",- documentId: "not is null",- limit: 1- },- { table: "memo", companyId: "company-1", id: "memo-1" }- ]);- });-- it("falls back to memo.journalId when the lines read finds nothing", async () => {- const { client, captured } = makeClient({- journalLine: { data: null },- memo: { data: supplierMemo }- });-- expect(- await resolveMemoJournalPartyFromClient(client, {- companyId: "company-1",- journalId: "journal-original"- })- ).toBe("supplier");-- expect(captured[1]).toEqual({- table: "memo",- companyId: "company-1",- journalId: "journal-original"- });- });-- it("treats a failed lines read as 'no memo link' rather than a party", async () => {- // A read error must not be mistaken for a resolved party: fall through to- // the pointer, and answer null when that finds nothing either.- const { client } = makeClient({- journalLine: { data: null, error: { message: "boom" } },- memo: { data: null }- });-- expect(- await resolveMemoJournalPartyFromClient(client, {- companyId: "company-1",- journalId: "journal-void"- })- ).toBeNull();- });-});diff --git a/packages/ee/src/accounting/core/posting-policy.test.ts b/packages/ee/src/accounting/core/posting-policy.test.tsindex 22d11dee93..1c6995e8c6 100644--- a/packages/ee/src/accounting/core/posting-policy.test.ts+++ b/packages/ee/src/accounting/core/posting-policy.test.ts@@ -15,9 +15,8 @@ import {resolvePostingSyncSettings} from "./posting";-/** Resolve a v3 stored fragment exactly as production reads it. */-// These tests exercise the POLICY, not delegation, so the settings are marked-// carbon-owned. Delegation has its own tests in sync/delegation.test.ts.+// The settings are marked carbon-owned: delegation has its own tests in+// sync/delegation.test.ts.const settingsWith = (fragment?: Record<string, unknown>) =>asCarbonOwnedSettings(resolvePostingSyncSettings({@@ -25,37 +24,53 @@ const settingsWith = (fragment?: Record<string, unknown>) =>}));+type DecisionInput = Parameters<typeof getJournalPostingPolicyDecision>[0];+const DOC_SYNC_ON = { invoiceEnabled: true, billEnabled: true };const DOC_SYNC_OFF = { invoiceEnabled: false, billEnabled: false };+const AR_JOURNALS = { families: { ar: "journals", ap: "documents" } };+const BILLS_ONLY = { invoiceEnabled: false, billEnabled: true };+const CHARGE_SYNC = { ...DOC_SYNC_ON, chargeEnabled: true };++const decide = ({+ fragment,+ ...input+}: Partial<Omit<DecisionInput, "settings">> & {+ fragment?: Record<string, unknown>;+}) =>+ getJournalPostingPolicyDecision({+ sourceType: "Purchase Receipt",+ docSync: DOC_SYNC_ON,+ ...input,+ settings: settingsWith(fragment)+ });-// ── POSTING_POLICY totality & structure ──────────────────────────────────────+const PUSH = { kind: "push", granularity: "individual" };+const docBacked = (entityType?: string) => ({+ kind: "exclude",+ reason: "DOC_BACKED",+ ...(entityType ? { backingDocument: { entityType } } : {})+});+const excluded = (reason: string) => ({ kind: "exclude", reason });+const warns = (code: string) => ({ kind: "warn", code });describe("POSTING_POLICY", () => {- it("is structurally valid for every source type", () => {+ it("gives every document-represented type a family and a backing entity, and no journal type a family", () => {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();+ expect(entry.family, sourceType).toBeDefined();+ expect(entry.backingEntityType, sourceType).not.toBeUndefined();} else {- expect(entry.family).toBeUndefined();- }-- if (entry.family === "per-line") {- expect(sourceType).toBe("Payment");+ expect(entry.representation, sourceType).toBe("journal");+ expect(entry.family, sourceType).toBeUndefined();}+ if (entry.family === "per-line") expect(sourceType).toBe("Payment");}});- it("derives the frozen v2 default/excluded lists exactly (behavior parity)", () => {+ // Flipping a type's representation changes what reaches the provider.+ it("derives the default (pushed) and excluded (document) source type lists", () => {expect([...POSTING_SYNC_DEFAULT_SOURCE_TYPES].sort()).toEqual(["Purchase Receipt",@@ -71,16 +86,10 @@ describe("POSTING_POLICY", () => {"Asset Disposal","Non-Conformance","Inbound Inspection",- // Added post-v2 with the Ramp integration: charge journals- // (Dr expense / Cr card liability) push to the provider like any other- // automated internal posting — no document representation exists."Charge",- // Added post-v2 with maintenance labor: time on a maintenance dispatch- // posts Dr maintenance / Cr labor absorption, like Production Event."Maintenance Event"].sort());-expect([...POSTING_SYNC_EXCLUDED_SOURCE_TYPES].sort()).toEqual(["Sales Invoice",@@ -90,517 +99,354 @@ describe("POSTING_POLICY", () => {"Debit Memo","Sales Return","Purchase Return",- // Added post-v2 with the reimbursements work: a reimbursement is a- // document-represented AP posting. Its backingEntityType is still null- // until the reimbursement syncers land, so it parks DOC_SYNC_DISABLED- // rather than pushing — but it belongs in the excluded (document) list,- // not the journal-push one."Reimbursement"].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" });-- // No type summarizes by default — daily summary is opt-in per type- expect(- getJournalPostingPolicyDecision({- sourceType: "Production Event",- settings,- docSync: DOC_SYNC_ON- })- ).toEqual({ kind: "push", granularity: "individual" });- });-- 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("Charge — per-row charge backing", () => {- const chargeSync = { ...DOC_SYNC_ON, chargeEnabled: true };-- it("hands a Charge with a supplier to the charge syncer", () => {- const decision = getJournalPostingPolicyDecision({+ it.each<[string, Parameters<typeof decide>[0], object]>([+ // Journal-represented types+ ["pushes a journal type individually by default", {}, PUSH],+ [+ "pushes Production Event individually (summary is opt-in)",+ { sourceType: "Production Event" },+ PUSH+ ],+ [+ "pushes an automated type even when a stored enabled:false says otherwise",+ {+ fragment: {+ sourceTypes: {+ "Purchase Receipt": { enabled: false, granularity: "individual" }+ }+ }+ },+ PUSH+ ],+ [+ "permanently excludes Manual",+ { sourceType: "Manual" },+ excluded("MANUAL_DISABLED")+ ],+ [+ "excludes an unknown source type",+ { sourceType: "Not A Source Type" },+ excluded("SOURCE_TYPE_DISABLED")+ ],+ [+ "excludes a missing source type",+ { sourceType: null },+ excluded("SOURCE_TYPE_DISABLED")+ ],+ [+ "hands Inventory Adjustment to the entity syncer when that sync is on",+ {+ sourceType: "Inventory Adjustment",+ inventoryAdjustmentEntitySyncEnabled: true+ },+ docBacked("inventoryAdjustment")+ ],++ // Charge journals are backed per row+ [+ "hands a supplier Charge to the charge syncer",+ {sourceType: "Charge",- settings: settingsWith(),- docSync: chargeSync,+ docSync: CHARGE_SYNC,charge: { type: "Charge", hasSupplier: true }- });- expect(decision).toMatchObject({- kind: "exclude",- reason: "DOC_BACKED",- backingDocument: { entityType: "charge" }- });- });-- it("keeps pushing a statement Payment / Cashback / Repayment as a journal entry", () => {- for (const type of ["Payment", "Cashback", "Repayment"] as const) {- expect(- getJournalPostingPolicyDecision({- sourceType: "Charge",- settings: settingsWith(),- docSync: chargeSync,- charge: { type, hasSupplier: true }- })- ).toMatchObject({ kind: "push" });- }- });-- it("keeps pushing a Charge with no merchant supplier (no vendor for a charge object)", () => {- expect(- getJournalPostingPolicyDecision({- sourceType: "Charge",- settings: settingsWith(),- docSync: chargeSync,- charge: { type: "Charge", hasSupplier: false }- })- ).toMatchObject({ kind: "push" });- });-- it("backs a Credit only where the provider can represent a refund", () => {- const credit = { type: "Credit", hasSupplier: true } as const;- expect(- getJournalPostingPolicyDecision({+ },+ docBacked("charge")+ ],+ ...(["Payment", "Cashback", "Repayment"] as const).map(+ (type): [string, Parameters<typeof decide>[0], object] => [+ `keeps pushing a statement ${type} as a journal`,+ {sourceType: "Charge",- settings: settingsWith(),- docSync: chargeSync,- charge: credit- })- ).toMatchObject({ kind: "push" });- expect(- getJournalPostingPolicyDecision({- sourceType: "Charge",- settings: settingsWith(),- docSync: { ...chargeSync, chargeCreditEnabled: true },- charge: credit- })- ).toMatchObject({ kind: "exclude", reason: "DOC_BACKED" });- });-- it("pushes every charge as a journal entry when charge sync is off or the row is unknown", () => {- expect(- getJournalPostingPolicyDecision({- sourceType: "Charge",- settings: settingsWith(),- docSync: DOC_SYNC_ON,- charge: { type: "Charge", hasSupplier: true }- })- ).toMatchObject({ kind: "push" });- expect(- getJournalPostingPolicyDecision({- sourceType: "Charge",- settings: settingsWith(),- docSync: chargeSync,- charge: null- })- ).toMatchObject({ kind: "push" });- });- });-- 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 RETURNS as DOC_SYNC_DISABLED (no document representation exists yet)", () => {- for (const sourceType of ["Sales Return", "Purchase Return"]) {- const decision = getJournalPostingPolicyDecision({- sourceType,- settings: settingsWith(),- docSync: DOC_SYNC_ON- });- expect(decision, sourceType).toMatchObject({- kind: "warn",- code: "DOC_SYNC_DISABLED"- });- }- });-- /**- * `families.vendorCredit` was renamed to `families.supplierCredit`- * (Carbon says supplier; only the providers say vendor). The migration- * rewrites every stored row, but an instance still on the old code can- * write the old key mid-deploy — and because the key DEFAULTS to "none",- * dropping it does not fail, it silently stops pushing supplier credits- * for a company that had turned them on.- */- it("carries a stored families.vendorCredit onto supplierCredit", () => {- const decision = getJournalPostingPolicyDecision({+ docSync: CHARGE_SYNC,+ charge: { type, hasSupplier: true }+ },+ PUSH+ ]+ ),+ [+ "keeps pushing a Charge with no merchant supplier",+ {+ sourceType: "Charge",+ docSync: CHARGE_SYNC,+ charge: { type: "Charge", hasSupplier: false }+ },+ PUSH+ ],+ [+ "keeps pushing a Credit when the provider cannot represent a refund",+ {+ sourceType: "Charge",+ docSync: CHARGE_SYNC,+ charge: { type: "Credit", hasSupplier: true }+ },+ PUSH+ ],+ [+ "backs a Credit when the provider can represent a refund",+ {+ sourceType: "Charge",+ docSync: { ...CHARGE_SYNC, chargeCreditEnabled: true },+ charge: { type: "Credit", hasSupplier: true }+ },+ docBacked("charge")+ ],+ [+ "pushes a Charge when charge sync is off",+ { sourceType: "Charge", charge: { type: "Charge", hasSupplier: true } },+ PUSH+ ],+ [+ "pushes a Charge whose row is unknown",+ { sourceType: "Charge", docSync: CHARGE_SYNC, charge: null },+ PUSH+ ],++ // documents mode (the default for ar/ap)+ [+ "leaves a Sales Invoice to the invoice syncer",+ { sourceType: "Sales Invoice" },+ docBacked("invoice")+ ],+ [+ "warns when a documents-mode family's document sync is off",+ { sourceType: "Purchase Invoice", docSync: DOC_SYNC_OFF },+ warns("DOC_SYNC_DISABLED")+ ],+ [+ "warns for Sales Return, which has no document yet",+ { sourceType: "Sales Return" },+ warns("DOC_SYNC_DISABLED")+ ],+ [+ "warns for Purchase Return, which has no document yet",+ { sourceType: "Purchase Return" },+ warns("DOC_SYNC_DISABLED")+ ],+ [+ "leaves Payment to the payment syncer whatever the document flags",+ { sourceType: "Payment", docSync: DOC_SYNC_OFF, paymentFamily: "ar" },+ docBacked("payment")+ ],+ [+ "excludes a customer memo by default (memo families are opt-in)",+ { sourceType: "Credit Memo", memoParty: "customer" },+ excluded("FAMILY_OFF")+ ],+ [+ "excludes a supplier memo by default",+ { sourceType: "Debit Memo", memoParty: "supplier" },+ excluded("FAMILY_OFF")+ ],+ // An instance on old code can still write the pre-rename key mid-deploy.+ [+ "reads a stored families.vendorCredit as supplierCredit",+ {sourceType: "Debit Memo",- settings: settingsWith({ families: { vendorCredit: "documents" } }),- docSync: DOC_SYNC_ON,- memoParty: "supplier"- });- expect(decision).not.toMatchObject({ reason: "FAMILY_OFF" });- });-- it("prefers supplierCredit when a stored fragment carries both keys", () => {- const decision = getJournalPostingPolicyDecision({+ memoParty: "supplier",+ fragment: { families: { vendorCredit: "documents" } },+ docSync: { ...DOC_SYNC_ON, supplierCreditEnabled: true }+ },+ docBacked()+ ],+ [+ "prefers supplierCredit when both keys are stored",+ {sourceType: "Debit Memo",- settings: settingsWith({+ memoParty: "supplier",+ fragment: {families: { vendorCredit: "documents", supplierCredit: "none" }- }),- docSync: DOC_SYNC_ON,- memoParty: "supplier"- });- expect(decision).toMatchObject({- kind: "exclude",- reason: "FAMILY_OFF"- });- });-- it("excludes memos as FAMILY_OFF by default (their families are opt-in)", () => {- // Memos DO have a document representation now; what stops them by- // default is that creditMemo/supplierCredit default to "none".- for (const [sourceType, memoParty] of [- ["Credit Memo", "customer"],- ["Debit Memo", "supplier"]- ] as const) {- const decision = getJournalPostingPolicyDecision({- sourceType,- settings: settingsWith(),- docSync: DOC_SYNC_ON,- memoParty- });- expect(decision, sourceType).toMatchObject({- kind: "exclude",- reason: "FAMILY_OFF"- });- }- });-- 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({+ }+ },+ excluded("FAMILY_OFF")+ ],++ // journals mode+ [+ "pushes a journals-mode family individually",+ {sourceType: "Sales Invoice",- settings: journalsAr,- docSync: { invoiceEnabled: false, billEnabled: true }- });- expect(decision).toEqual({ kind: "push", granularity: "individual" });-- // Memos ride their OWN family (creditMemo/supplierCredit), not ar/ap.- const memo = getJournalPostingPolicyDecision({+ fragment: AR_JOURNALS,+ docSync: BILLS_ONLY+ },+ PUSH+ ],+ [+ "pushes a memo on its own journals-mode family",+ {sourceType: "Credit Memo",- settings: settingsWith({+ memoParty: "customer",+ fragment: {families: {ar: "journals",ap: "documents",creditMemo: "journals",supplierCredit: "none"}- }),- docSync: { invoiceEnabled: false, billEnabled: true },- memoParty: "customer"- });- 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({+ },+ docSync: BILLS_ONLY+ },+ PUSH+ ],+ [+ "warns when a journals-mode family's document sync is also on",+ { sourceType: "Sales Invoice", fragment: AR_JOURNALS },+ warns("DOUBLE_REPRESENTATION")+ ],+ [+ "leaves the other family in documents mode",+ {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({+ fragment: AR_JOURNALS,+ docSync: BILLS_ONLY+ },+ docBacked("bill")+ ],++ // none mode+ [+ "excludes a family set to none",+ {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({+ fragment: { families: { ar: "none", ap: "documents" } }+ },+ excluded("FAMILY_OFF")+ ],++ // Payment resolves its family per line+ [+ "follows the AR side of a payment when the families diverge",+ {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({+ fragment: AR_JOURNALS,+ docSync: BILLS_ONLY,+ paymentFamily: "ar"+ },+ PUSH+ ],+ [+ "follows the AP side of a payment when the families diverge",+ {sourceType: "Payment",- settings: settingsWith(),- docSync: DOC_SYNC_ON,+ fragment: AR_JOURNALS,+ docSync: BILLS_ONLY,+ paymentFamily: "ap"+ },+ docBacked()+ ],+ [+ "warns when a payment's side is unknown and the families diverge",+ {+ sourceType: "Payment",+ fragment: AR_JOURNALS,+ docSync: BILLS_ONLY,paymentFamily: null- });- expect(decision).toMatchObject({- kind: "exclude",- reason: "DOC_BACKED"- });- });+ },+ warns("PAYMENT_FAMILY_UNRESOLVED")+ ],+ [+ "needs no payment side when both families share a mode",+ { sourceType: "Payment", paymentFamily: null },+ docBacked()+ ]+ ])("%s", (_name, input, expected) => {+ expect(decide(input)).toMatchObject(expected);});});-// ── Memo families resolve by PARTY, not direction ────────────────────────────+// The stored per-type list is a parse-compatible v2 field the decision no+// longer reads: it can neither disable an automated type nor enable a+// document-represented one, nor Manual.+describe("stored source-type overrides", () => {+ it.each([...POSTING_SYNC_DEFAULT_SOURCE_TYPES])(+ "pushes %s even when a narrowed stored list omits it",+ (sourceType) => {+ expect(+ decide({ sourceType, fragment: { sourceTypes: ["Manual"] } }).kind+ ).toBe("push");+ }+ );++ it.each([...POSTING_SYNC_EXCLUDED_SOURCE_TYPES, "Manual"])(+ "never pushes %s, even when the stored list names it",+ (sourceType) => {+ expect(+ decide({+ sourceType,+ fragment: { sourceTypes: [sourceType], includeManual: true }+ }).kind+ ).not.toBe("push");+ }+ );+});-describe("memo family resolution (per-party)", () => {- // Memo doc sync on for both sides, so the FAMILY MODE is the only variable.+// The memo's PARTY picks its family, never the memo's direction: a supplier+// Credit Memo is AP, a customer Debit Memo is AR.+describe("memo family resolution", () => {const MEMO_DOC_SYNC = {invoiceEnabled: false,billEnabled: false,creditMemoEnabled: true,supplierCreditEnabled: true};-- // Only the customer family is on. A supplier memo must NOT be gated by it —- // which is exactly what direction-derived families got wrong.- const customerOnly = settingsWith({- families: {- ar: "none",- ap: "none",- creditMemo: "documents",- supplierCredit: "none"- }+ const families = (creditMemo: string, supplierCredit: string) => ({+ families: { ar: "none", ap: "none", creditMemo, supplierCredit }});-- const supplierOnly = settingsWith({- families: {- ar: "none",- ap: "none",- creditMemo: "none",- supplierCredit: "documents"+ // ap is "none" in both: bills handed to a spend tool must not suppress+ // supplier credits.+ const customerOnly = families("documents", "none");+ const supplierOnly = families("none", "documents");++ it.each([+ [+ "Credit Memo",+ "customer",+ "customer family on",+ customerOnly,+ docBacked()+ ],+ ["Debit Memo", "customer", "customer family on", customerOnly, docBacked()],+ ["Debit Memo", "supplier", "supplier family on", supplierOnly, docBacked()],+ [+ "Credit Memo",+ "supplier",+ "supplier family on",+ supplierOnly,+ docBacked()+ ],+ [+ "Credit Memo",+ "supplier",+ "customer family on",+ customerOnly,+ excluded("FAMILY_OFF")+ ],+ [+ "Debit Memo",+ "customer",+ "supplier family on",+ supplierOnly,+ excluded("FAMILY_OFF")+ ],+ [+ "Credit Memo",+ null,+ "customer family on",+ customerOnly,+ warns("MEMO_PARTY_UNRESOLVED")+ ]+ ] as const)(+ "decides a %s from a %s party with the %s",+ (sourceType, memoParty, _families, fragment, expected) => {+ expect(+ decide({ sourceType, memoParty, fragment, docSync: MEMO_DOC_SYNC })+ ).toMatchObject(expected);}- });-- const decide = (- sourceType: "Credit Memo" | "Debit Memo",- memoParty: "customer" | "supplier" | null,- settings: ReturnType<typeof settingsWith>- ) =>- getJournalPostingPolicyDecision({- sourceType,- settings,- docSync: MEMO_DOC_SYNC,- memoParty- });-- it("gates a CUSTOMER memo by creditMemo in both directions", () => {- expect(decide("Credit Memo", "customer", customerOnly)).toMatchObject({- kind: "exclude",- reason: "DOC_BACKED"- });- // The crossing combo: a customer memo in the DEBIT direction is still AR.- expect(decide("Debit Memo", "customer", customerOnly)).toMatchObject({- kind: "exclude",- reason: "DOC_BACKED"- });- });-- it("gates a SUPPLIER memo by supplierCredit in both directions", () => {- expect(decide("Debit Memo", "supplier", supplierOnly)).toMatchObject({- kind: "exclude",- reason: "DOC_BACKED"- });- // The crossing combo: a supplier memo in the CREDIT direction is still AP.- expect(decide("Credit Memo", "supplier", supplierOnly)).toMatchObject({- kind: "exclude",- reason: "DOC_BACKED"- });- });-- it("does not let direction pick the family (the misclassification bug)", () => {- // Under direction-derived families a "Credit Memo" always resolved to the- // AR family, so a SUPPLIER credit memo was gated by the wrong side.- expect(decide("Credit Memo", "supplier", customerOnly)).toMatchObject({- kind: "exclude",- reason: "FAMILY_OFF"- });- // ...and a "Debit Memo" always resolved to AP, misfiling a CUSTOMER one.- expect(decide("Debit Memo", "customer", supplierOnly)).toMatchObject({- kind: "exclude",- reason: "FAMILY_OFF"- });- });-- it("is decoupled from the invoice/bill families", () => {- // ap: "none" (bills handed to a spend tool) must NOT suppress vendor- // credits — the reason memos get their own families at all.- const apOff = settingsWith({- families: {- ar: "documents",- ap: "none",- creditMemo: "none",- supplierCredit: "documents"- }- });- expect(decide("Debit Memo", "supplier", apOff)).toMatchObject({- kind: "exclude",- reason: "DOC_BACKED"- });- });-- it("parks MEMO_PARTY_UNRESOLVED rather than guessing a family", () => {- expect(decide("Credit Memo", null, customerOnly)).toMatchObject({- kind: "warn",- code: "MEMO_PARTY_UNRESOLVED"- });- });+ );});diff --git a/packages/ee/src/accounting/core/posting.test.ts b/packages/ee/src/accounting/core/posting.test.tsindex 5b56f48ddc..ad3bad00bb 100644--- a/packages/ee/src/accounting/core/posting.test.ts+++ b/packages/ee/src/accounting/core/posting.test.ts@@ -5,23 +5,31 @@import { describe, expect, it } from "vitest";import { asCarbonOwnedSettings } from "../../sync/delegation";import {+ addDaysToIsoDate,aggregateJournalEntriesForDate,collectUnmappedDimensionValues,+ DEFAULT_POSTING_SYNC_SETTINGS,+ evaluatePeriodLock,getDailyConsolidationNarration,getDimensionTupleKey,+ getJournalEntrySyncEntityId,getPostingSyncSourceTypeSkipReason,getZeroJournalSkipReason,+ isBalancedJournal,+ isJournalEntrySyncFailure,isPaymentSyncbackEnabled,isZeroJournal,JournalEntrySyncError,netJournalLinesPerAccount,+ type PostingSyncSettings,+ parseJournalEntrySyncEntityId,resolvePostingSyncSettings,runJournalEntryPreflight,toDebitSignedAmount} from "./posting";import type { Accounting } from "./types";-// ── Daily-consolidation aggregation (Task 12) ────────────────────────────────+// ── Daily-consolidation aggregation ────────────────────────────────────────// One aggregated journal per posting date: signed amounts summed per account// across the member journals, zero-net accounts dropped, balance asserted.@@ -246,127 +254,66 @@ describe("getDailyConsolidationNarration", () => {});});-// ── Source-type gate ─────────────────────────────────────────────────────────+// ── Drain-time backstop ──────────────────────────────────────────────────────+// The policy decisions themselves are in posting-policy.test.ts. The backstop+// derives document-sync flags from the family modes and forwards the memo+// party; a skip returns the decision's message, a push returns null.describe("getPostingSyncSourceTypeSkipReason", () => {- const settings = asCarbonOwnedSettings(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");- });-- // The memo families are resolved per PARTY, so the backstop needs the party- // the enqueue decision already resolved from `memo.journalId`. Without it- // every memo journal parked as MEMO_PARTY_UNRESOLVED — and for a family in- // `journals` mode that is a delivery hole: the enqueue decision said push,- // and the drain-time backstop skipped it.- describe("memo journals (per-party families)", () => {- const memoJournalsMode = asCarbonOwnedSettings(- resolvePostingSyncSettings({- settings: {- postingSync: {- families: {- ar: "documents",- ap: "documents",- creditMemo: "journals",- vendorCredit: "journals"- }- }- }- })+ const settingsWith = (families?: Record<string, string>) =>+ asCarbonOwnedSettings(+ resolvePostingSyncSettings(+ families ? { settings: { postingSync: { families } } } : null+ ));+ const memoJournals = {+ ar: "documents",+ ap: "documents",+ creditMemo: "journals",+ supplierCredit: "journals"+ };- it("pushes a memo journal whose family is in journals mode once the party is supplied", () => {- expect(- getPostingSyncSourceTypeSkipReason("Credit Memo", memoJournalsMode, {- memoParty: "customer"- })- ).toBeNull();- // The PARTY decides the family, not the direction: a supplier Credit- // memo is gated by Vendor Credits.- expect(- getPostingSyncSourceTypeSkipReason("Credit Memo", memoJournalsMode, {- memoParty: "supplier"- })- ).toBeNull();- expect(- getPostingSyncSourceTypeSkipReason("Debit Memo", memoJournalsMode, {- memoParty: "supplier"- })- ).toBeNull();- });-- it("parks an unresolvable memo party instead of guessing a family", () => {- expect(- getPostingSyncSourceTypeSkipReason("Credit Memo", memoJournalsMode)- ).toContain("could not be resolved to a customer or supplier memo");- });-- it("keeps a family-off memo journal excluded with the party supplied", () => {- // Memo families default to "none".- expect(- getPostingSyncSourceTypeSkipReason("Credit Memo", settings, {- memoParty: "customer"- })- ).toContain('set to "none"');- });-- it("excludes a documents-mode memo journal as document-backed", () => {- const memoDocumentsMode = asCarbonOwnedSettings(- resolvePostingSyncSettings({- settings: {- postingSync: {- families: { creditMemo: "documents" }- }- }- })+ it.each<+ [+ string,+ string,+ Record<string, string> | undefined,+ Parameters<typeof getPostingSyncSourceTypeSkipReason>[2],+ boolean+ ]+ >([+ ["pushes", "Purchase Receipt", undefined, undefined, true],+ ["skips", "Sales Invoice", undefined, undefined, false],+ [+ "skips",+ "Inventory Adjustment",+ undefined,+ { inventoryAdjustmentEntitySyncEnabled: true },+ false+ ],+ // A journals-mode family has its document sync off, so no double-representation warning.+ [+ "pushes",+ "Sales Invoice",+ { ar: "journals", ap: "documents" },+ undefined,+ true+ ],+ ["pushes", "Credit Memo", memoJournals, { memoParty: "supplier" }, true],+ // Without the party a memo parks as unresolved, a delivery hole in journals mode.+ ["skips", "Credit Memo", memoJournals, undefined, false]+ ])(+ "%s a %s journal (families %o, options %o)",+ (_verb, sourceType, families, options, pushes) => {+ const reason = getPostingSyncSourceTypeSkipReason(+ sourceType,+ settingsWith(families),+ options);- expect(- getPostingSyncSourceTypeSkipReason("Credit Memo", memoDocumentsMode, {- memoParty: "customer"- })- ).toContain("document-backed");- });- });+ if (pushes) expect(reason).toBeNull();+ else expect(reason).toEqual(expect.any(String));+ }+ );});// ── Natural-balance → debit-signed conversion ───────────────────────────────@@ -841,3 +788,353 @@ describe("zero journals", () => {expect(result.failure).toBeNull();});});++// ── Preflight, settings resolution and journal-sync helpers ──────────────────++// 3-line balanced fixture: Dr Inventory 150.00, Dr Freight 25.50,+// Cr GRNI accrual 175.50 (Carbon signed amounts: positive = debit)+const receiptJournal = (+ 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: receiptJournal(),+ accountCodesById: ACCOUNT_CODES,+ controlAccountIds: new Set<string>(),+ lockDate: null,+ settings: makeSettings()+});++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 = receiptJournal();+ 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 = receiptJournal();+ 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 = receiptJournal();+ 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("resolvePostingSyncSettings", () => {+ it.each([undefined, {}, { settings: {} }])(+ "resolves %o to the defaults",+ (metadata) => {+ expect(resolvePostingSyncSettings(metadata)).toEqual(+ DEFAULT_POSTING_SYNC_SETTINGS+ );+ }+ );++ // Memo families are opt-in; invoices and bills sync as documents.+ it("defaults ar/ap to documents mode and the memo families to none", () => {+ expect(DEFAULT_POSTING_SYNC_SETTINGS.families).toEqual({+ ar: "documents",+ ap: "documents",+ creditMemo: "none",+ supplierCredit: "none"+ });+ });++ 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",+ creditMemo: "none",+ supplierCredit: "none"+ });+ });++ 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);+ });+});diff --git a/packages/ee/src/accounting/core/sales-document-components.test.ts b/packages/ee/src/accounting/core/sales-document-components.test.tsindex 4df0508175..52b538f46d 100644--- a/packages/ee/src/accounting/core/sales-document-components.test.ts+++ b/packages/ee/src/accounting/core/sales-document-components.test.ts@@ -4,9 +4,6 @@import { EPSILON, round } from "@carbon/utils";import { describe, expect, it } from "vitest";-import { QboSalesInvoiceSyncer } from "../providers/quickbooks-online/entities/invoice";-import { RilletSalesInvoiceSyncer } from "../providers/rillet/entities/invoice";-import { SalesInvoiceSyncer } from "../providers/xero/entities/invoice";import { SalesInvoiceSchema } from "./models";import {assertNoAssetDisposalComponents,@@ -15,9 +12,9 @@ import {isRevenueComponent} from "./sales-document-components";import {- loadSalesInvoices,requirePostedSalesAccountId,- requirePostedShippingAccountId+ requirePostedShippingAccountId,+ resolveReplayedRevenueAccounts} from "./sales-invoice-source";import type { Accounting } from "./types";@@ -489,500 +486,145 @@ describe("normalized sales invoice currency/component contract", () => {});});-function sourceDatabase(- missingCurrency = false,- postingRows = [- {- documentId: "invoice",- accountId: "posted-shipping",- description: "Shipping Revenue",- amount: 15,- accountClass: "Revenue",- isGroup: false- }- ],- invoiceIds = ["invoice"]-) {- const source = fixture();- const headerValues: Record<string, unknown> = Object.fromEntries(- Object.entries(source).map(([key, value]) => [`salesInvoice.${key}`, value])- );- Object.assign(headerValues, {- "salesInvoice.subtotal": 999,- "salesInvoice.totalTax": 999,- "salesInvoice.totalAmount": 999,- "salesInvoices.subtotal": source.subtotal,- "salesInvoices.totalTax": source.totalTax,- "salesInvoices.totalAmount": source.totalAmount,- "salesInvoices.balance": source.balance,- "salesInvoiceShipment.shippingCost": source.headerShippingCost,- "company.baseCurrencyCode": source.baseCurrencyCode,- "baseCurrency.decimalPlaces": source.baseCurrencyDecimalPlaces,- "documentCurrency.decimalPlaces": missingCurrency- ? null- : source.currencyDecimalPlaces+// The original revenue account a provider document replays, per role, from the+// invoice's posted journal lines. A defect belongs to ONE invoice: the loader+// is a batch, and a throw there parks every sibling invoice drained beside it.+describe("resolveReplayedRevenueAccounts", () => {+ const posting = (+ documentId: string,+ accountId: string,+ overrides: Partial<{+ description: string;+ accountClass: string;+ isGroup: boolean;+ }> = {}+ ) => ({+ documentId,+ accountId,+ description: "Sales Account",+ accountClass: "Revenue",+ isGroup: false,+ ...overrides});- const lineValues: Record<string, unknown> = Object.fromEntries(- Object.entries(source.lines[0]!).map(([key, value]) => [- `salesInvoiceLine.${key}`,- value- ])- );- lineValues["salesInvoiceLine.invoiceId"] = source.id;- lineValues["item.readableIdWithRevision"] = "SERVICE";- const reads: Array<{- table: string;- columns: string[];- where: unknown[][];- joins: string[];- on: unknown[][];- }> = [];- const database = {- selectFrom(table: string) {- const read = {- table,- columns: [] as string[],- where: [] as unknown[][],- joins: [] as string[],- on: [] as unknown[][]- };- reads.push(read);- const builder: any = {- select(columns: string[] | string) {- read.columns.push(...(Array.isArray(columns) ? columns : [columns]));- return builder;- },- where(...args: unknown[]) {- read.where.push(args);- return builder;- },- leftJoin(name: string, ...args: unknown[]) {- read.joins.push(name);- if (typeof args[0] === "function") {- const join: any = {- onRef(...refs: unknown[]) {- read.on.push(refs);- return join;- },- on(...refs: unknown[]) {- read.on.push(refs);- return join;- }- };- args[0](join);- }- return builder;- },- innerJoin(name: string, ...args: unknown[]) {- return builder.leftJoin(name, ...args);- },- async execute() {- if (table === "journalLine") return postingRows;- const values = table === "salesInvoice" ? headerValues : lineValues;- return invoiceIds.map((id) =>- Object.fromEntries(- read.columns.map((column) => {- const [name, alias] = column.split(" as ");- const value =- name === "salesInvoice.id" ||- name === "salesInvoiceLine.invoiceId"- ? id- : name === "salesInvoiceLine.id"- ? `line-${id}`- : values[name!];- return [alias ?? name!.split(".").at(-1)!, value];- })- )- );- }- };- return builder;- }+ const shipping = (documentId: string, accountId: string) =>+ posting(documentId, accountId, { description: "Shipping Revenue" });+ const replay = (rows: ReturnType<typeof posting>[], invoiceId: string) => {+ const resolve = resolveReplayedRevenueAccounts(rows);+ return {+ sales: resolve("SalesRevenue", invoiceId),+ shipping: resolve("ShippingRevenue", invoiceId)+ };};- return { database, reads };-}-describe.each([- SalesInvoiceSyncer,- QboSalesInvoiceSyncer,- RilletSalesInvoiceSyncer-])("provider source fetch %s", (Syncer) => {- it("reads authoritative view totals, all charge columns and group-scoped currency metadata through the actual batch path", async () => {- const { database, reads } = sourceDatabase();- const syncer = new Syncer({- database: database as never,- companyId: "company",- provider: { id: "xero" } as never,- config: {- enabled: true,- direction: "push-to-accounting",- owner: "carbon"- },- entityType: "invoice"- });- const result = await (- syncer as unknown as {- fetchLocalBatch(- ids: string[]- ): Promise<Map<string, Accounting.SalesInvoice>>;- }- ).fetchLocalBatch(["invoice"]);- const source = result.get("invoice");- expect(source).toMatchObject({- subtotal: 133,- totalTax: 13,- totalAmount: 151,- balance: 151,- headerShippingCost: 5,- shippingRevenueAccountId: "posted-shipping",- baseCurrencyCode: "USD",- baseCurrencyDecimalPlaces: 2,- currencyDecimalPlaces: 2- });- expect(source?.lines[0]).toMatchObject({- shippingCost: 10,- addOnCost: 20,- nonTaxableAddOnCost: 3,- convertedUnitPrice: 80- });- expect(buildSalesDocumentComponents(source!)).toMatchObject({- subtotal: 110.4,- totalTax: 10.4,- totalAmount: 120.8- });- expect(reads).toHaveLength(3);- expect(reads[0]?.where).toContainEqual([- "salesInvoice.companyId",- "=",- "company"- ]);- expect(reads[1]?.where).toContainEqual([- "salesInvoiceLine.companyId",- "=",- "company"- ]);- expect(reads[0]?.on).toContainEqual([- "documentCurrency.companyGroupId",- "=",- "company.companyGroupId"- ]);- expect(reads[0]?.on).toContainEqual([- "baseCurrency.companyGroupId",- "=",- "company.companyGroupId"- ]);- });- it("fails source loading when authoritative currency precision is unavailable", async () => {- const { database } = sourceDatabase(true);- const syncer = new Syncer({- database: database as never,- companyId: "company",- provider: { id: "xero" } as never,- config: {- enabled: true,- direction: "push-to-accounting",- owner: "carbon"- },- entityType: "invoice"- });- await expect(syncer.fetchLocal("invoice")).rejects.toThrow(- /currency|precision/i- );- });-});+ const clean = (documentId: string) => [+ posting(documentId, "sales-4000"),+ shipping(documentId, "shipping-4100")+ ];-describe("canonical invoice posting source", () => {- it("keeps different original shipping accounts in one batch and scopes every posting read", async () => {- const postings = ["a", "b"].map((id) => ({- documentId: id,- accountId: `shipping-${id}`,- description: "Shipping Revenue",- amount: 15,- accountClass: "Revenue",- isGroup: false- }));- const { database, reads } = sourceDatabase(false, postings, ["a", "b"]);- const result = await loadSalesInvoices(database as never, {- companyId: "company",- ids: ["a", "b"]+ it("extracts the merchandise and shipping accounts the original journal credited", () => {+ expect(replay(clean("a"), "a")).toEqual({+ sales: "sales-4000",+ shipping: "shipping-4100"});- expect(- [...result.values()].map((invoice) => invoice.shippingRevenueAccountId)- ).toEqual(["shipping-a", "shipping-b"]);- const read = reads.find((read) => read.table === "journalLine")!;- expect(read.where).toEqual(- expect.arrayContaining([- ["journalLine.companyId", "=", "company"],- ["journal.companyId", "=", "company"],- ["journal.sourceType", "=", "Sales Invoice"],- ["journalLine.documentType", "=", "Invoice"],- ["journal.status", "=", "Posted"],- ["journalLine.documentId", "in", ["a", "b"]]- ])- );- expect(read.on).toContainEqual([- "account.companyGroupId",- "=",- "company.companyGroupId"- ]);- expect(reads.some((read) => read.table === "accountDefault")).toBe(false);- });- it("refuses ambiguous original shipping accounts without choosing today's default", async () => {- const postings = ["a", "b"].map((id) => ({- documentId: "invoice",- accountId: `shipping-${id}`,- description: "Shipping Revenue",- amount: 15,- accountClass: "Revenue",- isGroup: false- }));- const { database } = sourceDatabase(false, postings);- // The refusal is the invoice's own, raised where the account is USED — the- // loader is a batch and must not fail its siblings. See the per-invoice- // isolation suite below.- const invoice = (- await loadSalesInvoices(database as never, {- companyId: "company",- ids: ["invoice"]- })- ).get("invoice")!;- expect(invoice.shippingRevenueAccountId).toBeNull();- expect(failureOf(() => requirePostedShippingAccountId(invoice))).toEqual({- errorCode: "UNMAPPED_ACCOUNTS",- warning: true,- invoiceId: "invoice"- });- });- it("ignores reversal and arbitrary revenue descriptions as original shipping facts", async () => {- const postings = ["VOID: Shipping Revenue", "Some revenue"].map(- (description) => ({- documentId: "invoice",- accountId: "other",- description,- amount: 15,- accountClass: "Revenue",- isGroup: false- })- );- const { database } = sourceDatabase(false, postings);- expect(- (- await loadSalesInvoices(database as never, {- companyId: "company",- ids: ["invoice"]- })- ).get("invoice")?.shippingRevenueAccountId- ).toBeNull();});-});-describe("replayed sales revenue account", () => {- /**- * The bug this exists to stop coming back: every test in this file used to post- * only a "Shipping Revenue" line, so the whole SalesRevenue extraction could be- * reverted to a shipping-only map and the suite stayed green — while every- * provider fixture hand-set `salesRevenueAccountId` and hid it.- */- it("extracts the account the original journal credited for merchandise", async () => {- const postings = [- {- documentId: "a",- accountId: "sales-4000",- description: "Sales Account",- amount: 100,- accountClass: "Revenue",- isGroup: false- },- {- documentId: "a",- accountId: "shipping-4100",- description: "Shipping Revenue",- amount: 15,- accountClass: "Revenue",- isGroup: false- }- ];- const { database } = sourceDatabase(false, postings, ["a"]);- const result = await loadSalesInvoices(database as never, {- companyId: "company",- ids: ["a"]- });- const invoice = result.get("a")!;- expect(invoice.salesRevenueAccountId).toBe("sales-4000");- expect(invoice.shippingRevenueAccountId).toBe("shipping-4100");+ it("keeps a different original shipping account per invoice in one batch", () => {+ const rows = [shipping("a", "shipping-a"), shipping("b", "shipping-b")];+ expect(replay(rows, "a").shipping).toBe("shipping-a");+ expect(replay(rows, "b").shipping).toBe("shipping-b");});- it("refuses an invoice whose merchandise revenue hit two accounts", async () => {- // Carbon posts ALL merchandise revenue to one account, so two means the- // journal is not the shape this replay assumes and guessing would misstate.- const postings = ["sales-4000", "sales-4001"].map((accountId) => ({- documentId: "a",- accountId,- description: "Sales Account",- amount: 50,- accountClass: "Revenue",- isGroup: false- }));- const { database } = sourceDatabase(false, postings, ["a"]);- const invoice = (- await loadSalesInvoices(database as never, {- companyId: "company",- ids: ["a"]- })- ).get("a")!;- expect(invoice.salesRevenueAccountId).toBeNull();- expect(failureOf(() => requirePostedSalesAccountId(invoice))).toEqual({- errorCode: "UNMAPPED_ACCOUNTS",- warning: true,- invoiceId: "a"- });+ it("answers null for an invoice with no revenue postings rather than today's default", () => {+ expect(replay(clean("a"), "b")).toEqual({ sales: null, shipping: null });});-});-/**- * `loadSalesInvoices` is the batch loader behind every invoice syncer's- * `fetchLocalBatch`. `pushBatchToAccounting` calls it ONCE for the whole claimed- * group (`DEFAULT_CLAIM_LIMIT` = 20 operations) and its outer `catch` records- * whatever the loader threw against EVERY id in the group — so a throw for one- * invoice's malformed revenue posting parked up to 19 healthy posted invoices as- * `Warning UNMAPPED_ACCOUNTS` naming a document they have nothing to do with.- * Nothing automatic recovers them either: `shouldEnqueueMissingDocument` refuses- * to re-enqueue a parked Warning, the capped re-drive arm in- * `computeReconcileDecision` is `bill`-only, and the changed-since-failure retry- * needs the invoice to be edited. One bad document therefore stopped AR sync for- * its whole batch, permanently and silently.- *- * Before this branch only a *Shipping* Revenue row could reach those throws, so- * an invoice with no shipping was immune. Replaying merchandise revenue put- * every invoice on that path.- */-describe("per-invoice revenue-account defects do not fail their batch", () => {- const cleanPostings = (documentId: string) => [- {- documentId,- accountId: "sales-4000",- description: "Sales Account",- amount: 100,- accountClass: "Revenue",- isGroup: false- },- {- documentId,- accountId: "shipping-4100",- description: "Shipping Revenue",- amount: 15,- accountClass: "Revenue",- isGroup: false+ it.each(["VOID: Shipping Revenue", "Some revenue"])(+ "does not read a %s line as an original revenue posting",+ (description) => {+ expect(replay([posting("a", "other", { description })], "a")).toEqual({+ sales: null,+ shipping: null+ });}- ];-- async function loadPair(- badPostings: Array<Record<string, unknown>>- ): Promise<Map<string, Accounting.SalesInvoice>> {- const { database } = sourceDatabase(- false,- [...cleanPostings("good"), ...badPostings] as never,- ["good", "bad"]- );- return loadSalesInvoices(database as never, {- companyId: "company",- ids: ["good", "bad"]- });- }+ );- function expectGoodInvoiceUnaffected(- result: Map<string, Accounting.SalesInvoice>- ) {- const good = result.get("good")!;- expect(requirePostedSalesAccountId(good)).toBe("sales-4000");- expect(requirePostedShippingAccountId(good)).toBe("shipping-4100");- }+ // Carbon posts all merchandise revenue to one account and all shipping to+ // another, so two of either means the journal is not the shape replayed.+ it.each([+ [+ "merchandise",+ [posting("bad", "sales-4000"), posting("bad", "sales-4001")],+ { sales: null, shipping: null }+ ],+ [+ "shipping",+ [shipping("bad", "shipping-a"), shipping("bad", "shipping-b")],+ { sales: null, shipping: null }+ ],+ [+ "a group merchandise",+ [posting("bad", "sales-parent", { isGroup: true })],+ { sales: null, shipping: null }+ ],+ // Only the broken role is unresolved; an invoice with no shipping still syncs.+ [+ "a non-Revenue shipping",+ [+ posting("bad", "sales-4000"),+ posting("bad", "shipping-asset", {+ description: "Shipping Revenue",+ accountClass: "Asset"+ })+ ],+ { sales: "sales-4000", shipping: null }+ ],+ // Half-broken is still broken: picking the surviving account is a guess.+ [+ "a group posting beside a valid merchandise",+ [+ posting("bad", "sales-parent", { isGroup: true }),+ posting("bad", "sales-4000")+ ],+ { sales: null, shipping: null }+ ]+ ])(+ "leaves the role unresolved for %s posting without touching a sibling invoice",+ (_case, badRows, expected) => {+ const rows = [...clean("good"), ...badRows];+ expect(replay(rows, "bad")).toEqual(expected);+ expect(replay(rows, "good")).toEqual({+ sales: "sales-4000",+ shipping: "shipping-4100"+ });+ }+ );+});- it("leaves a sibling invoice fully usable when merchandise revenue is ambiguous", async () => {- const result = await loadPair(- ["sales-4000", "sales-4001"].map((accountId) => ({- documentId: "bad",- accountId,- description: "Sales Account",- amount: 50,- accountClass: "Revenue",- isGroup: false- }))+describe("requirePosted*AccountId", () => {+ it.each([+ ["sales", "salesRevenueAccountId", requirePostedSalesAccountId],+ ["shipping", "shippingRevenueAccountId", requirePostedShippingAccountId]+ ] as const)("returns the replayed %s account", (_role, field, require) => {+ expect(require(fixture() as Accounting.SalesInvoice)).toBe(+ fixture()[field]);- expectGoodInvoiceUnaffected(result);- const bad = result.get("bad")!;- expect(failureOf(() => requirePostedSalesAccountId(bad))).toEqual({- errorCode: "UNMAPPED_ACCOUNTS",- warning: true,- invoiceId: "bad"- });});- it("leaves a sibling invoice fully usable when a merchandise posting is not a Revenue leaf", async () => {- // A group account, and a non-Revenue class, were the two conditions that- // threw from inside the posting-row loop — before the result map was even- // built, so they took every invoice in the batch with them.- const result = await loadPair([- {- documentId: "bad",- accountId: "sales-parent",- description: "Sales Account",- amount: 100,- accountClass: "Revenue",- isGroup: true- }- ]);- expectGoodInvoiceUnaffected(result);- expect(result.get("bad")!.salesRevenueAccountId).toBeNull();- });-- it("leaves a sibling invoice fully usable when a shipping posting is not a Revenue leaf", async () => {- const result = await loadPair([- ...cleanPostings("bad").slice(0, 1),- {- documentId: "bad",- accountId: "shipping-asset",- description: "Shipping Revenue",- amount: 15,- accountClass: "Asset",- isGroup: false- }- ]);- expectGoodInvoiceUnaffected(result);- const bad = result.get("bad")!;- // Only the broken ROLE is unresolved — the invoice's merchandise account is- // still replayed, so a document with no shipping component still syncs.- expect(bad.salesRevenueAccountId).toBe("sales-4000");- expect(failureOf(() => requirePostedShippingAccountId(bad))).toEqual({- errorCode: "UNMAPPED_ACCOUNTS",- warning: true,- invoiceId: "bad"- });- });-- it("does not fall back to the valid line when one posting of a role is unusable", async () => {- // Half-broken is still broken: picking the surviving account would be the- // guess the whole replay exists to avoid.- const result = await loadPair([- {- documentId: "bad",- accountId: "sales-parent",- description: "Sales Account",- amount: 40,- accountClass: "Revenue",- isGroup: true- },- {- documentId: "bad",- accountId: "sales-4000",- description: "Sales Account",- amount: 60,- accountClass: "Revenue",- isGroup: false- }- ]);- expectGoodInvoiceUnaffected(result);- expect(result.get("bad")!.salesRevenueAccountId).toBeNull();- });+ it.each([+ ["sales", "salesRevenueAccountId", requirePostedSalesAccountId],+ ["shipping", "shippingRevenueAccountId", requirePostedShippingAccountId]+ ] as const)(+ "parks the one invoice whose %s account is unresolved as an UNMAPPED_ACCOUNTS warning",+ (_role, field, require) => {+ const invoice = { ...fixture(), id: "bad", [field]: null };+ expect(+ failureOf(() => require(invoice as Accounting.SalesInvoice))+ ).toEqual({+ errorCode: "UNMAPPED_ACCOUNTS",+ warning: true,+ invoiceId: "bad"+ });+ }+ );});describe("fixed-asset disposal components", () => {diff --git a/packages/ee/src/accounting/core/sales-invoice-source.ts b/packages/ee/src/accounting/core/sales-invoice-source.tsindex 7ad863a094..025fa0018b 100644--- a/packages/ee/src/accounting/core/sales-invoice-source.ts+++ b/packages/ee/src/accounting/core/sales-invoice-source.ts@@ -136,69 +136,7 @@ export async function loadSalesInvoices(.where("journal.sourceType", "=", "Sales Invoice").where("journal.status", "=", "Posted").execute();- // Both revenue roles are extracted the same way, and for the same reason: a- // provider document must replay the account its ORIGINAL journal posted to,- // never today's default. Merchandise revenue joined shipping here when AR- // invoices stopped referencing items — the item used to carry the account- // implicitly (via the provider item's own config), and with the item gone the- // posted account is the only thing that can.- //- // Every defect below belongs to ONE invoice, and none of them throws from- // here. This is a BATCH loader: `pushBatchToAccounting` calls it once for the- // whole claimed group (up to 20 operations) and its outer catch parks every- // id in that group as an error carrying whatever this function threw. So one- // invoice with a malformed revenue posting used to park every other posted- // invoice drained beside it — as a Warning naming a DIFFERENT document — and- // nothing brings those back: `shouldEnqueueMissingDocument` refuses to- // re-enqueue a parked Warning, the capped re-drive is `bill`-only, and the- // changed-since-failure retry needs the document to be edited. Instead the- // role's account is left unresolved (`null`) and- // `requirePostedSalesAccountId` / `requirePostedShippingAccountId` raise the- // structured error for that one invoice from inside `mapToRemote`, which- // `pushBatchToAccounting` already catches per entity.- const revenueAccounts: Record<RevenueRole, Map<string, Set<string>>> = {- ShippingRevenue: new Map(),- SalesRevenue: new Map()- };- // Invoices whose posting for a role is unusable, whatever else it posted.- const unusableRoles: Record<RevenueRole, Set<string>> = {- ShippingRevenue: new Set(),- SalesRevenue: new Set()- };-- for (const row of postingRows) {- const role = classifyAccountingPostingRole(row.description);- if (role !== "ShippingRevenue" && role !== "SalesRevenue") continue;- // Unreachable in practice — the query filters `documentId in ids`, so the- // column is only nullable in the generated type — but a row that names no- // invoice cannot be recorded against one either, and the alternative here- // is a batch-wide throw.- if (!row.documentId) continue;- if (!row.accountId || row.accountClass !== "Revenue" || row.isGroup) {- unusableRoles[role].add(row.documentId);- continue;- }- const byInvoice = revenueAccounts[role];- const accounts = byInvoice.get(row.documentId) ?? new Set<string>();- accounts.add(row.accountId);- byInvoice.set(row.documentId, accounts);- }-- /**- * The one account a role replays, or `null` when the journal cannot name it.- *- * Ambiguity is never resolved by guessing — Carbon posts ALL merchandise- * revenue to one account (`accountDefault.salesAccount`; there is no- * per-item revenue account in the schema) and all shipping revenue to- * another, so two of either means the journal is not the shape this replay- * assumes. A role with ANY unusable posting stays unresolved even when a- * second line did name a valid leaf, for the same reason.- */- const resolveReplayedAccountId = (role: RevenueRole, invoiceId: string) => {- if (unusableRoles[role].has(invoiceId)) return null;- const ids = [...(revenueAccounts[role].get(invoiceId) ?? [])];- return ids.length === 1 ? ids[0]! : null;- };+ const replayed = resolveReplayedRevenueAccounts(postingRows);// Group lines by invoice IDconst linesByInvoiceId = new Map<string, (typeof lineRows)[number][]>();@@ -244,11 +182,8 @@ export async function loadSalesInvoices(baseCurrencyCode: row.baseCurrencyCode,baseCurrencyDecimalPlaces: Number(row.baseCurrencyDecimalPlaces),currencyDecimalPlaces: Number(row.currencyDecimalPlaces),- shippingRevenueAccountId: resolveReplayedAccountId(- "ShippingRevenue",- row.id- ),- salesRevenueAccountId: resolveReplayedAccountId("SalesRevenue", row.id),+ shippingRevenueAccountId: replayed("ShippingRevenue", row.id),+ salesRevenueAccountId: replayed("SalesRevenue", row.id),headerShippingCost: Number(row.headerShippingCost ?? 0),exchangeRate: Number(row.exchangeRate),postingDate: row.postingDate,@@ -296,12 +231,90 @@ export async function loadSalesInvoices(return result;}+/**+ * The original revenue account each invoice's posted journal names, per role,+ * from its "Sales Account" / "Shipping Revenue" journal lines.+ */+export function resolveReplayedRevenueAccounts(+ postingRows: Array<{+ documentId: string | null;+ accountId: string | null;+ description: string | null;+ accountClass: string | null;+ isGroup: boolean | null;+ }>+): (role: RevenueRole, invoiceId: string) => string | null {+ // Both revenue roles are extracted the same way, and for the same reason: a+ // provider document must replay the account its ORIGINAL journal posted to,+ // never today's default. Merchandise revenue joined shipping here when AR+ // invoices stopped referencing items — the item used to carry the account+ // implicitly (via the provider item's own config), and with the item gone the+ // posted account is the only thing that can.+ //+ // Every defect below belongs to ONE invoice, and none of them throws from+ // here. This is a BATCH loader: `pushBatchToAccounting` calls it once for the+ // whole claimed group (up to 20 operations) and its outer catch parks every+ // id in that group as an error carrying whatever this function threw. So one+ // invoice with a malformed revenue posting used to park every other posted+ // invoice drained beside it — as a Warning naming a DIFFERENT document — and+ // nothing brings those back: `shouldEnqueueMissingDocument` refuses to+ // re-enqueue a parked Warning, the capped re-drive is `bill`-only, and the+ // changed-since-failure retry needs the document to be edited. Instead the+ // role's account is left unresolved (`null`) and+ // `requirePostedSalesAccountId` / `requirePostedShippingAccountId` raise the+ // structured error for that one invoice from inside `mapToRemote`, which+ // `pushBatchToAccounting` already catches per entity.+ const revenueAccounts: Record<RevenueRole, Map<string, Set<string>>> = {+ ShippingRevenue: new Map(),+ SalesRevenue: new Map()+ };+ // Invoices whose posting for a role is unusable, whatever else it posted.+ const unusableRoles: Record<RevenueRole, Set<string>> = {+ ShippingRevenue: new Set(),+ SalesRevenue: new Set()+ };++ for (const row of postingRows) {+ const role = classifyAccountingPostingRole(row.description);+ if (role !== "ShippingRevenue" && role !== "SalesRevenue") continue;+ // Unreachable in practice — the query filters `documentId in ids`, so the+ // column is only nullable in the generated type — but a row that names no+ // invoice cannot be recorded against one either, and the alternative here+ // is a batch-wide throw.+ if (!row.documentId) continue;+ if (!row.accountId || row.accountClass !== "Revenue" || row.isGroup) {+ unusableRoles[role].add(row.documentId);+ continue;+ }+ const byInvoice = revenueAccounts[role];+ const accounts = byInvoice.get(row.documentId) ?? new Set<string>();+ accounts.add(row.accountId);+ byInvoice.set(row.documentId, accounts);+ }++ /**+ * The one account a role replays, or `null` when the journal cannot name it.+ *+ * Ambiguity is never resolved by guessing — Carbon posts ALL merchandise+ * revenue to one account (`accountDefault.salesAccount`; there is no+ * per-item revenue account in the schema) and all shipping revenue to+ * another, so two of either means the journal is not the shape this replay+ * assumes. A role with ANY unusable posting stays unresolved even when a+ * second line did name a valid leaf, for the same reason.+ */+ return (role: RevenueRole, invoiceId: string): string | null => {+ if (unusableRoles[role].has(invoiceId)) return null;+ const ids = [...(revenueAccounts[role].get(invoiceId) ?? [])];+ return ids.length === 1 ? ids[0]! : null;+ };+}+/*** Merchandise components must replay an original account, never today's default.** This is also where an UNRESOLVABLE original account is reported, not just an* absent one — the loader leaves every defect as `null` so the refusal lands on- * the one invoice it belongs to (see the comment in `loadSalesInvoices`). The+ * the one invoice it belongs to (see `resolveReplayedRevenueAccounts`). The* message therefore names all three causes; the invoice id is what a reader* needs to open the journal and see which.*/diff --git a/packages/ee/src/accounting/core/subscriptions.test.ts b/packages/ee/src/accounting/core/subscriptions.test.tsindex c3475a52ff..1d246082f2 100644--- a/packages/ee/src/accounting/core/subscriptions.test.ts+++ b/packages/ee/src/accounting/core/subscriptions.test.ts@@ -2,238 +2,218 @@// Carbon Enterprise file, licensed only under the Carbon Commercial License// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.-import { describe, expect, it, vi } from "vitest";+import { describe, expect, it } from "vitest";import { DEFAULT_SYNC_CONFIG, ProviderID, validateSyncConfig } from "./models";import {ensureProviderSubscriptions,- getSyncSubscriptionName,REQUIRED_SYNC_SUBSCRIPTIONS} from "./subscriptions";+type Row = {+ id: string;+ companyId: string;+ name: string;+ table: string;+ handlerType?: string;+ config?: unknown;+ active?: boolean;+};+/**- * 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.+ * An in-memory `eventSystemSubscription` table behind the create (upsert on+ * companyId + name + table) and delete RPCs and the list read.*/-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 })+function makeStore(initial: Row[] = []) {+ const rows = [...initial];+ let nextId = 0;+ const client = {+ async rpc(fn: string, params: Record<string, any>) {+ if (fn === "create_event_system_subscription") {+ const row: Row = {+ id: `new_${nextId++}`,+ companyId: params.p_company_id,+ name: params.p_name,+ table: params.p_table,+ handlerType: params.p_handler_type,+ config: params.p_config,+ active: params.p_active+ };+ const index = rows.findIndex(+ (r) =>+ r.companyId === row.companyId &&+ r.name === row.name &&+ r.table === row.table+ );+ if (index === -1) rows.push(row);+ else rows[index] = { ...row, id: rows[index]!.id };+ return { data: [{ id: row.id }], error: null };+ }+ if (fn === "delete_event_system_subscription") {+ const index = rows.findIndex((r) => r.id === params.p_subscription_id);+ if (index !== -1) rows.splice(index, 1);+ return { data: null, error: null };+ }+ throw new Error(`unexpected rpc ${fn}`);+ },+ from: () => ({+ select: () => ({+ eq: (_c1: string, companyId: string) => ({+ eq: async (_c2: string, name: string) => ({+ data: rows.filter(+ (r) => r.companyId === companyId && r.name === name+ ),+ error: null+ })+ })})})- }));-- return { rpc, from } as any;+ };+ return { client: client as any, rows };}-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"- );- }- });+const tablesOf = (providerId: (typeof ProviderID)[keyof typeof ProviderID]) =>+ REQUIRED_SYNC_SUBSCRIPTIONS[providerId].map((s) => s.table);- 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+describe("REQUIRED_SYNC_SUBSCRIPTIONS", () => {+ it.each(Object.values(ProviderID))(+ "%s subscribes journal and the master/document tables it owns",+ (providerId) => {+ expect(tablesOf(providerId)).toEqual(+ expect.arrayContaining([+ "journal",+ "customer",+ "supplier",+ "salesInvoice",+ "purchaseInvoice"+ ]));- expect(tables).not.toContain("address");}- });-- it("never subscribes item — the part catalog is not accounting data", () => {- // Carbon's item master is parts, materials, tools and consumables: tens of- // thousands of rows that mean nothing to an accounting system. Subscribing- // the table pushed every one of them, on every edit, with no filter (no item- // syncer overrides `shouldSync`) — burying the few real sellable goods in- // Products & Services and churning the provider on engineering edits.- //- // No invoice references a Carbon item any more (AR lines carry a synthetic- // per-revenue-account product, or are account-coded); the documents that do- // — sales orders, purchase orders, inventory adjustments — still push- // exactly the items they name, JIT via `ensureDependencySynced("item", …)`.- // Re-adding this subscription would silently restore the catalog dump.- for (const providerId of Object.values(ProviderID)) {- const tables = REQUIRED_SYNC_SUBSCRIPTIONS[providerId].map(- (subscription) => subscription.table- );- expect(tables, `${providerId} must not subscribe item`).not.toContain(- "item"- );+ );++ // address is covered by its parent's bump; item would push the whole parts+ // catalog — documents that need an item sync it on demand.+ it.each(Object.values(ProviderID))(+ "%s never subscribes address or item",+ (providerId) => {+ expect(tablesOf(providerId)).not.toContain("address");+ expect(tablesOf(providerId)).not.toContain("item");}- });+ );- it("still subscribes the tables a provider genuinely owns", () => {- // Guards the removal above from over-reaching: dropping `item` must not- // disturb the master/document tables the push actually depends on.- for (const providerId of Object.values(ProviderID)) {- const tables = REQUIRED_SYNC_SUBSCRIPTIONS[providerId].map(- (subscription) => subscription.table- );- for (const table of [- "customer",- "supplier",- "salesInvoice",- "purchaseInvoice"- ]) {- expect(tables, `${providerId} must subscribe ${table}`).toContain(- table- );- }- }+ it("subscribes payment only for the push-capable providers", () => {+ expect(+ Object.values(ProviderID).filter((providerId) =>+ tablesOf(providerId).includes("payment")+ )+ ).toEqual([ProviderID.XERO, ProviderID.QUICKBOOKS, ProviderID.RILLET]);});+});- it("lets a company sync bills with the item entity turned OFF", () => {- // `validateSyncConfig` refuses to enable an entity whose declared dependency- // is disabled. `bill` used to declare `dependsOn: ["vendor", "item"]` —- // left over from before AP bills became account-costed journal replays — so- // "bills on, items off" was an invalid config, blocking the one thing a- // customer would most reasonably want. No bill syncer references an item on- // the push.+describe("validateSyncConfig item dependency", () => {+ const withItemsOff = (...entities: string[]) => {const config = structuredClone(DEFAULT_SYNC_CONFIG);config.entities.item.enabled = false;- config.entities.bill.enabled = true;- config.entities.vendor.enabled = true;-- const errors = validateSyncConfig(config);- expect(errors.filter((e) => e.includes("Bills"))).toEqual([]);- });-- it("still requires items for the documents that DO reference them", () => {- // The guard against over-correcting. Purchase/sales ORDERS and inventory- // adjustments genuinely JIT-sync items (they are non-posting or item-keyed,- // so item detail is real), and disabling items must still be refused for- // them rather than silently producing lines with no product.- for (const entity of [- "purchaseOrder",- "salesOrder",- "inventoryAdjustment"- ] as const) {- const config = structuredClone(DEFAULT_SYNC_CONFIG);- config.entities.item.enabled = false;- config.entities[entity].enabled = true;- config.entities.customer.enabled = true;- config.entities.vendor.enabled = true;-- expect(- validateSyncConfig(config).some((e) => e.includes("Items")),- `${entity} must still require items`- ).toBe(true);+ for (const entity of entities) {+ config.entities[entity as keyof typeof config.entities].enabled = true;}- });-- it("lets a company sync sales invoices with the item entity turned OFF", () => {- // The point of the change: an AR invoice line carries a synthetic- // per-revenue-account item (or none, on Xero), never the Carbon item, so- // the parts catalog never needs to reach the provider.- const config = structuredClone(DEFAULT_SYNC_CONFIG);- config.entities.item.enabled = false;- config.entities.invoice.enabled = true;- config.entities.customer.enabled = true;-+ return validateSyncConfig(config);+ };++ // Bills and AR invoices are account-coded; no line names a Carbon item.+ it.each([+ ["bill", "vendor", "Bills"],+ ["invoice", "customer", "Sales Invoices"]+ ])("allows %s sync with items off", (entity, party, label) => {expect(- validateSyncConfig(config).filter((e) => e.includes("Sales Invoices"))+ withItemsOff(entity, party).filter((e) => e.includes(label))).toEqual([]);});- 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- ]);- });+ it.each(["purchaseOrder", "salesOrder", "inventoryAdjustment"])(+ "still requires items for %s, whose lines name them",+ (entity) => {+ expect(+ withItemsOff(entity, "customer", "vendor").some((e) =>+ e.includes("Items")+ )+ ).toBe(true);+ }+ );});describe("ensureProviderSubscriptions", () => {- it("upserts every required table under the provider's sync name", async () => {- const client = makeClient([]);-+ it("creates every required table as an active SYNC subscription under the provider's name", async () => {+ const { client, rows } = makeStore();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(rows.map((r) => r.table).sort()).toEqual(+ tablesOf(ProviderID.RILLET).sort());-- 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);+ for (const row of rows) {+ expect(row).toMatchObject({+ companyId: "company-1",+ name: "rillet-sync",+ handlerType: "SYNC",+ config: { provider: ProviderID.RILLET },+ active: 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" }+ it("removes this company's rows for tables no longer required, and nobody else's", async () => {+ const { client, rows } = makeStore([+ {+ id: "addr",+ companyId: "company-1",+ name: "rillet-sync",+ table: "address"+ },+ {+ id: "other-name",+ companyId: "company-1",+ name: "webhook",+ table: "address"+ },+ {+ id: "other-company",+ companyId: "company-2",+ name: "rillet-sync",+ table: "address"+ }]);-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"]);+ expect(rows.filter((r) => r.table === "address").map((r) => r.id)).toEqual([+ "other-name",+ "other-company"+ ]);});- 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- }))- );-+ it("keeps the existing rows of a fully converged install", async () => {+ const existing = tablesOf(ProviderID.XERO).map((table, index) => ({+ id: `sub_${index}`,+ companyId: "company-1",+ name: "xero-sync",+ table+ }));+ const { client, rows } = makeStore(existing);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([]);+ expect(rows.map((r) => r.id)).toEqual(existing.map((r) => r.id));});});diff --git a/packages/ee/src/accounting/core/sync-factory.test.ts b/packages/ee/src/accounting/core/sync-factory.test.tsdeleted file mode 100644index c7a375e412..0000000000--- a/packages/ee/src/accounting/core/sync-factory.test.ts+++ /dev/null@@ -1,274 +0,0 @@-// SPDX-License-Identifier: LicenseRef-Carbon-Commercial-// Carbon Enterprise file, licensed only under the Carbon Commercial License-// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.--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 { QboChargeSyncer } from "../providers/quickbooks-online/entities/charge";-import { QboCreditMemoSyncer } from "../providers/quickbooks-online/entities/credit-memo";-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 { QboReimbursementSyncer } from "../providers/quickbooks-online/entities/reimbursement";-import { QboVendorSyncer } from "../providers/quickbooks-online/entities/vendor";-import { QboVendorCreditSyncer } from "../providers/quickbooks-online/entities/vendor-credit";-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 { RilletReimbursementSyncer } from "../providers/rillet/entities/reimbursement";-import { RilletVendorSyncer } from "../providers/rillet/entities/vendor";-import { xeroSyncerRegistry } from "../providers/xero";-import { BillSyncer } from "../providers/xero/entities/bill";-import { XeroChargeSyncer } from "../providers/xero/entities/charge";-import { ContactSyncer } from "../providers/xero/entities/contact";-import { CreditMemoSyncer as XeroCreditMemoSyncer } from "../providers/xero/entities/credit-memo";-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 { XeroReimbursementSyncer } from "../providers/xero/entities/reimbursement";-import { SalesOrderSyncer } from "../providers/xero/entities/sales-order";-import { VendorCreditSyncer as XeroVendorCreditSyncer } from "../providers/xero/entities/vendor-credit";-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,- charge: XeroChargeSyncer,- invoice: SalesInvoiceSyncer,- purchaseOrder: PurchaseOrderSyncer,- salesOrder: SalesOrderSyncer,- inventoryAdjustment: InventoryAdjustmentSyncer,- journalEntry: JournalEntrySyncer,- creditMemo: XeroCreditMemoSyncer,- supplierCredit: XeroVendorCreditSyncer,- reimbursement: XeroReimbursementSyncer,- // 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,- charge: QboChargeSyncer,- invoice: QboSalesInvoiceSyncer,- purchaseOrder: QboPurchaseOrderSyncer,- journalEntry: QboJournalEntrySyncer,- creditMemo: QboCreditMemoSyncer,- supplierCredit: QboVendorCreditSyncer,- reimbursement: QboReimbursementSyncer,- 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",- "charge",- "creditMemo",- "customer",- "invoice",- "item",- "journalEntry",- "payment",- "reimbursement",- "vendor",- "supplierCredit"- ].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);- expect(- SyncFactory.getSyncer(makeContext("reimbursement", rillet))- ).toBeInstanceOf(RilletReimbursementSyncer);- });-- 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/providers/quickbooks-online/__tests__/provider.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/__tests__/provider.test.tsindex 3db0b30a74..8b6899e40b 100644--- a/packages/ee/src/accounting/providers/quickbooks-online/__tests__/provider.test.ts+++ b/packages/ee/src/accounting/providers/quickbooks-online/__tests__/provider.test.ts@@ -3,7 +3,7 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { DEFAULT_SYNC_CONFIG, ProviderID } from "../../../core/models";+import { DEFAULT_SYNC_CONFIG } from "../../../core/models";import type { ProviderCredentials } from "../../../core/types";import { AccountingApiError } from "../../../core/utils";import { Qbo } from "../models";@@ -12,7 +12,6 @@ import {extractQboErrorDetails,isQboDuplicateNameError,isQboStaleObjectError,- QBO_CDC_ENTITY_TYPES,QBO_FAULT_CODES,type QboEnvironment,QboProvider@@ -147,20 +146,6 @@ describe("QboProvider base URL", () => {`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({- role: "accounting",- transport: "rest",- supportsWebhooks: false,- supportsJournalPush: true,- maxJournalDimensionSlots: 2,- searchableCounterparts: ["customer", "vendor"],- importableEntities: ["customer", "vendor"]- });- });});describe("QboProvider refresh-on-401", () => {@@ -533,24 +518,6 @@ describe("QboProvider entity reads/writes", () => {});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();@@ -592,58 +559,17 @@ describe("listChanges (SupportsIncrementalPull)", () => {// 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);-+describe("buildQboSyncConfig", () => {+ // Inbound payment pull must work as soon as the integration connects.+ it("forces payment on as two-way and accounting-owned whatever the stored config says", () => {const stored = structuredClone(DEFAULT_SYNC_CONFIG);stored.entities.payment = {enabled: false,- direction: "two-way",+ direction: "push-to-accounting",owner: "carbon"};-expect(buildQboSyncConfig(stored).entities.payment).toEqual({enabled: true,direction: "two-way",@@ -651,22 +577,10 @@ describe("buildQboSyncConfig — payment force-enable (two-way)", () => {});});- 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",@@ -696,11 +610,8 @@ describe("buildQboSyncConfig — Carbon-owned master + documents", () => {});});- it("leaves payment accounting-owned and does not touch unforced entities", () => {+ it("passes an unforced entity through unchanged", () => {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 throughexpect(applied.entities.purchaseOrder).toEqual(DEFAULT_SYNC_CONFIG.entities.purchaseOrder);diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/charge-lifecycle.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/charge-lifecycle.test.tsindex 70fa6d500a..52f723c449 100644--- a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/charge-lifecycle.test.ts+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/charge-lifecycle.test.ts@@ -3,56 +3,31 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ type FakeDatabase,+ fakeDatabase+} from "../../../../core/fake-database-test-fixture";import type { Qbo } from "../../models";import { type QboCardCharge, QboChargeSyncer } from "../charge";-const { mappings } = vi.hoisted(() => ({- mappings: new Map<- string,- {- externalId: string;- metadata?: Record<string, unknown>;- lastSyncedAt?: string;- }- >()-}));-vi.mock("../../../../core/external-mapping", () => ({- createMappingService: () => ({- getByEntity: async (_type: string, id: string) => mappings.get(id) ?? null,- getByEntities: async (_type: string, ids: string[]) =>- new Map(- ids.flatMap((id) => (mappings.has(id) ? [[id, mappings.get(id)]] : []))- ),- getExternalId: async (_type: string, id: string) =>- mappings.get(id)?.externalId ?? null,- link: async (- _type: string,- id: string,- _provider: string,- externalId: string,- options?: { metadata?: Record<string, unknown> }- ) => {- mappings.set(id, {- externalId,- metadata: options?.metadata,- lastSyncedAt: "2026-09-10T00:00:00Z"- });- },- linkBatch: async (- rows: Array<{ entityId: string; externalId: string }>- ) => {- for (const row of rows)- mappings.set(row.entityId, { externalId: row.externalId });- }- })-}));-vi.mock("../../../../core/utils", async (importOriginal) => ({- ...(await importOriginal<typeof import("../../../../core/utils")>()),- withTriggersDisabled: async (- _db: unknown,- operation: (tx: unknown) => Promise<unknown>- ) => operation({})-}));+let db: FakeDatabase;+beforeEach(() => {+ db = fakeDatabase();+});++/** Seed the mapping a previous push left for charge `id`. */+function mapped(id: string, fields: Record<string, unknown>) {+ db.rows("externalIntegrationMapping").push({+ entityType: "charge",+ entityId: id,+ integration: "quickbooks",+ companyId: "company-1",+ metadata: null,+ ...fields+ });+}+const mappingOf = (id: string) =>+ db.rows("externalIntegrationMapping").find((row) => row.entityId === id);function local(id: string,@@ -74,7 +49,7 @@ function local(function setup(provider: object, status: QboCardCharge["status"] = "Posted") {const syncer = new QboChargeSyncer({- database: {} as never,+ database: db.database,companyId: "company-1",entityType: "charge",config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },@@ -99,12 +74,10 @@ function setup(provider: object, status: QboCardCharge["status"] = "Posted") {return syncer;}-beforeEach(() => mappings.clear());-describe("QBO charge durability", () => {it("processes loaded mixed batch rows without single refetches and isolates each failure", async () => {for (const id of ["updated", "voided", "unchanged"])- mappings.set(id, {+ mapped(id, {externalId: `remote-${id}`,lastSyncedAt: "2026-09-09T00:00:00Z"});@@ -169,12 +142,12 @@ describe("QBO charge durability", () => {expect(batch.fetchLocalBatch).toHaveBeenCalledTimes(1);expect(updatePurchase).toHaveBeenCalledTimes(1);expect(deletePurchase).toHaveBeenCalledTimes(1);- expect(mappings.get("good")?.externalId).toBe("remote-good");- expect(mappings.get("voided")?.metadata?.voided).toBe(true);+ expect(mappingOf("good")?.externalId).toBe("remote-good");+ expect(mappingOf("voided")?.metadata).toMatchObject({ voided: true });});it("preserves QBO's sparse update path for a mapped charge edited after sync", async () => {- mappings.set("a", {+ mapped("a", {externalId: "remote-a",lastSyncedAt: "2026-09-09T00:00:00Z"});@@ -203,7 +176,7 @@ describe("QBO charge durability", () => {expect(await syncer.pushToAccounting("a")).toMatchObject({status: "error"});- expect(mappings.has("a")).toBe(false);+ expect(mappingOf("a")).toBeUndefined();});it("fails closed when a void has no durable remote identity", async () => {@@ -234,7 +207,7 @@ describe("QBO charge durability", () => {})]));- expect(mappings.get("a")?.externalId).toBe("remote-a");+ expect(mappingOf("a")?.externalId).toBe("remote-a");await syncer.pushBatchToAccounting(["a", "b"]);expect(createPurchase.mock.calls.filter(([payload]) => payload.DocNumber === "a")@@ -259,7 +232,7 @@ describe("QBO charge durability", () => {});it("deletes a mapped void and records a durable tombstone", async () => {- mappings.set("a", { externalId: "remote-a", metadata: { retained: true } });+ mapped("a", { externalId: "remote-a", metadata: { retained: true } });const deletePurchase = vi.fn(async () => undefined);const syncer = setup({ deletePurchase }, "Voided");expect(await syncer.pushToAccounting("a")).toMatchObject({@@ -267,7 +240,7 @@ describe("QBO charge durability", () => {action: "deleted",remoteId: "remote-a"});- expect(mappings.get("a")?.metadata).toMatchObject({+ expect(mappingOf("a")?.metadata).toMatchObject({voided: true,retained: true});@@ -276,7 +249,7 @@ describe("QBO charge durability", () => {});it("keeps a rejected void as an error without marking the mapping deleted", async () => {- mappings.set("a", { externalId: "remote-a" });+ mapped("a", { externalId: "remote-a" });const syncer = setup({deletePurchase: async () => {@@ -289,6 +262,6 @@ describe("QBO charge durability", () => {status: "error",error: "Period locked"});- expect(mappings.get("a")?.metadata?.voided).not.toBe(true);+ expect(mappingOf("a")?.metadata).toBeNull();});});diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/charge.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/charge.test.tsindex c93edbe369..9b28a7f2b9 100644--- a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/charge.test.ts+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/charge.test.ts@@ -159,33 +159,6 @@ describe("mapChargeToQboPurchase", () => {expect(payload.DepartmentRef).toBeUndefined();});- it("uses the merchant name on the line over the line label", () => {- const payload = mapChargeToQboPurchase({- charge: charge({ merchantName: "Acme Fuel" }),- costing: costing(),- ...base- });- expect(payload.Line[0]?.Description).toBe("Acme Fuel");- });-- it("falls back to the line label when there is no merchant name", () => {- const payload = mapChargeToQboPurchase({- charge: charge({ merchantName: null }),- costing: costing(),- ...base- });- expect(payload.Line[0]?.Description).toBe("Airfare");- });-- it("falls back to the card memo when there is no merchant name or line description", () => {- const payload = mapChargeToQboPurchase({- charge: charge({ merchantName: null }),- costing: costing({ lines: [{ ...lines[0]!, description: null }] }),- ...base- });- expect(payload.Line[0]?.Description).toBe("SFO→ORD for the Apollo kickoff");- });-it("converts a foreign charge to its transaction currency and pins the reciprocal QBO rate", () => {// A CAD charge: base USD lines × 1.25 CAD per USD; QBO quotes USD per CAD.const payload = mapChargeToQboPurchase({diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/credit-memo.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/credit-memo.test.tsindex f528bd966c..a5b6f6ebef 100644--- a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/credit-memo.test.ts+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/credit-memo.test.ts@@ -5,6 +5,10 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { CREDIT_REASON_ITEM_ENTITY_TYPE } from "../../../../core/credit-reason-item";import type { ExternalIntegrationMappingService } from "../../../../core/external-mapping";+import {+ type FakeDatabase,+ fakeDatabase+} from "../../../../core/fake-database-test-fixture";import { JournalEntrySyncError } from "../../../../core/posting";import type { Qbo } from "../../models";import {@@ -26,34 +30,6 @@ import {qboVendorCreditSkipReason} from "../vendor-credit";-/**- * `recordQboMemoApplication` writes its mapping row inside- * `withTriggersDisabled`, a real Kysely transaction that opens with a `SET LOCAL`- * statement. Stub it so the row lands in `mappingRows` instead — that map is the- * durable store the resumability test reads back.- */-const { mappingRows } = vi.hoisted(() => ({- mappingRows: new Map<string, string>()-}));-vi.mock("../../../../core/utils", async (importOriginal) => ({- ...(await importOriginal<typeof import("../../../../core/utils")>()),- withTriggersDisabled: async (- _db: unknown,- cb: (tx: unknown) => Promise<unknown>- ) => {- const builder: Record<string, any> = {};- builder.values = (value: any) => {- for (const row of Array.isArray(value) ? value : [value]) {- mappingRows.set(`${row.entityType}::${row.entityId}`, row.externalId);- }- return builder;- };- builder.onConflict = () => builder;- builder.execute = async () => [];- return cb({ insertInto: () => builder });- }-}));-const INTEGRATION = "quickbooks";const REASON_ACCOUNT_REF: Qbo.Ref = { value: "84", name: "Sales Returns" };@@ -416,48 +392,69 @@ function settlement(}/**- * Drives `upsertRemote` (and so `applySettlements`) with no QBO and no database.- *- * `mappingRows` is the DURABLE store: `recordQboMemoApplication` writes into it- * through the mocked `withTriggersDisabled` above, and the same rows back- * `mappingService.getExternalId` — so a second push really does see what the- * first one recorded, which is the whole claim of the resumability test.+ * The company and mappings the memo pushes read: the settled documents are+ * already in QuickBooks, and the bank account is mapped. `db` is reset per test+ * and outlives a syncer, so a second push sees the application rows the first+ * one recorded — the whole claim of the resumability test.*/+let db: FakeDatabase;+beforeEach(() => {+ const mapping = (+ entityType: string,+ entityId: string,+ externalId: string+ ) => ({+ entityType,+ entityId,+ integration: INTEGRATION,+ companyId: "company-1",+ externalId+ });+ db = fakeDatabase({+ company: [{ id: "company-1", baseCurrencyCode: "USD" }],+ accountDefault: [+ {+ companyId: "company-1",+ payablesAccount: "acc_ap",+ bankCashAccount: "acc_bank"+ }+ ],+ externalIntegrationMapping: [+ mapping("invoice", "si_1", "qbo-invoice-si_1"),+ mapping("invoice", "si_2", "qbo-invoice-si_2"),+ mapping("bill", "pi_1", "qbo-bill-pi_1"),+ mapping("account", "acc_bank", "60")+ ]+ });+});+const applicationMapping = (entityId: string) =>+ db+ .rows("externalIntegrationMapping")+ .find(+ (row) =>+ row.entityType === "qboMemoApplication" && row.entityId === entityId+ )?.externalId;++/** Drives `upsertRemote` (and so `applySettlements`) with no QBO. */function makeCreditMemoSyncer(args: {memo: QboMemoSource;applyCreditMemo?: ReturnType<typeof vi.fn>;- baseCurrencyCode?: string;}) {const applyCreditMemo =args.applyCreditMemo ?? vi.fn(async () => "qbo-payment-1");const createCreditMemo = vi.fn(async () => ({ Id: "qbo-cm-1" }));const syncer = new QboCreditMemoSyncer({- database: {} as never,+ database: db.database,companyId: "company-1",provider: { id: INTEGRATION, createCreditMemo, applyCreditMemo } as never,config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },entityType: "creditMemo"});-- const patched = syncer as unknown as Record<string, any>;- patched.mappingService = {- getByEntity: vi.fn(async () => null),- getExternalId: vi.fn(async (entityType: string, entityId: string) =>- entityType === "invoice"- ? `qbo-invoice-${entityId}`- : (mappingRows.get(`${entityType}::${entityId}`) ?? null)- )- };- // The one company read `upsertRemote` needs — stubbed rather than faked,- // there is no database in this process.- patched.baseCurrencyCodePromise = Promise.resolve(- args.baseCurrencyCode ?? "USD"- );vi.spyOn(syncer, "fetchLocal").mockResolvedValue(args.memo);const push = () =>- patched.upsertRemote(+ (syncer as unknown as Record<string, any>).upsertRemote({ CustomerRef: { value: "17" } } as never,args.memo.id) as Promise<string>;@@ -469,14 +466,13 @@ function makeCreditMemoSyncer(args: {function makeVendorCreditSyncer(args: {memo: QboMemoSource;applyVendorCredit?: ReturnType<typeof vi.fn>;- baseCurrencyCode?: string;}) {const applyVendorCredit =args.applyVendorCredit ?? vi.fn(async () => "qbo-billpayment-1");const createVendorCredit = vi.fn(async () => ({ Id: "qbo-vc-1" }));const syncer = new QboVendorCreditSyncer({- database: {} as never,+ database: db.database,companyId: "company-1",provider: {id: INTEGRATION,@@ -486,30 +482,10 @@ function makeVendorCreditSyncer(args: {config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },entityType: "supplierCredit"});-- const patched = syncer as unknown as Record<string, any>;- patched.mappingService = {- getByEntity: vi.fn(async () => null),- getExternalId: vi.fn(async (entityType: string, entityId: string) =>- entityType === "bill"- ? `qbo-bill-${entityId}`- : (mappingRows.get(`${entityType}::${entityId}`) ?? null)- )- };- patched.accountDefaultsPromise = Promise.resolve({- payablesAccount: "acc_ap",- bankCashAccount: "acc_bank"- });- patched.accountRefsByIdPromise = Promise.resolve(- new Map<string, Qbo.Ref>([["acc_bank", { value: "60" }]])- );- patched.baseCurrencyCodePromise = Promise.resolve(- args.baseCurrencyCode ?? "USD"- );vi.spyOn(syncer, "fetchLocal").mockResolvedValue(args.memo);const push = () =>- patched.upsertRemote(+ (syncer as unknown as Record<string, any>).upsertRemote({ VendorRef: { value: "55" } } as never,args.memo.id) as Promise<string>;@@ -615,10 +591,6 @@ describe("the cross-currency application guard (parity with Xero)", () => {});describe("QboCreditMemoSyncer.applySettlements", () => {- beforeEach(() => {- mappingRows.clear();- });-it("sends the DOCUMENT-currency principal for a foreign memo, not the base amount", async () => {// EUR 100.00 at 0.92 EUR per USD of base: appliedAmount is 108.70 base.const { push, applyCreditMemo } = makeCreditMemoSyncer({@@ -722,9 +694,7 @@ describe("QboCreditMemoSyncer.applySettlements", () => {await expect(first.push()).rejects.toThrow("500");// The whole point: linkEntities never ran, so the memo's own mapping// metadata was never written — the per-application row is what survives.- expect(mappingRows.get("qboMemoApplication::memo_1:st_1")).toBe(- "qbo-payment-1"- );+ expect(applicationMapping("memo_1:st_1")).toBe("qbo-payment-1");const second = makeCreditMemoSyncer({ memo: memoWithTwo });await second.push();@@ -736,17 +706,11 @@ describe("QboCreditMemoSyncer.applySettlements", () => {Line: Array<{ LinkedTxn: Array<{ TxnId: string }> }>;};expect(retried.Line[0]?.LinkedTxn[0]?.TxnId).toBe("qbo-invoice-si_2");- expect(mappingRows.get("qboMemoApplication::memo_1:st_2")).toBe(- "qbo-payment-1"- );+ expect(applicationMapping("memo_1:st_2")).toBe("qbo-payment-1");});});describe("QboVendorCreditSyncer.applySettlements", () => {- beforeEach(() => {- mappingRows.clear();- });-it("sends CurrencyRef and the inverted ExchangeRate on a FOREIGN BillPayment", async () => {const { push, applyVendorCredit } = makeVendorCreditSyncer({memo: supplierMemo({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.tsindex 28dd5925cf..003c255819 100644--- 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.ts@@ -2,7 +2,8 @@// Carbon Enterprise file, licensed only under the Carbon Commercial License// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.-import { beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";+import { fakeDatabase } from "../../../../core/fake-database-test-fixture";import {isJournalEntrySyncFailure,JournalEntrySyncError@@ -186,39 +187,6 @@ describe("mapItemToQboItem (mapping fixture with account resolution)", () => {});});-const { shippingLinks, linkControl } = vi.hoisted(() => ({- shippingLinks: [] as Array<Record<string, unknown>>,- linkControl: { failOnce: false }-}));-vi.mock("../../../../core/utils", async (original) => ({- ...(await original<typeof import("../../../../core/utils")>()),- withTriggersDisabled: async (- _database: unknown,- callback: (tx: unknown) => Promise<unknown>- ) => {- const builder: any = {- values(values: Record<string, unknown>) {- shippingLinks.push(values);- return builder;- },- onConflict() {- return builder;- },- async execute() {- if (linkControl.failOnce) {- linkControl.failOnce = false;- throw new Error("link failed");- }- return [];- }- };- return callback({ insertInto: () => builder });- }-}));-beforeEach(() => {- shippingLinks.length = 0;- linkControl.failOnce = false;-});const shippingItem = (overrides: Partial<Qbo.Item> = {}): Qbo.Item => ({Id: "shipping-remote",SyncToken: "1",@@ -235,9 +203,31 @@ function shippingSyncer(existing?: Qbo.Item;matches?: Qbo.Item[];create?: ReturnType<typeof vi.fn>;- refs?: Map<string, Qbo.Ref>;+ /** Carbon account id → the QBO account it is mapped to. */+ refs?: Record<string, string>;} = {}) {+ const mapping = (+ entityType: string,+ entityId: string,+ externalId: string+ ) => ({+ entityType,+ entityId,+ integration: "quickbooks",+ companyId: "company-1",+ externalId+ });+ const db = fakeDatabase({+ externalIntegrationMapping: [+ ...Object.entries(+ args.refs ?? { "acct-shipping": "income-shipping" }+ ).map(([accountId, ref]) => mapping("account", accountId, ref)),+ ...(args.existingId+ ? [mapping("shippingItem", "acct-shipping", args.existingId)]+ : [])+ ]+ });const query = vi.fn(async (_entity: string, _where?: string) => args.matches ?? []);@@ -247,7 +237,7 @@ function shippingSyncer(vi.fn(async (_payload: QboCreatePayload<Qbo.Item>) => shippingItem());const updateItem = vi.fn(async (payload: Qbo.Item) => payload);const syncer = new QboItemSyncer({- database: {} as never,+ database: db.database,companyId: "company-1",provider: {id: "quickbooks",@@ -259,12 +249,18 @@ function shippingSyncer(config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },entityType: "item"});- (syncer as any).mappingService = {- getExternalId: vi.fn(async () => args.existingId ?? null)+ return {+ syncer,+ db,+ query,+ getItem,+ createItem,+ updateItem,+ helperLinks: () =>+ db+ .rows("externalIntegrationMapping")+ .filter((row) => row.entityType === "shippingItem")};- (syncer as any).getAccountRefsById = async () =>- args.refs ?? new Map([["acct-shipping", { value: "income-shipping" }]]);- return { syncer, query, getItem, createItem, updateItem };}describe("QBO shipping helper identity", () => {it("creates one sales-only Service per shipping account and caches reuse", async () => {@@ -288,14 +284,16 @@ describe("QBO shipping helper identity", () => {UnitPrice: 0,IncomeAccountRef: { value: "income-shipping" }});- expect(shippingLinks[0]).toMatchObject({- entityType: "shippingItem",- entityId: "acct-shipping",- integration: "quickbooks",- externalId: "shipping-remote",- companyId: "company-1",- metadata: { accountId: "acct-shipping", kind: "shipping" }- });+ expect(test.helperLinks()).toMatchObject([+ {+ entityType: "shippingItem",+ entityId: "acct-shipping",+ integration: "quickbooks",+ externalId: "shipping-remote",+ companyId: "company-1",+ metadata: { accountId: "acct-shipping", kind: "shipping" }+ }+ ]);expect(test.query).toHaveBeenCalledOnce();});it("reuses an owned compatible helper mapping without a create or name lookup", async () => {@@ -310,7 +308,10 @@ describe("QBO shipping helper identity", () => {});it("recovers remote-create/local-link retries through the exact compatible remote name", async () => {const test = shippingSyncer();- linkControl.failOnce = true;+ test.db.failNextWrite(+ "externalIntegrationMapping",+ new Error("link failed")+ );await expect(test.syncer.ensureShippingItem({ shippingAccountId: "acct-shipping" })).rejects.toThrow("link failed");@@ -346,7 +347,7 @@ describe("QBO shipping helper identity", () => {})).toBe("shipping-remote");expect(test.createItem).toHaveBeenCalledOnce();- expect(shippingLinks).toHaveLength(1);+ expect(test.helperLinks()).toHaveLength(1);});it.each([{ Type: "NonInventory" },@@ -365,7 +366,7 @@ describe("QBO shipping helper identity", () => {});expect(test.createItem).not.toHaveBeenCalled();expect(test.updateItem).not.toHaveBeenCalled();- expect(shippingLinks).toEqual([]);+ expect(test.helperLinks()).toEqual([]);});it("reconverges only an owned helper with the current SyncToken", async () => {@@ -401,7 +402,7 @@ describe("QBO shipping helper identity", () => {);});it("fails unmapped shipping before remote reads/writes", async () => {- const test = shippingSyncer({ refs: new Map() });+ const test = shippingSyncer({ refs: {} });await expect(test.syncer.ensureShippingItem({ shippingAccountId: "acct-shipping" })).rejects.toMatchObject({diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/reimbursement-employee-vendor.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/reimbursement-employee-vendor.test.tsindex aae2b5e8d3..aa722cdbbf 100644--- a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/reimbursement-employee-vendor.test.ts+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/reimbursement-employee-vendor.test.ts@@ -3,6 +3,10 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ type FakeDatabase,+ fakeDatabase+} from "../../../../core/fake-database-test-fixture";import type { ReimbursementSource } from "../../../../core/reimbursement-source";import { AccountingApiError } from "../../../../core/utils";import type { Qbo } from "../../models";@@ -15,33 +19,18 @@ import { QboReimbursementSyncer } from "../reimbursement";// unique, so the retry's create fails with fault 6240. Without adoption that// reimbursement can never sync again.-const { mappings } = vi.hoisted(() => ({- mappings: new Map<string, string>()-}));--vi.mock("../../../../core/external-mapping", () => ({- createMappingService: () => ({- getByEntity: async () => null,- getExternalId: async (_type: string, id: string) =>- mappings.get(id) ?? null,- link: async (- _type: string,- id: string,- _provider: string,- externalId: string- ) => {- mappings.set(id, externalId);- }- })-}));--vi.mock("../../../../core/utils", async (importOriginal) => ({- ...(await importOriginal<typeof import("../../../../core/utils")>()),- withTriggersDisabled: async (- _db: unknown,- operation: (tx: unknown) => Promise<unknown>- ) => operation({})-}));+let db: FakeDatabase;+beforeEach(() => {+ db = fakeDatabase();+});+/** The QBO vendor the employee is mapped to, if any. */+const employeeVendorMapping = (employeeId: string) =>+ db+ .rows("externalIntegrationMapping")+ .find(+ (row) =>+ row.entityType === "employeeVendor" && row.entityId === employeeId+ )?.externalId;const reimbursement: ReimbursementSource = {id: "reimb_1",@@ -95,7 +84,7 @@ function duplicateNameFault(): AccountingApiError {function syncer(provider: object) {const instance = new QboReimbursementSyncer({- database: {} as never,+ database: db.database,companyId: "company-1",entityType: "reimbursement",config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },@@ -106,8 +95,6 @@ function syncer(provider: object) {};}-beforeEach(() => mappings.clear());-describe("QBO employee-vendor JIT create", () => {it("keys the create on a deterministic requestid so Intuit replays a lost response", async () => {const createVendor = vi.fn(async () => ({ Id: "vend_9" }) as Qbo.Vendor);@@ -121,7 +108,7 @@ describe("QBO employee-vendor JIT create", () => {buildQboRequestId("company-1", "employee-vendor", "emp_1"));// The mapping the next attempt reads instead of creating again.- expect(mappings.get("emp_1")).toBe("vend_9");+ expect(employeeVendorMapping("emp_1")).toBe("vend_9");});it("adopts the existing Vendor on fault 6240 instead of failing forever", async () => {@@ -144,7 +131,7 @@ describe("QBO employee-vendor JIT create", () => {);// The adoption is what makes the retry recoverable: the mapping the first// attempt failed to write is written now.- expect(mappings.get("emp_1")).toBe("vend_orphan");+ expect(employeeVendorMapping("emp_1")).toBe("vend_orphan");});it("rethrows fault 6240 when the colliding name belongs to no Vendor", async () => {@@ -158,7 +145,7 @@ describe("QBO employee-vendor JIT create", () => {await expect(syncer({ createVendor, query }).resolveEmployeeVendor(reimbursement)).rejects.toThrow(/Duplicate Name Exists/);- expect(mappings.size).toBe(0);+ expect(db.rows("externalIntegrationMapping")).toEqual([]);});it("does not swallow a non-duplicate fault", async () => {diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/reimbursement.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/reimbursement.test.tsindex 0d0e9db168..bbdf39f3df 100644--- a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/reimbursement.test.ts+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/reimbursement.test.ts@@ -2,7 +2,8 @@// Carbon Enterprise file, licensed only under the Carbon Commercial License// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.-import { beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";+import { fakeDatabase } from "../../../../core/fake-database-test-fixture";import { JournalEntrySyncError } from "../../../../core/posting";import type { ReimbursementSource } from "../../../../core/reimbursement-source";import type { Qbo } from "../../models";@@ -17,33 +18,6 @@ import {// carrying Carbon's SEGREGATED employee-payable control account rather than// letting QBO imply the trade-AP account.-/**- * The JIT vendor's mapping row is written inside `withTriggersDisabled`, a real- * Kysely transaction that opens with a `SET LOCAL` statement. Stub it so the row- * lands in `mappingRows` — the store the re-read under test then reads back.- */-const { mappingRows } = vi.hoisted(() => ({- mappingRows: new Map<string, string>()-}));-vi.mock("../../../../core/utils", async (importOriginal) => ({- ...(await importOriginal<typeof import("../../../../core/utils")>()),- withTriggersDisabled: async (- _db: unknown,- cb: (tx: unknown) => Promise<unknown>- ) => {- const builder: Record<string, any> = {};- builder.values = (value: any) => {- for (const row of Array.isArray(value) ? value : [value]) {- mappingRows.set(`${row.entityType}::${row.entityId}`, row.externalId);- }- return builder;- };- builder.onConflict = () => builder;- builder.execute = async () => [];- return cb({ insertInto: () => builder });- }-}));-const reimbursement = (overrides: Partial<ReimbursementSource> = {}): ReimbursementSource => ({@@ -219,7 +193,21 @@ describe("mapReimbursementToQboBill", () => {* failed with Intuit fault 6240 and parked Failed. A Posted reimbursement's* `updatedAt` never changes, so nothing re-enqueued it without a human Retry.*/-function makeEmployeeVendorSyncer() {+/** `mappedTo`: the Vendor the employee is already mapped to. */+function makeEmployeeVendorSyncer(mappedTo?: string) {+ const db = fakeDatabase({+ externalIntegrationMapping: mappedTo+ ? [+ {+ entityType: "employeeVendor",+ entityId: "emp_1",+ integration: "quickbooks",+ companyId: "company-1",+ externalId: mappedTo+ }+ ]+ : []+ });let created = 0;const createVendor = vi.fn(async () => {created += 1;@@ -227,31 +215,28 @@ function makeEmployeeVendorSyncer() {});const syncer = new QboReimbursementSyncer({- database: {} as never,+ database: db.database,companyId: "company-1",provider: { id: "quickbooks", createVendor } as never,config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },entityType: "reimbursement"});- (syncer as any).mappingService = {- getExternalId: async (entityType: string, entityId: string) =>- mappingRows.get(`${entityType}::${entityId}`) ?? null- };-return {resolve: (local: ReimbursementSource) =>(syncer as any).resolveEmployeeVendor(local) as Promise<string>,createVendor,- store: mappingRows+ employeeMapping: () =>+ db+ .rows("externalIntegrationMapping")+ .find(+ (row) =>+ row.entityType === "employeeVendor" && row.entityId === "emp_1"+ )?.externalId};}describe("QboReimbursementSyncer.resolveEmployeeVendor", () => {- beforeEach(() => {- mappingRows.clear();- });-it("creates the employee Vendor ONCE for two reimbursements in one batch", async () => {const test = makeEmployeeVendorSyncer();// Both snapshots come from the SAME fetchLocalBatch, so both say null.@@ -262,12 +247,11 @@ describe("QboReimbursementSyncer.resolveEmployeeVendor", () => {expect(test.createVendor).toHaveBeenCalledTimes(1);expect(second).toBe(first);- expect(test.store.get("employeeVendor::emp_1")).toBe(first);+ expect(test.employeeMapping()).toBe(first);});it("reuses an already-mapped Vendor without creating one", async () => {- const test = makeEmployeeVendorSyncer();- test.store.set("employeeVendor::emp_1", "qbo-vendor-77");+ const test = makeEmployeeVendorSyncer("qbo-vendor-77");expect(await test.resolve(reimbursement({ employeeVendorExternalId: null }))diff --git a/packages/ee/src/accounting/providers/rillet/__tests__/provider.test.ts b/packages/ee/src/accounting/providers/rillet/__tests__/provider.test.tsindex 86ce0c7acd..e2b5af915a 100644--- a/packages/ee/src/accounting/providers/rillet/__tests__/provider.test.ts+++ b/packages/ee/src/accounting/providers/rillet/__tests__/provider.test.ts@@ -3,7 +3,7 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { DEFAULT_SYNC_CONFIG, ProviderID } from "../../../core/models";+import { DEFAULT_SYNC_CONFIG } from "../../../core/models";import type {GlobalSyncConfig,ProviderCredentials@@ -109,33 +109,9 @@ describe("RilletProvider base URL + headers", () => {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({- role: "accounting",- transport: "rest",- supportsWebhooks: true,- supportsJournalPush: true,- searchableCounterparts: ["customer", "vendor"],- importableEntities: ["customer", "vendor"]- });- });});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 });@@ -501,7 +477,7 @@ describe("buildRilletSyncConfig", () => {}).entities.journalEntry.enabled).toBe(true);- // Payment: two-way (pull inbound + push Carbon-born outbound, Phase G),+ // Payment: two-way (pull inbound + push Carbon-born outbound),// owner accounting, and FORCED enabled (no per-company toggle — the// documents-mode families gate governs whether it runs)expect(built.entities.payment).toEqual({@@ -519,10 +495,6 @@ describe("buildRilletSyncConfig", () => {});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({diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/charge.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/charge.test.tsindex 478de3bb55..6f17ece259 100644--- a/packages/ee/src/accounting/providers/rillet/entities/__tests__/charge.test.ts+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/charge.test.ts@@ -119,35 +119,6 @@ describe("mapChargeToRilletCharge", () => {expect(payload.items[0]?.fields).toBeUndefined();});- it("uses the merchant name on the line over the line label", () => {- const payload = mapChargeToRilletCharge({- charge: charge({ merchantName: "Acme Fuel" }),- costing: costing(),- ...base- });- expect(payload.items[0]?.description).toBe("Acme Fuel");- });-- it("falls back to the line label when there is no merchant name", () => {- const payload = mapChargeToRilletCharge({- charge: charge({ merchantName: null }),- costing: costing(),- ...base- });- expect(payload.items[0]?.description).toBe("Airfare");- });-- it("falls back to the card memo when there is no merchant name or line description", () => {- const payload = mapChargeToRilletCharge({- charge: charge({ merchantName: null }),- costing: costing({ lines: [{ ...lines[0]!, description: null }] }),- ...base- });- expect(payload.items[0]?.description).toBe(- "SFO→ORD for the Apollo kickoff"- );- });-it("converts a foreign charge to its transaction currency and pins the directed rate", () => {// A CAD charge: base USD lines × 1.25 CAD per USD.const payload = mapChargeToRilletCharge({diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/credit-memo.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/credit-memo.test.tsindex efb07bb65f..075332af13 100644--- a/packages/ee/src/accounting/providers/rillet/entities/__tests__/credit-memo.test.ts+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/credit-memo.test.ts@@ -3,6 +3,10 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ accountMappingRows,+ fakeDatabase+} from "../../../../core/fake-database-test-fixture";import { JournalEntrySyncError } from "../../../../core/posting";import type {Rillet,@@ -24,45 +28,6 @@ import {RilletVendorCreditSyncer} from "../vendor-credit";-// The syncers' DB loaders are stubbed; everything else in ./shared (the base-// class above all) stays real, so the push workflow under test is the-// production one.-vi.mock("../shared", async (importOriginal) => {- const original = await importOriginal<typeof import("../shared")>();- return {- ...original,- loadRilletAccountCodesById: vi.fn(- async () => new Map([["acct_returns", "4200"]])- ),- loadCompanyBaseCurrency: vi.fn(async () => "USD"),- loadCurrencyDecimalPlaces: vi.fn(async () => 2),- loadRilletMemoReasonAccount: vi.fn(async () => ({- accountId: "acct_returns",- name: "Sales Returns & Allowances",- number: "4200"- }))- };-});--const { linked } = vi.hoisted(() => ({ linked: [] as unknown[] }));-vi.mock("../../../../core/utils", async (importOriginal) => ({- ...(await importOriginal<typeof import("../../../../core/utils")>()),- withTriggersDisabled: async (- _db: unknown,- cb: (tx: unknown) => Promise<unknown>- ) => {- const b = {- values: (row: unknown) => {- linked.push(row);- return b;- },- onConflict: () => b,- execute: async () => []- };- return cb({ insertInto: () => b });- }-}));-const customerMemo = (overrides: Partial<RilletMemoSource> = {}): CreditMemoSource => ({@@ -261,21 +226,26 @@ describe("application sets", () => {});});-/** In-memory ExternalIntegrationMappingService stand-in. */-function fakeMappingService(store = new Map<string, string>()) {- return {- store,- getByEntity: vi.fn(async () => null),- getExternalId: vi.fn(- async (entityType: string, entityId: string) =>- store.get(`${entityType}:${entityId}`) ?? null- ),- link: vi.fn(- async (entityType: string, entityId: string, _i: string, id: string) => {- store.set(`${entityType}:${entityId}`, id);+/** The company, its currency and the reason account the memo syncers read. */+function memoDatabase() {+ return fakeDatabase({+ company: [+ { id: "company-1", baseCurrencyCode: "USD", companyGroupId: "group-1" }+ ],+ currency: [{ code: "USD", companyGroupId: "group-1", decimalPlaces: 2 }],+ account: [+ {+ id: "acct_returns",+ companyGroupId: "group-1",+ name: "Sales Returns & Allowances",+ number: "4200"}+ ],+ externalIntegrationMapping: accountMappingRows(+ { acct_returns: "4200" },+ "rillet")- };+ });}/** `POST /products` stub, typed so `mock.calls` keeps its argument tuple. */@@ -287,10 +257,10 @@ function makeCreateProduct() {function setupCreditMemoSyncer(args: {memo: CreditMemoSource;- mappingStore?: Map<string, string>;+ /** Shared between syncers to carry the reason product's mapping across. */+ db?: ReturnType<typeof memoDatabase>;createProduct?: ReturnType<typeof makeCreateProduct>;}) {- linked.length = 0;const applyCreditMemo = vi.fn(async (_id: string, _applications: Rillet.CreditMemoApplication[]) =>undefined@@ -301,7 +271,7 @@ function setupCreditMemoSyncer(args: {const createProduct = args.createProduct ?? makeCreateProduct();const syncer = new RilletCreditMemoSyncer({- database: {} as never,+ database: (args.db ?? memoDatabase()).database,companyId: "company-1",entityType: "creditMemo",config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },@@ -315,7 +285,6 @@ function setupCreditMemoSyncer(args: {});vi.spyOn(syncer, "fetchLocal").mockResolvedValue(args.memo);- (syncer as any).mappingService = fakeMappingService(args.mappingStore);(syncer as any).ensureDependencySynced = vi.fn(async (_type: string, localId: string) => `rillet-invoice-${localId}`);@@ -376,19 +345,19 @@ describe("RilletCreditMemoSyncer", () => {});it("creates the reason product once and reuses it for a second memo", async () => {- const mappingStore = new Map<string, string>();+ const db = memoDatabase();const createProduct = makeCreateProduct();const first = setupCreditMemoSyncer({memo: customerMemo(),- mappingStore,+ db,createProduct});await first.syncer.pushToAccounting("memo_1");const second = setupCreditMemoSyncer({memo: customerMemo({ id: "memo_9", memoId: "CM-2026-0009" }),- mappingStore,+ db,createProduct});await second.syncer.pushToAccounting("memo_9");@@ -423,7 +392,7 @@ function setupVendorCreditSyncer(memo: RilletMemoSource) {undefined);const syncer = new RilletVendorCreditSyncer({- database: {} as never,+ database: memoDatabase().database,companyId: "company-1",entityType: "supplierCredit",config: {@@ -440,7 +409,6 @@ function setupVendorCreditSyncer(memo: RilletMemoSource) {} as never});vi.spyOn(syncer, "fetchLocal").mockResolvedValue(memo);- (syncer as any).mappingService = fakeMappingService();(syncer as any).ensureDependencySynced = vi.fn(async (_type: string, localId: string) => `rillet-bill-${localId}`);diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/document-void.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/document-void.test.tsindex b72dcd1e1d..2d4bec6588 100644--- a/packages/ee/src/accounting/providers/rillet/entities/__tests__/document-void.test.ts+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/document-void.test.ts@@ -3,41 +3,38 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.import { describe, expect, it, vi } from "vitest";+import { fakeDatabase } from "../../../../core/fake-database-test-fixture";import { RilletBillSyncer } from "../bill";import { RilletChargeSyncer } from "../charge";import { RilletSalesInvoiceSyncer } from "../invoice";-const { linked } = vi.hoisted(() => ({ linked: [] as unknown[] }));-vi.mock("../../../../core/utils", async (importOriginal) => ({- ...(await importOriginal<typeof import("../../../../core/utils")>()),- withTriggersDisabled: async (- _db: unknown,- cb: (tx: unknown) => Promise<unknown>- ) => {- const b = {- values: (row: unknown) => {- linked.push(row);- return b;- },- onConflict: () => b,- execute: async () => []- };- return cb({ insertInto: () => b });- }-}));-describe.each([["invoice", RilletSalesInvoiceSyncer],["bill", RilletBillSyncer],["charge", RilletChargeSyncer]] as const)("Rillet %s void", (entityType, Syncer) => {- function setup(status: string, mapping: unknown, failure?: Error) {- linked.length = 0;+ function setup(+ status: string,+ mapping: { externalId: string; metadata?: Record<string, unknown> },+ failure?: Error+ ) {+ const db = fakeDatabase({+ externalIntegrationMapping: [+ {+ entityType,+ entityId: "doc-1",+ integration: "rillet",+ companyId: "company-1",+ metadata: null,+ ...mapping+ }+ ]+ });const deletion = failure? vi.fn().mockRejectedValue(failure): vi.fn().mockResolvedValue(undefined);const syncer = new Syncer({- database: {} as never,+ database: db.database,companyId: "company-1",entityType,config: {@@ -56,11 +53,14 @@ describe.each([id: "doc-1",status} as never);- (syncer as any).mappingService = { getByEntity: async () => mapping };- return { syncer, deletion };+ return {+ syncer,+ deletion,+ mapping: () => db.rows("externalIntegrationMapping")[0]+ };}it("propagates a mapped void before the existing mapping fast bailout", async () => {- const { syncer, deletion } = setup("Voided", {+ const { syncer, deletion, mapping } = setup("Voided", {externalId: "remote-1",metadata: { retained: true }});@@ -70,7 +70,7 @@ describe.each([remoteId: "remote-1"});expect(deletion).toHaveBeenCalledWith("remote-1");- expect(linked[0]).toMatchObject({+ expect(mapping()).toMatchObject({entityId: "doc-1",externalId: "remote-1",metadata: { retained: true, voided: true }@@ -88,7 +88,7 @@ describe.each([expect(deletion).not.toHaveBeenCalled();});it("does not hide failed remote deletion behind the old mapping", async () => {- const { syncer } = setup(+ const { syncer, mapping } = setup("Voided",{ externalId: "remote-1" },new Error("document has payments")@@ -97,7 +97,7 @@ describe.each([status: "error",error: "document has payments"});- expect(linked).toHaveLength(0);+ expect(mapping()?.metadata).toBeNull();});it("keeps ordinary posted replay immutable", async () => {const { syncer, deletion } = setup("Submitted", { externalId: "remote-1" });diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/item.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/item.test.tsindex bb475a25fc..1341d3dd41 100644--- a/packages/ee/src/accounting/providers/rillet/entities/__tests__/item.test.ts+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/item.test.ts@@ -2,7 +2,11 @@// Carbon Enterprise file, licensed only under the Carbon Commercial License// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.-import { beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";+import {+ accountMappingRows,+ fakeDatabase+} from "../../../../core/fake-database-test-fixture";import type { Rillet, RilletProductWrite } from "../../models";import { buildRilletIdempotencyKey } from "../../provider";import { RilletItemSyncer } from "../item";@@ -25,39 +29,6 @@ describe("Rillet monetary decimal strings", () => {);});-const { links, control } = vi.hoisted(() => ({- links: [] as Array<Record<string, unknown>>,- control: { failOnce: false }-}));-vi.mock("../../../../core/utils", async (original) => ({- ...(await original<typeof import("../../../../core/utils")>()),- withTriggersDisabled: async (- _db: unknown,- callback: (tx: unknown) => Promise<unknown>- ) => {- const builder: any = {- values(value: Record<string, unknown>) {- links.push(value);- return builder;- },- onConflict() {- return builder;- },- async execute() {- if (control.failOnce) {- control.failOnce = false;- throw new Error("link failed");- }- return [];- }- };- return callback({ insertInto: () => builder });- }-}));-beforeEach(() => {- links.length = 0;- control.failOnce = false;-});const product = (overrides: Partial<Rillet.Product> = {}): Rillet.Product => ({id: "shipping-product",name: "Carbon Shipping acct-shipping USD",@@ -69,13 +40,35 @@ const product = (overrides: Partial<Rillet.Product> = {}): Rillet.Product => ({revenue_pattern: "EVEN_PERIOD",...overrides});+const mapping = (entityType: string, entityId: string, externalId: string) => ({+ entityType,+ entityId,+ integration: "rillet",+ companyId: "company-1",+ externalId+});+function setup(args: {+ /** The product the shipping helper is already mapped to. */mappedId?: string;current?: Rillet.Product;- codes?: Map<string, string>;+ codes?: Record<string, string>;+ mappings?: Array<Record<string, unknown>>;} = {}) {+ const db = fakeDatabase({+ externalIntegrationMapping: [+ ...accountMappingRows(+ args.codes ?? { "acct-shipping": "4010" },+ "rillet"+ ),+ ...(args.mappedId+ ? [mapping("shippingItem", "acct-shipping:USD", args.mappedId)]+ : []),+ ...(args.mappings ?? [])+ ]+ });const getProduct = vi.fn(async (_id: string) => args.current ?? product());const createProduct = vi.fn(async (_payload: RilletProductWrite, _key?: string) => product()@@ -87,7 +80,7 @@ function setup(}));const syncer = new RilletItemSyncer({- database: {} as never,+ database: db.database,companyId: "company-1",provider: {id: "rillet",@@ -98,12 +91,17 @@ function setup(config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },entityType: "item"});- (syncer as any).mappingService = {- getExternalId: vi.fn(async () => args.mappedId ?? null)+ return {+ syncer,+ db,+ getProduct,+ createProduct,+ updateProduct,+ helperLinks: () =>+ db+ .rows("externalIntegrationMapping")+ .filter((row) => row.entityType === "shippingItem")};- (syncer as any).getAccountCodesById = async () =>- args.codes ?? new Map([["acct-shipping", "4010"]]);- return { syncer, getProduct, createProduct, updateProduct };}const shipping = {shippingAccountId: "acct-shipping",@@ -136,14 +134,16 @@ describe("Rillet shipping product helper", () => {localId: "acct-shipping:USD"}));- expect(links[0]).toMatchObject({- entityType: "shippingItem",- entityId: "acct-shipping:USD",- integration: "rillet",- companyId: "company-1",- externalId: "shipping-product",- metadata: { accountId: "acct-shipping", kind: "shipping" }- });+ expect(test.helperLinks()).toMatchObject([+ {+ entityType: "shippingItem",+ entityId: "acct-shipping:USD",+ integration: "rillet",+ companyId: "company-1",+ externalId: "shipping-product",+ metadata: { accountId: "acct-shipping", kind: "shipping" }+ }+ ]);});it("reuses an owned compatible mapping without another create", async () => {const test = setup({ mappedId: "shipping-product" });@@ -154,7 +154,10 @@ describe("Rillet shipping product helper", () => {});it("retries a lost local link using the same entity-scoped idempotency key", async () => {const test = setup();- control.failOnce = true;+ test.db.failNextWrite(+ "externalIntegrationMapping",+ new Error("link failed")+ );await expect(test.syncer.ensureShippingProduct(shipping)).rejects.toThrow("link failed");@@ -210,10 +213,10 @@ describe("Rillet shipping product helper", () => {amount: "0.000",currency: "BHD"});- expect(links[0]?.entityId).toBe("acct-shipping:BHD");+ expect(test.helperLinks()[0]?.entityId).toBe("acct-shipping:BHD");});it("refuses an unmapped shipping account before any provider write", async () => {- const test = setup({ codes: new Map() });+ const test = setup({ codes: {} });await expect(test.syncer.ensureShippingProduct(shipping)).rejects.toMatchObject({@@ -224,9 +227,9 @@ describe("Rillet shipping product helper", () => {});it("preserves unrelated full-product fields on the existing merchandise update path too", async () => {const test = setup({- current: { ...product(), unrelated: "keep" } as Rillet.Product+ current: { ...product(), unrelated: "keep" } as Rillet.Product,+ mappings: [mapping("item", "local-item", "shipping-product")]});- (test.syncer as any).getRemoteId = async () => "shipping-product";const changed = { ...product(), description: "Updated description" };await (test.syncer as unknown as {@@ -248,42 +251,28 @@ describe("Rillet shipping product helper", () => {* 2-decimal serialization gives a JPY price cents it cannot have and truncates* a 3-decimal BHD price.*/-function makeItemDb(baseCurrencyCode: string, decimalPlaces: number) {- const chain = (row: unknown) => {- const b: Record<string, unknown> = {};- b.select = () => b;- b.leftJoin = () => b;- b.where = () => b;- b.execute = async () => [row];- b.executeTakeFirst = async () => row;- return b;- };- return {- selectFrom: (table: string) => {- if (table === "company")- return chain({ baseCurrencyCode, companyGroupId: "group-1" });- if (table === "currency") return chain({ decimalPlaces });- if (table === "accountDefault")- return chain({ salesAccount: "acct-sales" });- return chain(undefined);- }- } as never;-}-function makeMerchandiseSyncer(baseCurrencyCode: string,decimalPlaces: number) {- const syncer = new RilletItemSyncer({- database: makeItemDb(baseCurrencyCode, decimalPlaces),+ const db = fakeDatabase({+ company: [{ id: "company-1", baseCurrencyCode, companyGroupId: "group-1" }],+ currency: [+ { code: baseCurrencyCode, companyGroupId: "group-1", decimalPlaces }+ ],+ accountDefault: [{ companyId: "company-1", salesAccount: "acct-sales" }],+ externalIntegrationMapping: accountMappingRows(+ { "acct-sales": "4000" },+ "rillet"+ )+ });+ return new RilletItemSyncer({+ database: db.database,companyId: "company-1",provider: { id: "rillet" } as never,config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },entityType: "item"});- (syncer as any).getAccountCodesById = async () =>- new Map([["acct-sales", "4000"]]);- return syncer;}const merchandiseItem = {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.tsindex 6f0c91ec8a..1b66c16b38 100644--- 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.ts@@ -9,36 +9,8 @@ import { RilletPaymentSyncer } from "../payment";// 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.-// Posting imports the post-payment operation lazily; stub it so these tests-// never reach the database or server env.-// 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(...(Array.isArray(v) ? v : [v]));- return insertBuilder;- };- insertBuilder.onConflict = () => insertBuilder;- insertBuilder.execute = async () => [];- return cb({ insertInto: () => insertBuilder });- }- };-});-+// Rows the push wrote to externalIntegrationMapping inside its transaction.+const txLinkSink: Array<Record<string, unknown>> = [];beforeEach(() => {txLinkSink.length = 0;});@@ -73,7 +45,6 @@ function makePushDb(opts: {mappings?: Array<Record<string, unknown>>;payment?: PaymentRow;settlements?: SettlementRow[];- linkSink: Array<Record<string, unknown>>;/** `currency.decimalPlaces` of the payment currency (USD unless overridden). */currencyDecimals?: number;}) {@@ -108,17 +79,24 @@ function makePushDb(opts: {transaction: () => ({execute: async (cb: (tx: unknown) => Promise<unknown>) => {const insertBuilder: Record<string, unknown> = {};- insertBuilder.values = (v: Record<string, unknown>) => {- opts.linkSink.push(v);+ insertBuilder.values = (+ v: Record<string, unknown> | Array<Record<string, unknown>>+ ) => {+ txLinkSink.push(...(Array.isArray(v) ? v : [v]));return insertBuilder;};insertBuilder.onConflict = () => insertBuilder;insertBuilder.execute = async () => [];- const tx = {- executeQuery: async () => ({ rows: [] }),- insertInto: () => insertBuilder+ // withTriggersDisabled's raw `SET LOCAL` runs through this executor.+ const executor = {+ transformQuery: (node: unknown) => node,+ compileQuery: () => ({ sql: "", parameters: [] }),+ executeQuery: async () => ({ rows: [] })};- return cb(tx);+ return cb({+ getExecutor: () => executor,+ insertInto: () => insertBuilder+ });}})} as never;@@ -228,12 +206,10 @@ const apSettlement: SettlementRow = {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+ settlements: [apSettlement]}),mapping: null, // Carbon-born: no existing payment mappingdocumentRemoteId: "bill-remote-1"@@ -277,8 +253,7 @@ describe("RilletPaymentSyncer push — happy path", () => {targetPurchaseInvoiceId: null,targetSalesInvoiceId: "sinv-1"}- ],- linkSink: []+ ]}),mapping: null,documentRemoteId: "inv-remote-1"@@ -299,8 +274,7 @@ describe("RilletPaymentSyncer push — origin routing (loop guard)", () => {const { syncer, createBillPayment } = makeSyncer({db: makePushDb({payment: apPayment,- settlements: [apSettlement],- linkSink: []+ settlements: [apSettlement]}),mapping: { metadata: null } as never // a pulled payment carries a mapping});@@ -328,8 +302,7 @@ describe("RilletPaymentSyncer push — gates (parked as Skipped)", () => {settings: { postingSync: { families: { ap: "journals" } } }},payment: apPayment,- settlements: [apSettlement],- linkSink: []+ settlements: [apSettlement]}),mapping: null});@@ -357,8 +330,7 @@ describe("RilletPaymentSyncer push — gates (parked as Skipped)", () => {sourceAmount: 40},apSettlement- ],- linkSink: []+ ]}),mapping: null,documentRemoteId: "bill-remote-1",@@ -402,7 +374,6 @@ describe("RilletPaymentSyncer push — gates (parked as Skipped)", () => {settlements: [{ ...apSettlement, appliedAmount: 1000, sourceAmount: 1000 }],- linkSink: [],currencyDecimals: 0}),mapping: null,@@ -425,7 +396,6 @@ describe("RilletPaymentSyncer push — gates (parked as Skipped)", () => {settlements: [{ ...apSettlement, appliedAmount: 0.563, sourceAmount: 0.563 }],- linkSink: [],currencyDecimals: 3}),mapping: null,@@ -444,8 +414,7 @@ describe("RilletPaymentSyncer push — gates (parked as Skipped)", () => {const { syncer } = makeSyncer({db: makePushDb({payment: { ...apPayment, exchangeRate: 2 },- settlements: [apSettlement],- linkSink: []+ settlements: [apSettlement]}),mapping: null});@@ -459,8 +428,7 @@ describe("RilletPaymentSyncer push — gates (parked as Skipped)", () => {const { syncer } = makeSyncer({db: makePushDb({payment: apPayment,- settlements: [{ ...apSettlement, discountAmount: 5 }],- linkSink: []+ settlements: [{ ...apSettlement, discountAmount: 5 }]}),mapping: null});@@ -474,8 +442,7 @@ describe("RilletPaymentSyncer push — gates (parked as Skipped)", () => {const { syncer } = makeSyncer({db: makePushDb({payment: apPayment,- settlements: [apSettlement],- linkSink: []+ settlements: [apSettlement]}),mapping: null,enabled: false@@ -502,8 +469,7 @@ describe("RilletPaymentSyncer push — void routing", () => {db: makePushDb({payment: { ...apPayment, status: "Voided" },settlements: [apSettlement],- mappings,- linkSink: []+ mappings})});expect(await syncer.pushToAccounting("pay_1")).toMatchObject({@@ -537,7 +503,6 @@ describe("RilletPaymentSyncer push — void routing", () => {db: makePushDb({payment: { ...apPayment, status: "Voided" },settlements: [apSettlement],- linkSink: [],mappings: [1, 2].map((n) => ({entityId: `pay_1:doc-${n}`,externalId: `bill:doc-${n}:pay-${n}`,@@ -557,7 +522,6 @@ describe("RilletPaymentSyncer push — void routing", () => {db: makePushDb({payment: { ...apPayment, status: "Voided" },settlements: [],- linkSink: [],mappings: [{entityId: "pay_1",@@ -578,8 +542,7 @@ describe("RilletPaymentSyncer push — void routing", () => {const { syncer } = makeSyncer({db: makePushDb({payment: { ...apPayment, status: "Voided" },- settlements: [apSettlement],- linkSink: []+ settlements: [apSettlement]}),mapping: { metadata: null } // pulled: no origin stamp});@@ -596,7 +559,7 @@ describe("RilletPaymentSyncer.pushRemotePayment — mapping Warnings", () => {accountCodes?: Map<string, string>;}) {const { syncer } = makeSyncer({- db: makePushDb({ linkSink: [] }),+ db: makePushDb({}),documentRemoteId: opts.documentRemoteId,accountCodes: opts.accountCodes});@@ -652,8 +615,7 @@ describe("outbound cash funding validation", () => {const { syncer, createBillPayment } = makeSyncer({db: makePushDb({payment: apPayment,- settlements: [{ ...apSettlement, sourcePaymentId: "prior-credit" }],- linkSink: []+ settlements: [{ ...apSettlement, sourcePaymentId: "prior-credit" }]}),mapping: null,documentRemoteId: "bill-remote-1"@@ -692,8 +654,7 @@ describe("RilletPaymentSyncer push — reimbursement payout", () => {makeSyncer({db: makePushDb({payment: apPayment,- settlements: [reimbursementSettlement],- linkSink: []+ settlements: [reimbursementSettlement]}),mapping: null,documentRemoteId: "reimbursement-remote-1"@@ -729,8 +690,7 @@ describe("RilletPaymentSyncer push — reimbursement payout", () => {const { syncer, createReimbursementPayment } = makeSyncer({db: makePushDb({payment: apPayment,- settlements: [reimbursementSettlement],- linkSink: []+ settlements: [reimbursementSettlement]}),mapping: null,documentRemoteId: null@@ -759,8 +719,7 @@ describe("RilletPaymentSyncer push — reimbursement payout", () => {makeSyncer({db: makePushDb({payment: apPayment,- settlements: [apSettlement], // a BILL settlement, not a reimbursement- linkSink: []+ settlements: [apSettlement] // a BILL settlement, not a reimbursement}),mapping: null,targetMapping: {@@ -790,8 +749,7 @@ describe("RilletPaymentSyncer push — reimbursement payout", () => {makeSyncer({db: makePushDb({payment: apPayment,- settlements: [apSettlement],- linkSink: []+ settlements: [apSettlement]}),mapping: null,targetMapping: {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.tsindex 182b4b2241..6d5984a185 100644--- a/packages/ee/src/accounting/providers/rillet/entities/__tests__/payment.test.ts+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/payment.test.ts@@ -2,7 +2,7 @@// Carbon Enterprise file, licensed only under the Carbon Commercial License// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.-import { beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it } from "vitest";import {type NormalizedPayment,upsertLocalPaymentDraft@@ -18,16 +18,6 @@ import {RilletPaymentSyncer} from "../payment";-const { invokeMock } = vi.hoisted(() => ({ invokeMock: vi.fn() }));-// A posting with a client runs as the caller behind it, else as the system.-vi.mock("@carbon/api/postings.server", () => ({- posting: (_name: string, handles: { client?: unknown }, input: unknown) =>- invokeMock(- { ...handles, actor: handles.client ? "caller" : "system" },- input- )-}));-describe("composite payment sync entity id", () => {it("round-trips invoice + payment ids as a prefix-less AR id", () => {const entityId = getRilletPaymentSyncEntityId(@@ -212,102 +202,10 @@ describe("amount/currency normalization helpers", () => {});});-// 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) {+// A fake Kysely database answering the documents-mode gate's+// `companyIntegration.metadata` read and the FX gate's `company.baseCurrencyCode`+// read. `metadata` undefined = no integration row (defaults to documents mode).+function makeGateDb(metadata: unknown, baseCurrencyCode: string) {const chain = (result: unknown) => {const c: any = {select: () => c,@@ -324,73 +222,119 @@ function makeFxDb(metadata: unknown, baseCurrencyCode: string) {} 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>;- };- }+function familyModeMetadata(family: "ar" | "ap", mode: string) {+ return { settings: { postingSync: { families: { [family]: mode } } } };+}- 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");+function makeGateSyncer({+ mappedDocumentId = "carbon-document-1" as string | null,+ metadata = undefined as unknown,+ baseCurrency = "USD"+} = {}) {+ const syncer = new RilletPaymentSyncer({+ database: makeGateDb(metadata, baseCurrency),+ companyId: "company-1",+ provider: { id: "rillet" } as never,+ config: {+ enabled: true,+ direction: "pull-from-accounting",+ owner: "accounting"+ },+ entityType: "payment"});+ // The pushed document's mapping is the ownership record.+ (syncer as unknown as Record<string, unknown>).mappingService = {+ getEntityId: async () => mappedDocumentId+ };+ return syncer as unknown as {+ shouldSync(context: {+ direction: "push" | "pull";+ remoteEntity?: Rillet.InvoicePayment | Rillet.BillPayment;+ isFirstSync: boolean;+ entityId: string;+ }): Promise<boolean | string>;+ };+}- 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+describe.each([+ {+ family: "ar" as const,+ entityId: "inv-ours:pay-1",+ remote: { id: "pay-1", status: "SUCCESSFUL" } as Rillet.InvoicePayment+ },+ {+ family: "ap" as const,+ entityId: "bill:bill-ours:bp-1",+ remote: {+ id: "bp-1",+ status: "SUCCESSFUL",+ bill_id: "bill-ours"+ } as Rillet.BillPayment+ }+])(+ "RilletPaymentSyncer.shouldSync ($family)",+ ({ family, entityId, remote }) => {+ const pull = (+ options: Parameters<typeof makeGateSyncer>[0],+ remoteEntity: Rillet.InvoicePayment | Rillet.BillPayment = remote+ ) =>+ makeGateSyncer(options).shouldSync({+ direction: "pull",+ entityId,+ remoteEntity,+ isFirstSync: true+ });++ it("proceeds for a payment on a locally mapped document", async () => {+ expect(await pull({})).toBe(true);+ });++ it.each(["journals", "none"])(+ "skips when the family is in %s mode",+ async (mode) => {+ expect(+ await pull({ metadata: familyModeMetadata(family, mode) })+ ).toEqual(expect.any(String));+ }+ );++ // Rillet feeds are org-wide: another Carbon instance's subsidiary shares them.+ it("skips a payment on a document with no local mapping", async () => {+ expect(await pull({ mappedDocumentId: null })).toEqual(+ expect.any(String)+ );});- 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+ it("skips a first-seen FAILED payment, which was never recorded", async () => {+ expect(await pull({}, { ...remote, status: "FAILED" })).toEqual(+ expect.any(String)+ );});- expect(result).toBe(true);- });+ }+);++// mapToNormalized books at rate 1, so a cross-currency payment would misstate.+describe("RilletPaymentSyncer.shouldSync FX gate", () => {+ it.each([+ ["EUR", false],+ ["USD", true],+ [undefined, true]+ ] as const)(+ "a %s payment on a USD company proceeds: %s",+ async (currency, proceeds) => {+ const result = await makeGateSyncer().shouldSync({+ direction: "pull",+ entityId: "inv-ours:pay-1",+ remoteEntity: {+ id: "pay-1",+ status: "SUCCESSFUL",+ ...(currency ? { amount: { amount: "125.00", currency } } : {})+ },+ isFirstSync: true+ });+ expect(result).toEqual(proceeds ? true : expect.any(String));+ }+ );});function makeMapperSyncer() {@@ -885,183 +829,3 @@ describe("upsertLocalPaymentDraft (AP bill payment)", () => {).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(- expect.objectContaining({- companyId: "company-1",- userId: "user-1",- actor: "system"- }),- { type: "post", paymentId: "payment-row-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(- expect.objectContaining({- companyId: "company-1",- userId: "user-1",- actor: "system"- }),- { type: "void", paymentId: "payment-row-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: null,- error: { message: "Accounting period is locked" }- });- 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/__tests__/reimbursement.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/reimbursement.test.tsindex 3d153c9164..582d9e93ca 100644--- a/packages/ee/src/accounting/providers/rillet/entities/__tests__/reimbursement.test.ts+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/reimbursement.test.ts@@ -3,6 +3,10 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ accountMappingRows,+ fakeDatabase+} from "../../../../core/fake-database-test-fixture";import { JournalEntrySyncError } from "../../../../core/posting";import type { ReimbursementSource } from "../../../../core/reimbursement-source";import type {@@ -15,42 +19,6 @@ import {RilletReimbursementSyncer} from "../reimbursement";-// Only the DB loaders in ./shared are stubbed; the base syncer's push-// workflow under test stays the production one.-vi.mock("../shared", async (importOriginal) => {- const original = await importOriginal<typeof import("../shared")>();- return {- ...original,- loadRilletAccountCodesById: vi.fn(- async () =>- new Map([- ["acct_travel", "6100"],- ["acct_meals", "6200"],- ["acct_employee_payable", "2180"]- ])- )- };-});--const { linked } = vi.hoisted(() => ({ linked: [] as unknown[] }));-vi.mock("../../../../core/utils", async (importOriginal) => ({- ...(await importOriginal<typeof import("../../../../core/utils")>()),- withTriggersDisabled: async (- _db: unknown,- cb: (tx: unknown) => Promise<unknown>- ) => {- const b = {- values: (row: unknown) => {- linked.push(row);- return b;- },- onConflict: () => b,- execute: async () => []- };- return cb({ insertInto: () => b });- }-}));-const reimbursement = (overrides: Partial<ReimbursementSource> = {}): ReimbursementSource => ({@@ -213,22 +181,36 @@ describe("mapReimbursementToRilletReimbursement", () => {});});-/** In-memory ExternalIntegrationMappingService stand-in. */-function fakeMappingService(mapping: unknown = null) {- return {- getByEntity: vi.fn(async () => mapping),- getExternalId: vi.fn(async () => null),- link: vi.fn(async () => undefined)- };-}-function setupSyncer(args: {local: ReimbursementSource;- mapping?: unknown;+ /** The reimbursement's existing mapping row, when it was pushed before. */+ mapping?: Record<string, unknown>;/** What Rillet's vendor list already holds (the strand-recovery source). */vendors?: Array<Partial<Rillet.Vendor>>;}) {- linked.length = 0;+ const db = fakeDatabase({+ externalIntegrationMapping: [+ ...accountMappingRows(+ {+ acct_travel: "6100",+ acct_meals: "6200",+ acct_employee_payable: "2180"+ },+ "rillet"+ ),+ ...(args.mapping+ ? [+ {+ entityType: "reimbursement",+ entityId: "reimb_1",+ integration: "rillet",+ companyId: "company-1",+ ...args.mapping+ }+ ]+ : [])+ ]+ });const createReimbursement = vi.fn(async (_payload: RilletReimbursementCreate) => ({id: "rillet-reimbursement-1"@@ -243,7 +225,7 @@ function setupSyncer(args: {const listVendors = vi.fn(async () => args.vendors ?? []);const syncer = new RilletReimbursementSyncer({- database: {} as never,+ database: db.database,companyId: "company-1",entityType: "reimbursement",config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },@@ -258,7 +240,6 @@ function setupSyncer(args: {});vi.spyOn(syncer, "fetchLocal").mockResolvedValue(args.local);- (syncer as any).mappingService = fakeMappingService(args.mapping ?? null);(syncer as any).resolveLineDimensions = vi.fn(async () => ({fieldIdByDimensionId: new Map(),fieldValueIdsByValue: new Map()@@ -269,7 +250,8 @@ function setupSyncer(args: {createReimbursement,deleteReimbursement,createVendor,- listVendors+ listVendors,+ links: () => db.rows("externalIntegrationMapping")};}@@ -295,7 +277,7 @@ describe("RilletReimbursementSyncer", () => {});it("creates the provider-side employee vendor when the employee is not linked yet", async () => {- const { syncer, createVendor, createReimbursement } = setupSyncer({+ const { syncer, createVendor, createReimbursement, links } = setupSyncer({local: reimbursement({ employeeVendorExternalId: null })});@@ -313,14 +295,14 @@ describe("RilletReimbursementSyncer", () => {);// Linked under employeeVendor, NOT vendor: that id space holds Carbon// supplier ids.- expect(linked).toContainEqual(+ expect(links()).toContainEqual(expect.objectContaining({entityType: "employeeVendor",entityId: "emp_1",externalId: "rillet-new-vendor-1"}));- expect(linked).not.toContainEqual(+ expect(links()).not.toContainEqual(expect.objectContaining({ entityType: "vendor" }));});@@ -384,7 +366,7 @@ describe("RilletReimbursementSyncer — stranded employee vendor", () => {});it("adopts the stranded vendor instead of creating a duplicate", async () => {- const { syncer, createVendor, createReimbursement } = setupSyncer({+ const { syncer, createVendor, createReimbursement, links } = setupSyncer({local: reimbursement({ employeeVendorExternalId: null }),vendors: [strandedVendor()]});@@ -398,7 +380,7 @@ describe("RilletReimbursementSyncer — stranded employee vendor", () => {"rillet-stranded-vendor-1");// And the missing mapping is written, so the next push short-circuits.- expect(linked).toContainEqual(+ expect(links()).toContainEqual(expect.objectContaining({entityType: "employeeVendor",entityId: "emp_1",diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/vendor-counterpart.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/vendor-counterpart.test.tsindex 09f3c78b4e..108b256ffd 100644--- a/packages/ee/src/accounting/providers/rillet/entities/__tests__/vendor-counterpart.test.ts+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/vendor-counterpart.test.ts@@ -3,6 +3,7 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.import { describe, expect, it, vi } from "vitest";+import { fakeDatabase } from "../../../../core/fake-database-test-fixture";import type { RilletVendorWrite } from "../../models";import { RilletVendorSyncer } from "../vendor";@@ -17,38 +18,6 @@ import { RilletVendorSyncer } from "../vendor";* refuses a claimed record, and an adoption links before it mutates.*/-/**- * The mapping write runs inside `withTriggersDisabled`, a real Kysely transaction- * that opens with a `SET LOCAL` statement. Stub it so the write is observable in- * `writeOrder` — and so it can REFUSE, which is what the partial unique index- * does when the remote vendor already belongs to another supplier.- */-const { writeOrder, linkBehaviour } = vi.hoisted(() => ({- writeOrder: [] as string[],- linkBehaviour: { throws: false }-}));-vi.mock("../../../../core/utils", async (importOriginal) => ({- ...(await importOriginal<typeof import("../../../../core/utils")>()),- withTriggersDisabled: async (- _db: unknown,- cb: (tx: unknown) => Promise<unknown>- ) => {- const builder: Record<string, any> = {};- builder.values = () => builder;- builder.onConflict = () => builder;- builder.execute = async () => {- writeOrder.push("link");- if (linkBehaviour.throws) {- throw new Error(- 'duplicate key value violates unique constraint "externalIntegrationMapping_external_unique"'- );- }- return [];- };- return cb({ insertInto: () => builder });- }-}));-const COMPANY_ID = "company-1";const payload = (@@ -62,22 +31,42 @@ const payload = (...overrides}) as RilletVendorWrite;+const mapping = (entityId: string, externalId: string) => ({+ entityType: "vendor",+ entityId,+ integration: "rillet",+ externalId,+ companyId: COMPANY_ID+});+function setup(opts: {/** The Carbon supplier the matched remote vendor is already mapped to. */- claimedBy?: string | null;+ claimedBy?: string;/** Make the mapping write refuse, as the partial unique index would. */linkThrows?: boolean;}) {- const order = writeOrder;- order.length = 0;- linkBehaviour.throws = opts.linkThrows === true;-- const createVendor = vi.fn(async () => {- order.push("createVendor");- return { id: "V-NEW" };+ // No mapping row for THIS supplier — the ladder is what resolves it.+ const db = fakeDatabase({+ externalIntegrationMapping: opts.claimedBy+ ? [mapping(opts.claimedBy, "V1")]+ : []});+ if (opts.linkThrows)+ db.failNextWrite(+ "externalIntegrationMapping",+ new Error(+ 'duplicate key value violates unique constraint "externalIntegrationMapping_external_unique"'+ )+ );++ const createVendor = vi.fn(async () => ({ id: "V-NEW" }));+ /** The mapping rows as they stood when the remote vendor was rewritten. */+ let mappingsAtUpdate: unknown[] = [];const updateVendor = vi.fn(async () => {- order.push("updateVendor");+ mappingsAtUpdate = db.rows("externalIntegrationMapping").map((row) => ({+ entityId: row.entityId,+ externalId: row.externalId+ }));return { id: "V1" };});const findRemoteCandidates = vi.fn(async () => [@@ -85,7 +74,7 @@ function setup(opts: {]);const syncer = new RilletVendorSyncer({- database: {} as never,+ database: db.database,companyId: COMPANY_ID,entityType: "vendor",config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },@@ -98,20 +87,12 @@ function setup(opts: {} as never});- (syncer as any).mappingService = {- // No mapping row for THIS supplier — the ladder is what resolves it.- getExternalId: async () => null,- // ...but the matched remote vendor may already belong to another one.- getEntityId: async (_integration: string, remoteId: string) =>- remoteId === "V1" ? (opts.claimedBy ?? null) : null- };-return {push: (localId = "sup_2") =>(syncer as any).upsertRemote(payload(), localId) as Promise<string>,createVendor,updateVendor,- order+ mappingsAtUpdate: () => mappingsAtUpdate};}@@ -127,16 +108,18 @@ describe("RilletVendorSyncer.upsertRemote — the counterpart ladder", () => {});it("writes the mapping BEFORE it mutates an adopted vendor", async () => {- const test = setup({ claimedBy: null });+ const test = setup({});expect(await test.push("sup_2")).toBe("V1");// Order, not presence: the unique index is the only check that can catch a// mis-resolution, so it has to run while the remote record is intact.- expect(test.order).toEqual(["link", "updateVendor"]);+ expect(test.mappingsAtUpdate()).toEqual([+ { entityId: "sup_2", externalId: "V1" }+ ]);});it("leaves the remote vendor untouched when the mapping write refuses", async () => {- const test = setup({ claimedBy: null, linkThrows: true });+ const test = setup({ linkThrows: true });await expect(test.push("sup_2")).rejects.toThrow(/unique constraint/);expect(test.updateVendor).not.toHaveBeenCalled();diff --git a/packages/ee/src/accounting/providers/xero/entities/__tests__/charge.test.ts b/packages/ee/src/accounting/providers/xero/entities/__tests__/charge.test.tsindex 907552783b..09a8d46df8 100644--- a/packages/ee/src/accounting/providers/xero/entities/__tests__/charge.test.ts+++ b/packages/ee/src/accounting/providers/xero/entities/__tests__/charge.test.ts@@ -180,35 +180,6 @@ describe("mapChargeToXeroBankTransaction", () => {expect(payload.LineItems[0]?.Tracking).toBeUndefined();});- it("uses the merchant name on the line over the line label", () => {- const payload = mapChargeToXeroBankTransaction({- charge: charge({ merchantName: "Acme Fuel" }),- costing: costing(),- ...base- });- expect(payload.LineItems[0]?.Description).toBe("Acme Fuel");- });-- it("falls back to the line label when there is no merchant name", () => {- const payload = mapChargeToXeroBankTransaction({- charge: charge({ merchantName: null }),- costing: costing(),- ...base- });- expect(payload.LineItems[0]?.Description).toBe("Airfare");- });-- it("falls back to the card memo when there is no merchant name or line description", () => {- const payload = mapChargeToXeroBankTransaction({- charge: charge({ merchantName: null }),- costing: costing({ lines: [{ ...lines[0]!, description: null }] }),- ...base- });- expect(payload.LineItems[0]?.Description).toBe(- "SFO→ORD for the Apollo kickoff"- );- });-it("converts a foreign charge to its transaction currency and pins CurrencyRate", () => {// A CAD charge: base USD lines × 1.25 CAD per USD.const payload = mapChargeToXeroBankTransaction({diff --git a/packages/ee/src/accounting/providers/xero/entities/__tests__/reimbursement-employee-contact.test.ts b/packages/ee/src/accounting/providers/xero/entities/__tests__/reimbursement-employee-contact.test.tsindex 5bf1256b1d..ffb242721e 100644--- a/packages/ee/src/accounting/providers/xero/entities/__tests__/reimbursement-employee-contact.test.ts+++ b/packages/ee/src/accounting/providers/xero/entities/__tests__/reimbursement-employee-contact.test.ts@@ -4,6 +4,10 @@import { createHash } from "node:crypto";import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ type FakeDatabase,+ fakeDatabase+} from "../../../../core/fake-database-test-fixture";import type { ReimbursementSource } from "../../../../core/reimbursement-source";import { XeroReimbursementSyncer } from "../reimbursement";@@ -13,33 +17,15 @@ import { XeroReimbursementSyncer } from "../reimbursement";// names, so the retry's POST fails with a duplicate-name validation error.// Without a lookup-before-create that reimbursement can never sync again.-const { mappings } = vi.hoisted(() => ({- mappings: new Map<string, string>()-}));--vi.mock("../../../../core/external-mapping", () => ({- createMappingService: () => ({- getByEntity: async () => null,- getExternalId: async (_type: string, id: string) =>- mappings.get(id) ?? null,- link: async (- _type: string,- id: string,- _provider: string,- externalId: string- ) => {- mappings.set(id, externalId);- }- })-}));--vi.mock("../../../../core/utils", async (importOriginal) => ({- ...(await importOriginal<typeof import("../../../../core/utils")>()),- withTriggersDisabled: async (- _db: unknown,- operation: (tx: unknown) => Promise<unknown>- ) => operation({})-}));+let db: FakeDatabase;+beforeEach(() => {+ db = fakeDatabase();+});+/** The Xero contact the employee is mapped to, if any. */+const employeeContactMapping = (employeeId: string) =>+ db+ .rows("externalIntegrationMapping")+ .find((row) => row.entityId === employeeId)?.externalId;const reimbursement: ReimbursementSource = {id: "reimb_1",@@ -84,7 +70,7 @@ const CONTACT_NAME = "Dana Okafor ([email protected])";function syncer(request: ReturnType<typeof vi.fn>) {const instance = new XeroReimbursementSyncer({- database: {} as never,+ database: db.database,companyId: "company-1",entityType: "reimbursement",config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },@@ -95,8 +81,6 @@ function syncer(request: ReturnType<typeof vi.fn>) {};}-beforeEach(() => mappings.clear());-describe("Xero employee-contact JIT create", () => {it("adopts the existing Contact found by exact name instead of POSTing a duplicate", async () => {const request = vi.fn(async (method: string, _url: string) => {@@ -126,7 +110,7 @@ describe("Xero employee-contact JIT create", () => {);// The adoption is what makes the retry recoverable: the mapping the first// attempt failed to write is written now.- expect(mappings.get("emp_1")).toBe("contact-orphan");+ expect(employeeContactMapping("emp_1")).toBe("contact-orphan");});it("creates the Contact with a deterministic Idempotency-Key when Xero has none", async () => {@@ -151,7 +135,7 @@ describe("Xero employee-contact JIT create", () => {}}));- expect(mappings.get("emp_1")).toBe("contact-new");+ expect(employeeContactMapping("emp_1")).toBe("contact-new");});it("refuses to guess when two Contacts share the employee's name", async () => {@@ -167,6 +151,6 @@ describe("Xero employee-contact JIT create", () => {await expect(syncer(request).resolveEmployeeContact(reimbursement)).rejects.toThrow(/Multiple Xero contacts are named/);- expect(mappings.size).toBe(0);+ expect(db.rows("externalIntegrationMapping")).toEqual([]);});});diff --git a/packages/ee/src/accounting/providers/xero/entities/__tests__/reimbursement.test.ts b/packages/ee/src/accounting/providers/xero/entities/__tests__/reimbursement.test.tsindex a4449fc0b8..9fc1171fad 100644--- a/packages/ee/src/accounting/providers/xero/entities/__tests__/reimbursement.test.ts+++ b/packages/ee/src/accounting/providers/xero/entities/__tests__/reimbursement.test.ts@@ -2,7 +2,8 @@// Carbon Enterprise file, licensed only under the Carbon Commercial License// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.-import { beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";+import { fakeDatabase } from "../../../../core/fake-database-test-fixture";import { JournalEntrySyncError } from "../../../../core/posting";import type { ReimbursementSource } from "../../../../core/reimbursement-source";import {@@ -15,33 +16,6 @@ import {// ACCPAY field set (Reference is ACCREC-ONLY — the Carbon readable id has to// ride InvoiceNumber) and the two-decimal monetary boundary.-/**- * The JIT contact's mapping row is written inside `withTriggersDisabled`, a real- * Kysely transaction that opens with a `SET LOCAL` statement. Stub it so the row- * lands in `mappingRows` — the store the re-read under test then reads back.- */-const { mappingRows } = vi.hoisted(() => ({- mappingRows: new Map<string, string>()-}));-vi.mock("../../../../core/utils", async (importOriginal) => ({- ...(await importOriginal<typeof import("../../../../core/utils")>()),- withTriggersDisabled: async (- _db: unknown,- cb: (tx: unknown) => Promise<unknown>- ) => {- const builder: Record<string, any> = {};- builder.values = (value: any) => {- for (const row of Array.isArray(value) ? value : [value]) {- mappingRows.set(`${row.entityType}::${row.entityId}`, row.externalId);- }- return builder;- };- builder.onConflict = () => builder;- builder.execute = async () => [];- return cb({ insertInto: () => builder });- }-}));-const reimbursement = (overrides: Partial<ReimbursementSource> = {}): ReimbursementSource => ({@@ -236,7 +210,21 @@ describe("mapReimbursementToXeroInvoice", () => {* failed Xero's unique-name validation and parked Failed. A Posted* reimbursement's `updatedAt` never changes, so nothing re-enqueued it.*/-function makeEmployeeContactSyncer() {+/** `mappedTo`: the Contact the employee is already mapped to. */+function makeEmployeeContactSyncer(mappedTo?: string) {+ const db = fakeDatabase({+ externalIntegrationMapping: mappedTo+ ? [+ {+ entityType: "employeeVendor",+ entityId: "emp_1",+ integration: "xero",+ companyId: "company-1",+ externalId: mappedTo+ }+ ]+ : []+ });let created = 0;// Resolving now makes TWO kinds of request: a name lookup that recovers a// Contact a crashed run left behind, then a create when it finds none. The@@ -260,33 +248,30 @@ function makeEmployeeContactSyncer() {request.mock.calls.filter(([method]) => method === "GET");const syncer = new XeroReimbursementSyncer({- database: {} as never,+ database: db.database,companyId: "company-1",provider: { id: "xero", request } as never,config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },entityType: "reimbursement"});- (syncer as any).mappingService = {- getExternalId: async (entityType: string, entityId: string) =>- mappingRows.get(`${entityType}::${entityId}`) ?? null- };-return {resolve: (local: ReimbursementSource) =>(syncer as any).resolveEmployeeContact(local) as Promise<string>,request,creates,lookups,- store: mappingRows+ employeeMapping: () =>+ db+ .rows("externalIntegrationMapping")+ .find(+ (row) =>+ row.entityType === "employeeVendor" && row.entityId === "emp_1"+ )?.externalId};}describe("XeroReimbursementSyncer.resolveEmployeeContact", () => {- beforeEach(() => {- mappingRows.clear();- });-it("creates the employee Contact ONCE for two reimbursements in one batch", async () => {const test = makeEmployeeContactSyncer();// Both snapshots come from the SAME fetchLocalBatch, so both say null.@@ -300,12 +285,11 @@ describe("XeroReimbursementSyncer.resolveEmployeeContact", () => {expect(test.creates()).toHaveLength(1);expect(test.lookups()).toHaveLength(1);expect(second).toBe(first);- expect(test.store.get("employeeVendor::emp_1")).toBe(first);+ expect(test.employeeMapping()).toBe(first);});it("reuses an already-mapped Contact without creating one", async () => {- const test = makeEmployeeContactSyncer();- test.store.set("employeeVendor::emp_1", "xero-contact-uuid");+ const test = makeEmployeeContactSyncer("xero-contact-uuid");expect(await test.resolve(reimbursement({ employeeVendorExternalId: null }))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.tsindex 82ced056ef..1824b2e74a 100644--- a/packages/ee/src/accounting/providers/xero/entities/journal-entry.test.ts+++ b/packages/ee/src/accounting/providers/xero/entities/journal-entry.test.ts@@ -4,24 +4,7 @@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 { JournalEntrySyncError } from "../../../core/posting";import type { Accounting } from "../../../core/types";import {buildXeroTrackingTarget,@@ -70,26 +53,6 @@ const ACCOUNT_CODES: ReadonlyMap<string, string> = new Map([["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({@@ -169,399 +132,6 @@ describe("mapJournalEntryToManualJournal", () => {});});-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"];- // Memos resolve their family from the memo's PARTY, which this- // party-less reason helper cannot know — so they report that instead.- const partyResolved = ["Credit Memo", "Debit Memo"];- // Reimbursement IS document-backed (the `reimbursement` entity), but this- // helper only knows the invoice/bill flags, so it reports the backing- // sync as disabled. Either way the journal never pushes here — and the- // real decision, with the full docSync flags, is made by- // getJournalPostingPolicyDecision at enqueue time.- const backedButUnflagged = ["Reimbursement"];-- for (const sourceType of POSTING_SYNC_EXCLUDED_SOURCE_TYPES) {- const expected = backed.includes(sourceType)- ? "excluded from posting sync"- : partyResolved.includes(sourceType)- ? "customer or supplier memo"- : backedButUnflagged.includes(sourceType)- ? "document sync is disabled"- : "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",- // Memo families are opt-in, go-forward — see PostingSyncStoredSchema.- creditMemo: "none",- supplierCredit: "none"- });- 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: "individual" });- 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",- creditMemo: "none",- supplierCredit: "none"- });- });-- 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", () => {diff --git a/packages/ee/src/mcp/server.test.ts b/packages/ee/src/mcp/server.test.tsindex eb67600fcb..d78fedee71 100644--- a/packages/ee/src/mcp/server.test.ts+++ b/packages/ee/src/mcp/server.test.ts@@ -2,12 +2,6 @@// Carbon Enterprise file, licensed only under the Carbon Commercial License// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.-import { describeRequest } from "@carbon/logger/middleware.server";-import {- annotateRequestSpan,- nameRequestSpan,- withSpan-} from "@carbon/logger/tracing.server";import {Client,StreamableHTTPClientTransport@@ -17,16 +11,6 @@ import { requireEntitlement } from "../entitlements.server";import { serveMcpRequest } from "./server";import type { McpCallResult } from "./types";-vi.mock("@carbon/logger/tracing.server", () => ({- annotateRequestSpan: vi.fn(),- nameRequestSpan: vi.fn(),- withSpan: vi.fn((_name: string, _attributes: unknown, run: () => unknown) =>- run()- )-}));-vi.mock("@carbon/logger/middleware.server", () => ({- describeRequest: vi.fn()-}));vi.mock("../entitlements.server", () => ({requireEntitlement: vi.fn(async () => undefined)}));@@ -84,67 +68,6 @@ async function connect(return client;}-describe("MCP tool calls are traced", () => {- beforeEach(() => vi.clearAllMocks());-- it("names a call_tool span after the operation and still runs it", async () => {- const client = await connect();-- const result = await client.callTool({- name: "call_tool",- arguments: { name: "sales_getCustomer", arguments: { customerId: "c" } }- });-- expect(JSON.stringify(result.content)).toContain("cust_1");- expect(callOperation).toHaveBeenCalledWith(- "sales_getCustomer",- expect.objectContaining({ companyId: "co1" }),- expect.objectContaining({ customerId: "c" })- );- const attributes = {- "carbon.mcp.tool": "call_tool",- "carbon.operation": "sales_getCustomer"- };- expect(withSpan).toHaveBeenCalledWith(- "mcp call_tool sales_getCustomer",- attributes,- expect.any(Function)- );- expect(annotateRequestSpan).toHaveBeenCalledWith(attributes);- expect(nameRequestSpan).toHaveBeenCalledWith(- "POST /api/mcp call_tool sales_getCustomer"- );- expect(describeRequest).toHaveBeenCalledWith("call_tool sales_getCustomer");- });-- it("keeps a name the client made up out of the span name", async () => {- const client = await connect();-- await client.callTool({- name: "call_tool",- arguments: { name: "not_a_real_operation", arguments: {} }- });-- expect(withSpan).toHaveBeenCalledWith(- "mcp call_tool",- { "carbon.mcp.tool": "call_tool" },- expect.any(Function)- );- });-- it("traces the other tools by their own name", async () => {- const client = await connect();-- await client.callTool({ name: "search_tools", arguments: { query: "x" } });-- expect(withSpan).toHaveBeenCalledWith(- "mcp search_tools",- { "carbon.mcp.tool": "search_tools" },- expect.any(Function)- );- });-});-describe("call_tool keeps list output small", () => {beforeEach(() => vi.clearAllMocks());diff --git a/packages/ee/src/mount/lib/client.test.ts b/packages/ee/src/mount/lib/client.test.tsindex 810586c1d2..9c8dbf1e5b 100644--- a/packages/ee/src/mount/lib/client.test.ts+++ b/packages/ee/src/mount/lib/client.test.ts@@ -8,20 +8,16 @@ import {type AxiosRequestConfig,type AxiosResponse} from "axios";-import { describe, expect, it, vi } from "vitest";+import { afterAll, describe, expect, it, vi } from "vitest";+import { MountClient } from "./client";-vi.mock("@carbon/auth/client.server", () => ({- getCarbonServiceRole: () => ({})-}));-vi.mock("../../integrations/secrets", () => ({- resolveIntegrationSecrets: vi.fn()-}));-vi.mock("./service", () => ({- getMountIntegration: vi.fn(),- MOUNT_INTEGRATION_ID: "mount"-}));+// Import-safety: @carbon/auth builds a Supabase client at import.+vi.hoisted(() => {+ vi.stubEnv("SUPABASE_URL", "http://supabase.test");+ vi.stubEnv("SUPABASE_ANON_KEY", "anon-key");+});-const { MountClient } = await import("./client");+afterAll(() => vi.unstubAllEnvs());const COMPANY_ID = "company_1";diff --git a/packages/ee/src/onshape/panel/plan.test.ts b/packages/ee/src/onshape/panel/plan.test.tsindex c059bf9d4e..d62f87df8d 100644--- a/packages/ee/src/onshape/panel/plan.test.ts+++ b/packages/ee/src/onshape/panel/plan.test.ts@@ -330,23 +330,30 @@ describe("buildPartPlan", () => {},{ id: "item-2", readableId: "STD-006", revision: "0", name: "Stud" }];-- it("classifies create / adopt / update / unchanged / skip in request order", () => {- const rows = buildPartPlan({+ /** PAD-005 linked to item-1 at microversion m1 (the part is now at m2). */+ const linked = (microversionId = "m1") => [+ {+ entityId: "item-1",+ externalId: "d:e:p1",+ lastSyncedAt: null,+ metadata: { microversionId }+ }+ ];+ const planParts = (over: Partial<Parameters<typeof buildPartPlan>[0]>) =>+ buildPartPlan({documentId: "d",elementId: "e",parts,- requestedPartIds: ["p4", "p1", "p2", "p3", "missing"],- mappings: [- {- entityId: "item-1",- externalId: "d:e:p1",- lastSyncedAt: null,- metadata: { microversionId: "m1" }- }- ],+ requestedPartIds: ["p1"],+ mappings: linked(),items,- options+ options,+ ...over+ });++ it("classifies create / adopt / update / unchanged / skip in request order", () => {+ const rows = planParts({+ requestedPartIds: ["p4", "p1", "p2", "p3", "missing"]});expect(rows.map((r) => [r.partId, r.action])).toEqual([["p4", "create"],@@ -371,21 +378,7 @@ describe("buildPartPlan", () => {});it("overwrites the descriptions set to Update on every push", () => {- const rows = buildPartPlan({- documentId: "d",- elementId: "e",- parts,- requestedPartIds: ["p1"],- mappings: [- {- entityId: "item-1",- externalId: "d:e:p1",- lastSyncedAt: null,- metadata: { microversionId: "m1" }- }- ],- items,- options,+ const rows = planParts({mapping: {map: [],definitions: [],@@ -402,42 +395,57 @@ describe("buildPartPlan", () => {});it("reports unchanged when the mapping's microversion matches", () => {- const rows = buildPartPlan({- documentId: "d",- elementId: "e",- parts,- requestedPartIds: ["p1"],- mappings: [- {- entityId: "item-1",- externalId: "d:e:p1",- lastSyncedAt: null,- metadata: { microversionId: "m2" }- }- ],- items,- options+ const rows = planParts({+ mappings: linked("m2")});expect(rows[0]?.action).toBe("unchanged");expect(rows[0]?.changes).toEqual([]);});it("treats a mapping whose item is gone as no link", () => {- const rows = buildPartPlan({- documentId: "d",- elementId: "e",- parts,- requestedPartIds: ["p1"],+ const rows = planParts({mappings: [{ entityId: "deleted", externalId: "d:e:p1", lastSyncedAt: null }- ],- items,- options+ ]});expect(rows[0]?.action).toBe("adopt");});});+type AssemblyInput = Parameters<typeof buildAssemblyPlan>[0];++const top = node({ index: "1", partNumber: "TOP-001", name: "Top" });++/** A workspace push of WB-100 whose BOM is one TOP-001 line, nothing in Carbon. */+const planAssembly = (over: Partial<AssemblyInput> = {}) =>+ buildAssemblyPlan({+ documentId: "d",+ wv: "w",+ wvId: "w1",+ elementId: "e",+ root: {+ partNumber: "WB-100",+ name: "Workbench",+ description: null,+ revision: null+ },+ nodes: [top],+ items: [],+ methodByItemId: new Map(),+ mappedLinesByMethodId: new Map(),+ manualLinesByMethodId: new Map(),+ options,+ ...over+ });++/** WB-100 exists in Carbon with an Active make method. */+const releasedRoot = {+ items: [{ id: "root", readableId: "WB-100", revision: "0", name: "W" }],+ methodByItemId: new Map([+ ["root", { id: "active", status: "Active" as const }]+ ])+};+describe("buildAssemblyPlan", () => {const nodes: OnshapeBomNode[] = [node({@@ -468,26 +476,12 @@ describe("buildAssemblyPlan", () => {{ id: string; version: number | null }>) =>- buildAssemblyPlan({- documentId: "d",- wv: "w",- wvId: "w1",- elementId: "e",- root: {- partNumber: "WB-100",- name: "Workbench",- description: null,- revision: null- },- nodes: [node({ index: "1", partNumber: "TOP-001", name: "Top" })],- items: [{ id: "root", readableId: "WB-100", revision: "0", name: "W" }],- methodByItemId: new Map([["root", { id: "active", status: "Active" }]]),+ planAssembly({+ ...releasedRoot,mappedLinesByMethodId: new Map([["active", [{ readableId: "OLD-1", quantity: 1 }]],["draft", [{ readableId: "DRAFT-1", quantity: 2 }]]]),- manualLinesByMethodId: new Map(),- options,reusableDraftByItemId});@@ -510,25 +504,11 @@ describe("buildAssemblyPlan", () => {});it("does not refuse an Active method the push leaves unchanged", () => {- const built = buildAssemblyPlan({- documentId: "d",- wv: "w",- wvId: "w1",- elementId: "e",- root: {- partNumber: "WB-100",- name: "Workbench",- description: null,- revision: null- },- nodes: [node({ index: "1", partNumber: "TOP-001", name: "Top" })],- items: [{ id: "root", readableId: "WB-100", revision: "0", name: "W" }],- methodByItemId: new Map([["root", { id: "active", status: "Active" }]]),+ const built = planAssembly({+ ...releasedRoot,mappedLinesByMethodId: new Map([["active", [{ readableId: "TOP-001", quantity: 1 }]]- ]),- manualLinesByMethodId: new Map(),- options+ ])});expect(built.methods[0]?.unchanged).toBe(true);expect(withRefusedMethods(built, new Map([["root", "released"]]))).toBe(@@ -545,29 +525,56 @@ describe("buildAssemblyPlan", () => {{ readableId: "DRAFT-1", quantity: 2 }]);});++ describe("unchanged", () => {+ const unchanged = (+ lines: Array<{ readableId: string; quantity: number }>,+ reusableDraftByItemId?: Map<+ string,+ { id: string; version: number | null }+ >+ ) =>+ planAssembly({+ ...releasedRoot,+ nodes: [+ node({ index: "1", partNumber: "TOP-001", name: "Top" }),+ node({+ index: "2",+ partNumber: "LEG-003",+ name: "Leg",+ quantity: 4+ })+ ],+ mappedLinesByMethodId: new Map([["active", lines]]),+ reusableDraftByItemId+ }).methods[0]?.unchanged;+ const matching = [+ { readableId: "TOP-001", quantity: 1 },+ { readableId: "LEG-003", quantity: 4 }+ ];++ it("needs no Draft when the released method already has Onshape's lines", () => {+ expect(unchanged(matching)).toBe(true);+ });++ it.each([+ ["a quantity", [matching[0]!, { readableId: "LEG-003", quantity: 2 }]],+ ["a line", [matching[0]!]],+ ["the order", [matching[1]!, matching[0]!]]+ ])("needs a Draft when %s differs", (_what, lines) => {+ expect(unchanged(lines)).toBeUndefined();+ });++ it("writes into a reused Draft even when the lines match", () => {+ expect(+ unchanged(matching, new Map([["root", { id: "draft", version: 2 }]]))+ ).toBeUndefined();+ });+ });});describe("depth", () => {- const build = (depth: "all" | "top") =>- buildAssemblyPlan({- documentId: "d",- wv: "w",- wvId: "w1",- elementId: "e",- root: {- partNumber: "WB-100",- name: "Workbench",- description: null,- revision: null- },- nodes,- items: [],- methodByItemId: new Map(),- mappedLinesByMethodId: new Map(),- manualLinesByMethodId: new Map(),- options,- depth- });+ const build = (depth: "all" | "top") => planAssembly({ nodes, depth });it("defaults to the whole tree, and says so", () => {const plan = build("all");@@ -616,17 +623,7 @@ describe("buildAssemblyPlan", () => {});it("plans creates, reuses, methods and the line diff", () => {- const plan = buildAssemblyPlan({- documentId: "d",- wv: "w",- wvId: "w1",- elementId: "e",- root: {- partNumber: "WB-100",- name: "Workbench",- description: null,- revision: null- },+ const plan = planAssembly({nodes,items: [{ id: "wb", readableId: "WB-100", revision: "0", name: "Workbench" },@@ -638,8 +635,7 @@ describe("buildAssemblyPlan", () => {]),manualLinesByMethodId: new Map([["m-wb", [{ readableId: "PAD-005", quantity: 99 }]]- ]),- options+ ])});expect(plan.root.action).toBe("reuse");@@ -674,33 +670,16 @@ describe("buildAssemblyPlan", () => {expect(sub?.replaces).toEqual([]);});+ const tool = {+ id: "tool",+ readableId: "TOP-001",+ revision: "0",+ name: "Top",+ type: "Tool"+ };+it("skips a child whose Carbon item can never be a BOM line", () => {- const plan = buildAssemblyPlan({- documentId: "d",- wv: "w",- wvId: "w1",- elementId: "e",- root: {- partNumber: "WB-100",- name: null,- description: null,- revision: null- },- nodes: [node({ index: "1", partNumber: "TOP-001", name: "Top" })],- items: [- {- id: "tool",- readableId: "TOP-001",- revision: "0",- name: "Top",- type: "Tool"- }- ],- methodByItemId: new Map(),- mappedLinesByMethodId: new Map(),- manualLinesByMethodId: new Map(),- options- });+ const plan = planAssembly({ items: [tool] });expect(plan.items).toEqual([]);expect(plan.methods[0]?.writes).toEqual([]);expect(plan.skipped).toEqual([@@ -709,38 +688,8 @@ describe("buildAssemblyPlan", () => {});it("reuses the Part when a Tool shares its number", () => {- const plan = buildAssemblyPlan({- documentId: "d",- wv: "w",- wvId: "w1",- elementId: "e",- root: {- partNumber: "WB-100",- name: null,- description: null,- revision: null- },- nodes: [node({ index: "1", partNumber: "TOP-001", name: "Top" })],- items: [- {- id: "tool",- readableId: "TOP-001",- revision: "0",- name: "Top",- type: "Tool"- },- {- id: "part",- readableId: "TOP-001",- revision: "0",- name: "Top",- type: "Part"- }- ],- methodByItemId: new Map(),- mappedLinesByMethodId: new Map(),- manualLinesByMethodId: new Map(),- options+ const plan = planAssembly({+ items: [tool, { ...tool, id: "part", type: "Part" }]});expect(plan.skipped).toEqual([]);expect(plan.items.map((item) => item.itemId)).toEqual(["part"]);@@ -750,26 +699,13 @@ describe("buildAssemblyPlan", () => {});it("flags released and missing methods on reused parents", () => {- const plan = buildAssemblyPlan({- documentId: "d",- wv: "w",- wvId: "w1",- elementId: "e",- root: {- partNumber: "WB-100",- name: null,- description: null,- revision: null- },+ const plan = planAssembly({nodes,items: [{ id: "wb", readableId: "WB-100", revision: "0", name: "Workbench" },{ id: "asm", readableId: "ASM-008", revision: "0", name: "Foot" }],- methodByItemId: new Map([["wb", { id: "m-wb", status: "Active" }]]),- mappedLinesByMethodId: new Map(),- manualLinesByMethodId: new Map(),- options+ methodByItemId: new Map([["wb", { id: "m-wb", status: "Active" }]])});expect(plan.methods.map((m) => [m.parentPartNumber, m.status])).toEqual([["WB-100", "active"],@@ -795,31 +731,22 @@ describe("buildAssemblyPlan", () => {node({ index: "3", partNumber: "PAD-005", name: "Pad" }),node({ index: "4", partNumber: "TOP-001", name: "Top" })];+ const otherItems = [+ { id: "hdw", readableId: "HDW-010", revision: "0", name: "Bolt" },+ { id: "pad", readableId: "PAD-005", revision: "0", name: "Pad" }+ ];const build = (links: Array<[string, string]>) =>- buildAssemblyPlan({- documentId: "d",- wv: "w",- wvId: "w1",- elementId: "e",- root: {- partNumber: "WB-100",- name: null,- description: null,- revision: null- },+ planAssembly({nodes: conflictNodes,items: [{ id: "wb", readableId: "WB-100", revision: "0", name: "Workbench" },{ id: "leg", readableId: "LEG-003", revision: "0", name: "Leg" },- { id: "hdw", readableId: "HDW-010", revision: "0", name: "Bolt" },- { id: "pad", readableId: "PAD-005", revision: "0", name: "Pad" }+ ...otherItems],- methodByItemId: new Map(),- mappedLinesByMethodId: new Map(),- manualLinesByMethodId: new Map(),- options,linkedItemIdByExternalId: new Map(links)});+ const conflicts = (plan: ReturnType<typeof build>) =>+ Object.fromEntries(plan.items.map((i) => [i.partNumber, i.conflict]));it("marks a reuse found by part number alone, never a linked one or a create", () => {const plan = build([@@ -829,9 +756,7 @@ describe("buildAssemblyPlan", () => {["d2:ps:JKD", "someone-else"]]);expect(plan.root.conflict).toBeUndefined();- expect(- Object.fromEntries(plan.items.map((i) => [i.partNumber, i.conflict]))- ).toEqual({+ expect(conflicts(plan)).toEqual({"LEG-003": undefined,"HDW-010": true,// No itemSource, so nothing to link through.@@ -847,51 +772,23 @@ describe("buildAssemblyPlan", () => {it("keeps a part linked when a release added a higher revision the mapping does not point at", () => {// A release made Rev B the default and left the mappings on the Rev A// items; a link to Rev A is still a link to the part.- const plan = buildAssemblyPlan({- documentId: "d",- wv: "w",- wvId: "w1",- elementId: "e",- root: {- partNumber: "WB-100",- name: null,- description: null,- revision: null- },+ const plan = planAssembly({nodes: conflictNodes,items: [- {- id: "wb-a",- readableId: "WB-100",- revision: "A",- name: "Workbench"- },- {- id: "wb-b",- readableId: "WB-100",- revision: "B",- name: "Workbench"- },+ { id: "wb-a", readableId: "WB-100", revision: "A", name: "W" },+ { id: "wb-b", readableId: "WB-100", revision: "B", name: "W" },{ id: "leg-a", readableId: "LEG-003", revision: "A", name: "Leg" },{ id: "leg-b", readableId: "LEG-003", revision: "B", name: "Leg" },- { id: "hdw", readableId: "HDW-010", revision: "0", name: "Bolt" },- { id: "pad", readableId: "PAD-005", revision: "0", name: "Pad" }+ ...otherItems],- methodByItemId: new Map(),- mappedLinesByMethodId: new Map(),- manualLinesByMethodId: new Map(),- options,linkedItemIdByExternalId: new Map([["d:e:assembly", "wb-a"],["d2:ps:JHD", "leg-a"]])});expect(plan.root.conflict).toBeUndefined();- expect(- Object.fromEntries(plan.items.map((i) => [i.partNumber, i.conflict]))- ).toEqual({+ expect(conflicts(plan)).toEqual({"LEG-003": undefined,- // Linked to no item: a conflict."HDW-010": true,"PAD-005": true,"TOP-001": undefined@@ -900,85 +797,57 @@ describe("buildAssemblyPlan", () => {});});+type ReleaseItem = PanelRelease["items"][number];++const releaseItem = (over: Partial<ReleaseItem>): ReleaseItem => ({+ partNumber: "WB-100",+ revision: "A",+ elementType: 0,+ documentId: "d",+ versionId: "v1",+ elementId: "e-ps",+ partId: null,+ configuration: null,+ obsolete: false,+ state: "missing",+ itemId: null,+ ...over+});+describe("buildReleasePlan", () => {+ // Assembly WB-100 with its drawing, two parts, and a drawing of nothing.const release: PanelRelease = {releaseId: "rel-1",releaseName: "Release WB-100 A",createdAt: "2026-08-26T00:00:00Z",state: "not-pushed",items: [- {- partNumber: "WB-100",- revision: "A",- elementType: 1,- documentId: "d",- versionId: "v1",- elementId: "e-wb",- partId: null,- configuration: null,- obsolete: false,- state: "missing",- itemId: null- },- {- partNumber: "PAD-005",- revision: "A",- elementType: 0,- documentId: "d",- versionId: "v1",- elementId: "e-ps",- partId: null,- configuration: null,- obsolete: false,- state: "missing",- itemId: null- },- {- partNumber: "NEW-999",- revision: "A",- elementType: 0,- documentId: "d",- versionId: "v1",- elementId: "e-ps",- partId: null,- configuration: null,- obsolete: false,- state: "missing",- itemId: null- },- {- partNumber: "WB-100",- revision: "A",- elementType: 2,- documentId: "d",- versionId: "v1",- elementId: "e-drw",- partId: null,- configuration: null,- obsolete: false,- state: "missing",- itemId: null- },- {+ releaseItem({ elementType: 1, elementId: "e-wb" }),+ releaseItem({ partNumber: "PAD-005" }),+ releaseItem({ partNumber: "NEW-999" }),+ releaseItem({ elementType: 2, elementId: "e-drw" }),+ releaseItem({partNumber: "LONE-DRW",- revision: "A",elementType: 2,- documentId: "d",- versionId: "v1",- elementId: "e-drw2",- partId: null,- configuration: null,- obsolete: false,- state: "missing",- itemId: null- }+ elementId: "e-drw2"+ })]};-- it("classifies reuse / revision / create, children and drawings", () => {- const plan = buildReleasePlan({+ const planRelease = (+ over: Partial<Parameters<typeof buildReleasePlan>[0]> = {}+ ) =>+ buildReleasePlan({documentId: "d",release,+ items: [],+ bomLinesByElementId: {},+ methodByItemId: new Map(),+ options,+ ...over+ });++ it("classifies reuse / revision / create, children and drawings", () => {+ const plan = planRelease({items: [{ id: "pad-0", readableId: "PAD-005", revision: "0", name: "Foot pad" },{ id: "wb-a", readableId: "WB-100", revision: "A", name: "Workbench" },@@ -1002,8 +871,7 @@ describe("buildReleasePlan", () => {})]},- methodByItemId: new Map([["wb-a", { id: "m-wb-a", status: "Active" }]]),- options+ methodByItemId: new Map([["wb-a", { id: "m-wb-a", status: "Active" }]])});expect(plan.items.map((i) => [i.partNumber, i.action])).toEqual([@@ -1052,16 +920,12 @@ describe("buildReleasePlan", () => {}]};- const plan = buildReleasePlan({- documentId: "d",+ const plan = planRelease({release: drawingOnly,items: [{ id: "wb-b", readableId: "WB-100", revision: "B", name: "Workbench" },{ id: "wb-c", readableId: "WB-100", revision: "C", name: "Workbench" }],- bomLinesByElementId: {},- methodByItemId: new Map(),- options,drawingModelByElementId: new Map([["e-drw", { partNumber: "WB-100", revision: "C" }],// Carbon has no PAD-005 Rev C: nothing to attach to.@@ -1086,13 +950,7 @@ describe("buildReleasePlan", () => {});it("prefers the model with the drawing's own number in the release", () => {- const plan = buildReleasePlan({- documentId: "d",- release,- items: [],- bomLinesByElementId: {},- methodByItemId: new Map(),- options,+ const plan = planRelease({drawingModelByElementId: new Map([["e-drw", { partNumber: "OTHER-1", revision: "A" }]])@@ -1103,16 +961,12 @@ describe("buildReleasePlan", () => {});it("proposes no change notice when everything is already at its letter", () => {- const plan = buildReleasePlan({- documentId: "d",+ const plan = planRelease({release: { ...release, items: release.items.slice(0, 2) },items: [{ id: "wb-a", readableId: "WB-100", revision: "A", name: "Workbench" },{ id: "pad-a", readableId: "PAD-005", revision: "A", name: "Foot pad" }- ],- bomLinesByElementId: {},- methodByItemId: new Map(),- options+ ]});expect(plan.alreadyPushed).toBe(true);expect(plan.changeNotice).toBeNull();@@ -1120,8 +974,7 @@ describe("buildReleasePlan", () => {});it("is not already pushed when only a BOM child is missing, and proposes no notice for it", () => {- const plan = buildReleasePlan({- documentId: "d",+ const plan = planRelease({release: { ...release, items: release.items.slice(0, 1) },items: [{ id: "wb-a", readableId: "WB-100", revision: "A", name: "Workbench" }@@ -1135,8 +988,7 @@ describe("buildReleasePlan", () => {})]},- methodByItemId: new Map([["wb-a", { id: "m-wb-a", status: "Draft" }]]),- options+ methodByItemId: new Map([["wb-a", { id: "m-wb-a", status: "Draft" }]])});expect(plan.children.map((c) => [c.partNumber, c.action])).toEqual([["HDW-011", "create"]@@ -1147,8 +999,7 @@ describe("buildReleasePlan", () => {});it("copies a new revision from the newest one, even while it waits in its notice", () => {- const plan = buildReleasePlan({- documentId: "d",+ const plan = planRelease({release: {...release,items: [{ ...release.items[1]!, revision: "B" }]@@ -1168,10 +1019,7 @@ describe("buildReleasePlan", () => {active: false,name: "Foot pad"}- ],- bomLinesByElementId: {},- methodByItemId: new Map(),- options+ ]});expect(plan.items[0]).toMatchObject({action: "revision",@@ -1181,8 +1029,7 @@ describe("buildReleasePlan", () => {});it("points a BOM child at the revision the BOM names, and says when Carbon lacks it", () => {- const plan = buildReleasePlan({- documentId: "d",+ const plan = planRelease({release: { ...release, items: release.items.slice(0, 1) },items: [{ id: "wb-0", readableId: "WB-100", revision: "0", name: "Workbench" },@@ -1218,9 +1065,7 @@ describe("buildReleasePlan", () => {revision: "B"})]- },- methodByItemId: new Map(),- options+ }});expect(plan.children.map((child) => [@@ -1237,16 +1082,11 @@ describe("buildReleasePlan", () => {it("carries each released part's partId and configuration to the export", () => {const released = release.items[1]!;- const plan = buildReleasePlan({- documentId: "d",+ const plan = planRelease({release: {...release,items: [{ ...released, partId: "JHD", configuration: "size%3DLarge" }]- },- items: [],- bomLinesByElementId: {},- methodByItemId: new Map(),- options+ }});expect(plan.items[0]).toMatchObject({partNumber: "PAD-005",@@ -1333,26 +1173,17 @@ describe("released parts in workspace pushes", () => {});it("writes no fields to a released root or child in an assembly push", () => {- const plan = buildAssemblyPlan({- documentId: "d",- wv: "w",- wvId: "w1",- elementId: "e",+ const plan = planAssembly({root: {partNumber: "WB-100",name: "Workbench",description: "New text",revision: "B"},- nodes: [node({ index: "1", partNumber: "TOP-001", name: "Top" })],items: [{ id: "wb-b", readableId: "WB-100", revision: "B", name: "Old text" },{ id: "top-c", readableId: "TOP-001", revision: "C", name: "Old" }],- methodByItemId: new Map(),- mappedLinesByMethodId: new Map(),- manualLinesByMethodId: new Map(),- options,mapping: {map: [],definitions: [],@@ -1381,77 +1212,6 @@ describe("released parts in workspace pushes", () => {});});-describe("buildAssemblyPlan unchanged released methods", () => {- const build = (- lines: Array<{ readableId: string; quantity: number }>,- reusableDraftByItemId = new Map<- string,- { id: string; version: number | null }- >()- ) =>- buildAssemblyPlan({- documentId: "d",- wv: "w",- wvId: "w1",- elementId: "e",- root: {- partNumber: "WB-100",- name: "Workbench",- description: null,- revision: null- },- nodes: [- node({ index: "1", partNumber: "TOP-001", name: "Top", quantity: 1 }),- node({ index: "2", partNumber: "LEG-003", name: "Leg", quantity: 4 })- ],- items: [{ id: "root", readableId: "WB-100", revision: "0", name: "W" }],- methodByItemId: new Map([["root", { id: "active", status: "Active" }]]),- mappedLinesByMethodId: new Map([["active", lines]]),- manualLinesByMethodId: new Map(),- options,- reusableDraftByItemId- }).methods[0];-- it("needs no Draft when the released method already has Onshape's lines", () => {- expect(- build([- { readableId: "TOP-001", quantity: 1 },- { readableId: "LEG-003", quantity: 4 }- ])?.unchanged- ).toBe(true);- });-- it("needs a Draft when a quantity, a line or the order differs", () => {- expect(- build([- { readableId: "TOP-001", quantity: 1 },- { readableId: "LEG-003", quantity: 2 }- ])?.unchanged- ).toBeUndefined();- expect(- build([{ readableId: "TOP-001", quantity: 1 }])?.unchanged- ).toBeUndefined();- expect(- build([- { readableId: "LEG-003", quantity: 4 },- { readableId: "TOP-001", quantity: 1 }- ])?.unchanged- ).toBeUndefined();- });-- it("writes into a reused Draft as before", () => {- expect(- build(- [- { readableId: "TOP-001", quantity: 1 },- { readableId: "LEG-003", quantity: 4 }- ],- new Map([["root", { id: "draft", version: 2 }]])- )?.unchanged- ).toBeUndefined();- });-});-describe("buildAssemblyPlan descriptions", () => {const source = (partId: string) => ({documentId: "d2",@@ -1464,22 +1224,18 @@ describe("buildAssemblyPlan descriptions", () => {descriptionModes: { name: "everyPush", description: "everyPush" } as const,heldCustomFields: new Map()};+ const item = (id: string, readableId: string, name: string) => ({+ id,+ readableId,+ revision: "0",+ name+ });const build = (linkedItemIds?: Set<string>,links = new Map<string, string>(),mapping: typeof everyPush | null = everyPush) =>- buildAssemblyPlan({- documentId: "d",- wv: "w",- wvId: "w1",- elementId: "e",- root: {- partNumber: "WB-100",- name: "Workbench",- description: null,- revision: null- },+ planAssembly({nodes: [node({index: "1",@@ -1501,35 +1257,11 @@ describe("buildAssemblyPlan descriptions", () => {})],items: [- {- id: "wb",- readableId: "WB-100",- revision: "0",- name: "Workbench (Carbon)"- },- {- id: "leg",- readableId: "LEG-003",- revision: "0",- name: "Leg (Carbon)"- },- {- id: "plt",- readableId: "PLT-004",- revision: "0",- name: "Plate (Carbon)"- },- {- id: "hdw",- readableId: "HDW-010",- revision: "0",- name: "Nut (Carbon)"- }+ item("wb", "WB-100", "Workbench (Carbon)"),+ item("leg", "LEG-003", "Leg (Carbon)"),+ item("plt", "PLT-004", "Plate (Carbon)"),+ item("hdw", "HDW-010", "Nut (Carbon)")],- methodByItemId: new Map(),- mappedLinesByMethodId: new Map(),- manualLinesByMethodId: new Map(),- options,linkedItemIdByExternalId: links,linkedItemIds,mapping: mapping ?? undefined@@ -1769,20 +1501,8 @@ describe("changeNoticeDescriptionJson", () => {});describe("buildAssemblyPlan Show Assembly only", () => {- const unitPlan = (- mapping?: Parameters<typeof buildAssemblyPlan>[0]["mapping"]- ) =>- buildAssemblyPlan({- documentId: "d",- wv: "w",- wvId: "w1",- elementId: "e",- root: {- partNumber: "WB-100",- name: "Workbench",- description: null,- revision: null- },+ const unitPlan = (mapping?: AssemblyInput["mapping"]) =>+ planAssembly({nodes: [node({index: "1",@@ -1799,11 +1519,6 @@ describe("buildAssemblyPlan Show Assembly only", () => {]})],- items: [],- methodByItemId: new Map(),- mappedLinesByMethodId: new Map(),- manualLinesByMethodId: new Map(),- options,mapping});diff --git a/packages/ee/src/onshape/panel/review.test.ts b/packages/ee/src/onshape/panel/review.test.tsindex c91655f642..306e80b998 100644--- a/packages/ee/src/onshape/panel/review.test.ts+++ b/packages/ee/src/onshape/panel/review.test.ts@@ -20,17 +20,12 @@ import {applyRequestBody,clearFieldErrors,createReview,- customFieldChangeText,defaultSelectedPartIds,describeMethod,editedItem,indexFieldErrors,- itemFieldChangeText,- keptDifferenceText,- mappedValueText,normalizeWarnings,patchPartStatuses,- releaseResultText,replenishmentMismatches} from "./review";import type { PanelPartStatus } from "./status";@@ -831,135 +826,3 @@ describe("replenishmentMismatches", () => {expect(replenishmentMismatches(plan, {}, new Set(["ASM-009"]))).toEqual([]);});});--describe("mapped value review text", () => {- it("names the value and the Onshape property it came from", () => {- expect(- mappedValueText({- field: "replenishmentSystem",- label: "Replenishment",- value: "Buy",- mode: "create",- onshapeName: "Make or buy"- })- ).toBe('Replenishment: Buy · from Onshape "Make or buy"');- });-- it("says Carbon keeps its value for a Set at creation mapping", () => {- expect(- keptDifferenceText({- label: "Replenishment",- onshape: "Buy",- carbon: "Make"- })- ).toBe(- "Replenishment: Onshape has Buy. Carbon keeps Make (set at creation only)."- );- });-- it("says an every-push mapping replaces Carbon's value", () => {- expect(- itemFieldChangeText({- field: "replenishmentSystem",- label: "Replenishment",- from: "Make",- to: "Buy",- onshapeName: "Make or buy"- })- ).toBe("Replenishment: Replaces Make with Buy (updated on every push).");- expect(- itemFieldChangeText({- field: "defaultMethodType",- label: "Default Method Type",- from: "Make to Order",- to: "Purchase to Order",- onshapeName: null- })- ).toBe(- "Default Method Type: Replaces Make to Order with Purchase to Order (goes with the change above)."- );- });-- it("says what an every-push custom field write replaces or clears", () => {- const vendor = (- value: string | null,- replaces: string | null- ): PlanCustomField => ({- fieldId: "cf_vendor",- name: "Vendor",- mode: "everyPush",- dataTypeId: 5,- listOptions: null,- value,- onshapeName: "Vendor",- replaces- });- expect(customFieldChangeText(vendor("Acme Ltd", "Acme Co"))).toBe(- "Vendor: Replaces Acme Co with Acme Ltd (updated on every push)."- );- expect(customFieldChangeText(vendor("Acme Ltd", null))).toBe(- "Vendor: Sets Acme Ltd (updated on every push)."- );- expect(customFieldChangeText(vendor(null, "Acme Co"))).toBe(- "Vendor: Clears Acme Co (updated on every push)."- );- });-});--describe("releaseResultText", () => {- const base = {- revisionsCreated: 0,- itemsCreated: 0,- childrenCreated: 0,- linesWritten: 0,- methodsTouched: 0,- changeNotice: null- };-- it("counts in the singular and leaves out zero counts", () => {- expect(- releaseResultText({- ...base,- revisionsCreated: 1,- changeNotice: "CN-000008"- })- ).toBe(- "1 new revision on change notice CN-000008, inactive until it is released in Carbon"- );- });-- it("names what the notice holds, then BOM parts outside it, then the lines", () => {- expect(- releaseResultText({- ...base,- revisionsCreated: 3,- itemsCreated: 2,- childrenCreated: 1,- linesWritten: 4,- methodsTouched: 1,- changeNotice: "CN-000014"- })- ).toBe(- "3 new revisions and 2 new items on change notice CN-000014, inactive until it is released in Carbon · 1 BOM part added to Carbon · 4 BOM lines written"- );- });-- it("mentions BOMs only when the release has one", () => {- expect(releaseResultText(base)).toBe("Already in Carbon");- expect(releaseResultText({ ...base, methodsTouched: 1 })).toBe(- "Already in Carbon · BOM unchanged"- );- });-- it("reports drawings, and only drawings for a drawing-only release", () => {- expect(releaseResultText({ ...base, drawingsQueued: 1 })).toBe(- "Already in Carbon · 1 drawing sent to Carbon"- );- expect(- releaseResultText({ ...base, drawingsQueued: 2, drawingsOnly: true })- ).toBe("2 drawings sent to Carbon");- expect(releaseResultText({ ...base, drawingsOnly: true })).toBe(- "Nothing to push"- );- });-});diff --git a/packages/ee/src/paperless-parts/lib/utils.test.ts b/packages/ee/src/paperless-parts/lib/utils.test.tsindex b3d274ebff..98a450e272 100644--- a/packages/ee/src/paperless-parts/lib/utils.test.ts+++ b/packages/ee/src/paperless-parts/lib/utils.test.ts@@ -3,235 +3,88 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.import type { Database } from "@carbon/database";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { calculatePromisedDate } from "./utils";-describe("calculatePromisedDate", () => {- beforeEach(() => {- // Reset time mocking before each test- vi.restoreAllMocks();- });-- afterEach(() => {- vi.restoreAllMocks();- });-- it("should calculate ship date before cutoff time (7 AM) with 3 business days lead time", () => {- // Mock date: August 20, 2024 at 7:00 AM (Tuesday)- const mockDate = new Date("2024-08-20T07:00:00");- vi.useFakeTimers();- vi.setSystemTime(mockDate);-- const holidays: Database["public"]["Tables"]["holiday"]["Row"][] = [];- const leadTime = 3;-- const result = calculatePromisedDate(leadTime, holidays);- const resultDate = new Date(result);-- // Expected: August 23, 2024 (Friday) - 3 business days from Aug 20- expect(resultDate.getDate()).toBe(23);- expect(resultDate.getMonth()).toBe(7); // August is month 7 (0-indexed)- expect(resultDate.getFullYear()).toBe(2024);-- vi.useRealTimers();- });-- it("should calculate ship date after cutoff time (11 AM) with 3 business days lead time", () => {- // Mock date: Thursday August 22, 2024 at 11:00 AM- // This matches the user's example where order after cutoff rolls to next day- const mockDate = new Date("2024-08-22T11:00:00");- vi.useFakeTimers();- vi.setSystemTime(mockDate);-- const holidays: Database["public"]["Tables"]["holiday"]["Row"][] = [];- const leadTime = 3;-- const result = calculatePromisedDate(leadTime, holidays);- const resultDate = new Date(result);-- // Expected: August 28, 2024 (Wednesday)- // After cutoff on Aug 22 (Thu), start from Aug 23 (Fri)- // Add 3 business days: Aug 26 (Mon) +1, Aug 27 (Tue) +2, Aug 28 (Wed) +3- expect(resultDate.getDate()).toBe(28);- expect(resultDate.getMonth()).toBe(7); // August- expect(resultDate.getFullYear()).toBe(2024);-- vi.useRealTimers();- });-- it("should account for holidays when calculating ship date", () => {- // Mock date: August 29, 2024 at 7:00 AM (Thursday)- const mockDate = new Date("2024-08-29T07:00:00");- vi.useFakeTimers();- vi.setSystemTime(mockDate);-- // Labor Day 2024 is September 2 (Monday)- const holidays: Database["public"]["Tables"]["holiday"]["Row"][] = [- {- id: "1",- companyId: "test-company",- name: "Labor Day",- date: "2024-09-02",- year: 2024,- tags: [],- customFields: {},- createdAt: new Date().toISOString(),- updatedAt: new Date().toISOString(),- createdBy: "system",- updatedBy: "system"- }- ];- const leadTime = 3;-- const result = calculatePromisedDate(leadTime, holidays);- const resultDate = new Date(result);-- // Start: Aug 29 (Thu) before cutoff- // Add 3 business days: Aug 30 (Fri) +1, Aug 31-Sep 1 (weekend skip),- // Sep 2 (Mon holiday skip), Sep 3 (Tue) +2, Sep 4 (Wed) +3- expect(resultDate.getDate()).toBe(4);- expect(resultDate.getMonth()).toBe(8); // September is month 8- expect(resultDate.getFullYear()).toBe(2024);-- vi.useRealTimers();- });-- it("should handle weekend rollovers correctly", () => {- // Mock date: Friday at 9:00 AM- const mockDate = new Date("2024-08-23T09:00:00"); // Friday- vi.useFakeTimers();- vi.setSystemTime(mockDate);-- const holidays: Database["public"]["Tables"]["holiday"]["Row"][] = [];- const leadTime = 2;-- const result = calculatePromisedDate(leadTime, holidays);- const resultDate = new Date(result);-- // Expected: August 27, 2024 (Tuesday)- // From Aug 23 (Fri): Aug 26 (Mon) day 1, Aug 27 (Tue) day 2- expect(resultDate.getDate()).toBe(27);- expect(resultDate.getMonth()).toBe(7); // August- expect(resultDate.getFullYear()).toBe(2024);-- vi.useRealTimers();- });-- it("should handle multiple holidays correctly", () => {- // Mock date: August 29, 2024 before cutoff- const mockDate = new Date("2024-08-29T07:00:00");- vi.useFakeTimers();- vi.setSystemTime(mockDate);-- const holidays: Database["public"]["Tables"]["holiday"]["Row"][] = [- {- id: "1",- companyId: "test-company",- name: "Labor Day",- date: "2024-09-02",- year: 2024,- tags: [],- customFields: {},- createdAt: new Date().toISOString(),- updatedAt: new Date().toISOString(),- createdBy: "system",- updatedBy: "system"- },- {- id: "2",- companyId: "test-company",- name: "Custom Holiday",- date: "2024-09-03",- year: 2024,- tags: [],- customFields: {},- createdAt: new Date().toISOString(),- updatedAt: new Date().toISOString(),- createdBy: "system",- updatedBy: "system"- }- ];- const leadTime = 3;-- const result = calculatePromisedDate(leadTime, holidays);- const resultDate = new Date(result);-- // Expected: September 5, 2024 (Thursday)- // From Aug 29 (Thu): Add 3 business days- // Aug 30 (Fri) +1, Aug 31-Sep 1 (weekend skip),- // Sep 2 (Mon holiday skip), Sep 3 (Tue holiday skip),- // Sep 4 (Wed) +2, Sep 5 (Thu) +3- expect(resultDate.getDate()).toBe(5);- expect(resultDate.getMonth()).toBe(8); // September- expect(resultDate.getFullYear()).toBe(2024);-- vi.useRealTimers();- });-- it("should handle same-day orders before cutoff with 1 day lead time", () => {- // Mock date: Monday at 9:00 AM- const mockDate = new Date("2024-08-19T09:00:00");- vi.useFakeTimers();- vi.setSystemTime(mockDate);-- const holidays: Database["public"]["Tables"]["holiday"]["Row"][] = [];- const leadTime = 1;-- const result = calculatePromisedDate(leadTime, holidays);- const resultDate = new Date(result);-- // Expected: August 20, 2024 (Tuesday) - next business day- expect(resultDate.getDate()).toBe(20);- expect(resultDate.getMonth()).toBe(7); // August- expect(resultDate.getFullYear()).toBe(2024);-- vi.useRealTimers();- });-- it("should handle orders placed on Friday after cutoff", () => {- // Mock date: Friday at 11:00 AM- const mockDate = new Date("2024-08-23T11:00:00");- vi.useFakeTimers();- vi.setSystemTime(mockDate);-- const holidays: Database["public"]["Tables"]["holiday"]["Row"][] = [];- const leadTime = 1;-- const result = calculatePromisedDate(leadTime, holidays);- const resultDate = new Date(result);+type Holiday = Database["public"]["Tables"]["holiday"]["Row"];++const holiday = (date: string): Holiday => ({+ id: date,+ companyId: "company",+ name: date,+ date,+ year: 2024,+ tags: [],+ customFields: {},+ createdAt: "2024-01-01T00:00:00Z",+ updatedAt: null,+ createdBy: "system",+ updatedBy: null+});- // Expected: August 26, 2024 (Monday)- // After cutoff on Fri Aug 23, start from Sat Aug 24- // Add 1 business day: skip weekend, Aug 26 (Mon) +1- expect(resultDate.getDate()).toBe(26);- expect(resultDate.getMonth()).toBe(7); // August- expect(resultDate.getFullYear()).toBe(2024);+// The result is local midnight, so read it back in local time.+const localDay = (iso: string) => {+ const d = new Date(iso);+ const pad = (n: number) => String(n).padStart(2, "0");+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;+};- vi.useRealTimers();- });+afterEach(() => {+ vi.useRealTimers();+});- it("should handle exactly at cutoff time (10 AM)", () => {- // Mock date: Tuesday at exactly 10:00 AM- const mockDate = new Date("2024-08-20T10:00:00");+describe("calculatePromisedDate", () => {+ // 2024-08-19 is a Monday; Labor Day 2024-09-02 is a Monday.+ it.each<[string, string, number, string[], string]>([+ [+ "counts from today before the 10:00 cutoff",+ "2024-08-20T07:00:00",+ 3,+ [],+ "2024-08-23"+ ],+ [+ "counts from tomorrow after the cutoff",+ "2024-08-22T11:00:00",+ 3,+ [],+ "2024-08-28"+ ],+ [+ "treats exactly 10:00 as after the cutoff",+ "2024-08-20T10:00:00",+ 2,+ [],+ "2024-08-23"+ ],+ ["skips the weekend", "2024-08-23T09:00:00", 2, [], "2024-08-27"],+ [+ "promises the next weekday for a one-day lead time",+ "2024-08-19T09:00:00",+ 1,+ [],+ "2024-08-20"+ ],+ [+ "rolls a Friday-after-cutoff order past the weekend",+ "2024-08-23T11:00:00",+ 1,+ [],+ "2024-08-26"+ ],+ ["skips a holiday", "2024-08-29T07:00:00", 3, ["2024-09-02"], "2024-09-04"],+ [+ "skips consecutive holidays",+ "2024-08-29T07:00:00",+ 3,+ ["2024-09-02", "2024-09-03"],+ "2024-09-05"+ ]+ ])("%s", (_name, now, leadTime, holidays, expected) => {vi.useFakeTimers();- vi.setSystemTime(mockDate);-- const holidays: Database["public"]["Tables"]["holiday"]["Row"][] = [];- const leadTime = 2;-- const result = calculatePromisedDate(leadTime, holidays);- const resultDate = new Date(result);-- // Expected: August 23, 2024 (Friday)- // At 10 AM (>= cutoff), start from next day Aug 21- // Add 2 business days: Aug 21 (Wed) +1, Aug 22 (Thu) +2, result Aug 22...- // Wait result is 23, so Aug 21 +1, Aug 22 +2 would be Aug 22, but we got 23- // Let me check: at cutoff on Tue Aug 20, start from Wed Aug 21- // Add 2 business days: Aug 22 (Thu) +1, Aug 23 (Fri) +2- expect(resultDate.getDate()).toBe(23);- expect(resultDate.getMonth()).toBe(7); // August- expect(resultDate.getFullYear()).toBe(2024);-- vi.useRealTimers();+ vi.setSystemTime(new Date(now));+ expect(+ localDay(calculatePromisedDate(leadTime, holidays.map(holiday)))+ ).toBe(expected);});});diff --git a/packages/ee/src/ramp/config.test.ts b/packages/ee/src/ramp/config.test.tsindex e2a2658d27..023a6221a3 100644--- a/packages/ee/src/ramp/config.test.ts+++ b/packages/ee/src/ramp/config.test.ts@@ -71,65 +71,15 @@ describe("Ramp settings by install mode", () => {expect(accountSettings.filter((s) => surviving.has(s.name))).toEqual([]);});- it("gives every mode its own copy, so no install shows the all-modes blurb", () => {- // The bug this pins: the drawer and the card fell back to- // `integration.description`, which describes every mode at once — it told a- // push-only customer that Carbon "pulls your charges, bills, and employee- // reimbursements into Carbon's general ledger", the exact opposite of what- // that mode does. A mode added without its own copy silently reintroduces it.- for (const mode of Ramp.modes ?? []) {- expect(mode.label.length).toBeGreaterThan(0);- expect(mode.description.length).toBeGreaterThan(0);- expect(mode.shortDescription?.length ?? 0).toBeGreaterThan(0);- expect(mode.description).not.toBe(Ramp.description);- expect(mode.shortDescription).not.toBe(Ramp.shortDescription);- }- });-- it("does not promise inbound sync in the push-only copy", () => {- const pushOnly = (Ramp.modes ?? []).find((m) => m.id === "push-only");- const copy = `${pushOnly?.description} ${pushOnly?.shortDescription}`;- // "pull" / "into Carbon's ledger" are the claims that were wrong: this mode- // pulls nothing into the GL, and saying so is what made the whole feature- // read as the double-posting it exists to prevent.- expect(copy.toLowerCase()).not.toContain("pull");- expect(copy.toLowerCase()).not.toContain("into carbon's ledger");- });-- it("promises only the documents push-only mode can actually push", () => {- // The copy said Carbon "pushes purchase orders, receipts and provisional- // bills". Item-receipt push was designed and then dropped (2026-09-25): the- // mode's outbound ceiling is purchase orders and bills, `rampSyncerRegistry`- // registers exactly those two, and `RAMP_PUSH_ONLY_SCOPES` does not ask for- // `item_receipts:write`. This text is shown BEFORE consent for a choice that- // cannot be changed without reinstalling, so it sold a capability the mode- // does not have.- const pushOnly = (Ramp.modes ?? []).find((m) => m.id === "push-only");- const copy =- `${pushOnly?.description} ${pushOnly?.shortDescription}`.toLowerCase();-- expect(RAMP_MODE_PROFILES["push-only"].outboundCeiling).toEqual({- purchaseOrder: true,- bill: true- });- expect(pushOnly?.scopes).not.toContain("item_receipts:write");- expect(copy).toContain("purchase orders");- expect(copy).toContain("bills");- expect(copy).not.toContain("receipt");- });-it("names a ledger holder only when Carbon does not hold the seat", () => {- // A provider-mode install showed "Ramp reports the ledger is held by Rillet"- // beside "Carbon is my accounting system" — a flat contradiction, from a- // snapshot that provider mode never refreshes. Reported from the UI 2026-09-26.+ // Provider mode never refreshes the ledger-holder snapshot, so it must not show it.const stored = { accountingConnectionProvider: "Rillet" };expect(Ramp.resolveInstallMode?.({ ...stored, syncMode: "provider" })).toEqual({ id: "provider", detail: undefined });- // An install with no stored mode resolves to provider, so it must behave the- // same way — this is every pre-modes install.+ // An install with no stored mode is a provider install.expect(Ramp.resolveInstallMode?.(stored)).toEqual({id: "provider",detail: undefineddiff --git a/packages/ee/src/ramp/hooks.server.test.ts b/packages/ee/src/ramp/hooks.server.test.tsdeleted file mode 100644index 5c103fe0c6..0000000000--- a/packages/ee/src/ramp/hooks.server.test.ts+++ /dev/null@@ -1,192 +0,0 @@-// SPDX-License-Identifier: LicenseRef-Carbon-Commercial-// Carbon Enterprise file, licensed only under the Carbon Commercial License-// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.--import { beforeEach, describe, expect, it, vi } from "vitest";--const getBusiness = vi.hoisted(() => vi.fn());-const getEntities = vi.hoisted(() => vi.fn());-const getRampIntegration = vi.hoisted(() => vi.fn());-const ensureRampConnection = vi.hoisted(() => vi.fn());-const ensureRampWebhook = vi.hoisted(() => vi.fn());-const pushChartOfAccounts = vi.hoisted(() => vi.fn());-const pushCostCenters = vi.hoisted(() => vi.fn());-const pushProjects = vi.hoisted(() => vi.fn());-const trigger = vi.hoisted(() => vi.fn());-const ensureProviderSubscriptions = vi.hoisted(() => vi.fn());--vi.mock("@carbon/auth", () => ({ getAppUrl: () => "https://erp.example.com" }));-vi.mock("@carbon/auth/client.server", () => ({- getCarbonServiceRole: () => ({ role: "service" })-}));-vi.mock("@carbon/jobs", () => ({ trigger }));-// The convergence itself is covered by subscriptions-mapping.test.ts; here it-// is stubbed so these tests need no Supabase RPC fake.-vi.mock("../accounting/core/subscriptions", () => ({- ensureProviderSubscriptions-}));-vi.mock("./lib/service", () => ({- clearRampConnectionMetadata: vi.fn(),- ensureRampConnection,- ensureRampWebhook,- getRampIntegration,- pushChartOfAccounts,- pushCostCenters,- pushProjects-}));--import { rampOnInstall, rampOnUpdate } from "./hooks.server";--const credentials = {- type: "oauth2" as const,- accessToken: "access-token"-};--function integration(metadata: Record<string, unknown>) {- return {- client: { getBusiness, getEntities },- metadata: { credentials, sync: {}, ...metadata }- };-}--describe("Ramp install convergence", () => {- beforeEach(() => {- vi.clearAllMocks();- getBusiness.mockResolvedValue({ id: "business-1" });- getEntities.mockResolvedValue({ data: [{ id: "entity-1" }] });- ensureRampConnection.mockResolvedValue({ connectionId: "connection-1" });- ensureProviderSubscriptions.mockResolvedValue({ ensured: [], removed: [] });- ensureRampWebhook.mockResolvedValue({ webhookId: "webhook-1" });- pushChartOfAccounts.mockResolvedValue(undefined);- pushCostCenters.mockResolvedValue(undefined);- pushProjects.mockResolvedValue(undefined);- trigger.mockResolvedValue(undefined);- });-- it("connects OAuth without pushing or launching finance before account setup", async () => {- getRampIntegration.mockResolvedValue(integration({}));-- await rampOnInstall("company-1");-- expect(getBusiness).toHaveBeenCalledOnce();- expect(ensureRampConnection).toHaveBeenCalledOnce();- expect(ensureRampWebhook).toHaveBeenCalledOnce();- expect(pushChartOfAccounts).not.toHaveBeenCalled();- expect(pushCostCenters).not.toHaveBeenCalled();- expect(pushProjects).not.toHaveBeenCalled();- expect(trigger).not.toHaveBeenCalled();- });-- it("claims no connection and pushes no coding masters in push-only", async () => {- // The whole point of the mode. Every one of these is an `accounting:write`- // call, and Ramp permits exactly ONE connected accounting provider — making- // any of them would take the seat the customer's other system holds.- getRampIntegration.mockResolvedValue(- integration({- syncMode: "push-only",- cardLiabilityAccountId: "account-1"- })- );-- await rampOnInstall("company-1");-- expect(ensureRampConnection).not.toHaveBeenCalled();- expect(pushChartOfAccounts).not.toHaveBeenCalled();- expect(pushCostCenters).not.toHaveBeenCalled();- expect(pushProjects).not.toHaveBeenCalled();- });-- it("still registers the webhook and launches the sync in push-only", async () => {- // Push-only has plenty to do — purchase orders, receipts, provisional bills,- // and pulling bill payments back — so gating the coding masters must not- // gate the integration itself.- getRampIntegration.mockResolvedValue(- integration({- syncMode: "push-only",- cardLiabilityAccountId: "account-1"- })- );-- await rampOnInstall("company-1");-- expect(ensureRampWebhook).toHaveBeenCalledOnce();- expect(trigger).toHaveBeenCalledOnce();- });-- it("converges normally in provider mode", async () => {- getRampIntegration.mockResolvedValue(- integration({ syncMode: "provider", cardLiabilityAccountId: "account-1" })- );-- await rampOnInstall("company-1");-- expect(ensureRampConnection).toHaveBeenCalledOnce();- expect(pushChartOfAccounts).toHaveBeenCalledOnce();- });-- it("treats an install with no stored mode as provider", async () => {- // Every install predating modes must keep claiming its connection.- getRampIntegration.mockResolvedValue(- integration({ cardLiabilityAccountId: "account-1" })- );-- await rampOnInstall("company-1");-- expect(ensureRampConnection).toHaveBeenCalledOnce();- expect(pushChartOfAccounts).toHaveBeenCalledOnce();- });-- it("subscribes Ramp to the sync event system on install", async () => {- // Without this the PO/bill push is silently dead: the event handler is- // never told there is a spend provider to enqueue for.- getRampIntegration.mockResolvedValue(- integration({ cardLiabilityAccountId: "account-1" })- );-- await rampOnInstall("company-1");-- expect(ensureProviderSubscriptions).toHaveBeenCalledWith(- expect.anything(),- "company-1",- "ramp"- );- });-- it("converges master data and launches sync after required settings are saved", async () => {- getRampIntegration.mockResolvedValue(- integration({- cardLiabilityAccountId: "liability-1",- statementBankAccountId: "bank-1",- entityId: "entity-1"- })- );-- await rampOnUpdate("company-1");-- expect(getEntities).toHaveBeenCalledOnce();- expect(pushChartOfAccounts).toHaveBeenCalledOnce();- expect(pushCostCenters).toHaveBeenCalledOnce();- expect(pushProjects).toHaveBeenCalledOnce();- expect(trigger).toHaveBeenCalledWith("ramp-sync", {- companyId: "company-1",- reason: "settings-update"- });- });-- it("rejects a configured entity that the connected Ramp business does not own", async () => {- getRampIntegration.mockResolvedValue(- integration({- cardLiabilityAccountId: "liability-1",- statementBankAccountId: "bank-1",- entityId: "entity-other"- })- );-- await expect(rampOnUpdate("company-1")).rejects.toThrow(- "Ramp entity entity-other is not available"- );-- expect(pushChartOfAccounts).not.toHaveBeenCalled();- expect(trigger).not.toHaveBeenCalled();- });-});diff --git a/packages/ee/src/ramp/hooks.server.ts b/packages/ee/src/ramp/hooks.server.tsindex e9238fc419..aa6c9071f2 100644--- a/packages/ee/src/ramp/hooks.server.ts+++ b/packages/ee/src/ramp/hooks.server.ts@@ -4,6 +4,7 @@import { getAppUrl } from "@carbon/auth";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { trigger } from "@carbon/lib/trigger";import { SpendProviderID } from "../accounting/core/models";import { ensureProviderSubscriptions } from "../accounting/core/subscriptions";import { resolveCapabilities } from "../sync/capabilities";@@ -15,6 +16,7 @@ import {linkedConnections,resolveConnectedProviderName} from "./lib/connection-status";+import { extractEntityIds, planRampConvergence } from "./lib/convergence";import { rampOwnsCodingSurface, resolveRampModeProfile } from "./lib/modes";import {clearRampConnectionMetadata,@@ -60,7 +62,7 @@ async function convergeRamp();}- const ownsCodingSurface = rampOwnsCodingSurface(metadata);+ const plan = planRampConvergence(metadata);// Connecting a platform that cannot create a vendor without a reachable// contact AND an identifiable location is what makes both mandatory, so@@ -91,7 +93,7 @@ async function convergeRamp(// Only the seat-holder may create the accounting connection. In push-only// another system holds it, and claiming it is precisely what this mode exists// to avoid.- if (ownsCodingSurface) {+ if (plan.claimConnection) {await ensureRampConnection(serviceRole, companyId);}@@ -107,7 +109,7 @@ async function convergeRamp(// transient Ramp outage. Confirmed 2026-09-26 that a push-only token (no// `accounting:write`) may call this endpoint, so a refusal here is unexpected// rather than routine.- if (!ownsCodingSurface) {+ if (plan.refreshConnectionOwner) {try {await patchRampAccountingConnectionProvider(serviceRole,@@ -156,23 +158,26 @@ async function convergeRamp(// does not even offer the field. Returning here would have skipped the sync// enqueue below, so push-only would have pushed nothing until the next hourly// sweep.- if (ownsCodingSurface && !metadata.cardLiabilityAccountId) {+ if (!plan.launchSync) {return;}- if (metadata.entityId) {+ if (plan.validateEntityId) {let response: unknown;try {response = await client.getEntities();} catch (error) {- throw new Error(`Could not validate Ramp entity ${metadata.entityId}`, {- cause: error- });+ throw new Error(+ `Could not validate Ramp entity ${plan.validateEntityId}`,+ {+ cause: error+ }+ );}- if (!extractEntityIds(response).has(metadata.entityId)) {+ if (!extractEntityIds(response).has(plan.validateEntityId)) {throw new Error(- `Ramp entity ${metadata.entityId} is not available to this connection`+ `Ramp entity ${plan.validateEntityId} is not available to this connection`);}}@@ -184,7 +189,7 @@ async function convergeRamp(//// The sync still launches below: push-only has plenty to do (purchase orders,// receipts, provisional bills, and pulling bill payments back).- if (ownsCodingSurface) {+ if (plan.pushCodingMasters) {await pushChartOfAccounts(serviceRole, companyId);// Converge the cost-center ("project") field + its options. It re-runs on// every ramp-sync too, so a Ramp-side rejection here must not abort a valid@@ -209,23 +214,13 @@ async function convergeRamp(}}- // `@carbon/jobs` is deliberately NOT an `@carbon/ee` dependency (jobs -> ee,- // never the reverse), so the `ramp-sync` task — registered in- // packages/jobs/src/inngest/index.ts + packages/lib/src/trigger.ts — is- // reached via a lazy runtime import resolved through the app that owns both- // packages. The non-literal specifier keeps TS from resolving/type-checking a- // module ee cannot see.+ // Queued through @carbon/lib's trigger, as the Slack service does: ee cannot+ // depend on @carbon/jobs (jobs depends on ee), and importing jobs at runtime+ // fails in the built server, which runs its TypeScript source.// A failure to enqueue the initial sync must not fail the connect — the// hourly `ramp-sweep` fires `ramp-sync` for every active company regardless.try {- const jobsModule = "@carbon/jobs";- const jobs = (await import(/* @vite-ignore */ jobsModule)) as {- trigger: (- task: string,- payload: { companyId: string; reason: string }- ) => Promise<unknown>;- };- await jobs.trigger("ramp-sync", {+ await trigger("ramp-sync", {companyId,reason: opts.syncReason});@@ -332,28 +327,6 @@ export async function rampOnUninstall(companyId: string): Promise<void> {}}-/** Extract entity ids from Ramp's `{ data }`, `{ entities }`, or bare-array shape. */-function extractEntityIds(response: unknown): Set<string> {- let rows: unknown[] = [];- if (Array.isArray(response)) {- rows = response;- } else if (response && typeof response === "object") {- const value = response as { data?: unknown; entities?: unknown };- if (Array.isArray(value.data)) rows = value.data;- else if (Array.isArray(value.entities)) rows = value.entities;- }-- return new Set(- rows.flatMap((row) =>- row &&- typeof row === "object" &&- typeof (row as { id?: unknown }).id === "string"- ? [(row as { id: string }).id]- : []- )- );-}-export async function rampHealthcheck(companyId: string,_metadata: Record<string, unknown>diff --git a/packages/ee/src/ramp/lib/__tests__/provider.test.ts b/packages/ee/src/ramp/lib/__tests__/provider.test.tsindex 1591ace8e3..0938d61945 100644--- a/packages/ee/src/ramp/lib/__tests__/provider.test.ts+++ b/packages/ee/src/ramp/lib/__tests__/provider.test.ts@@ -32,24 +32,6 @@ function makeProvider(}describe("RampProvider", () => {- it("identifies as the ramp spend provider", () => {- const { provider } = makeProvider();-- expect(provider.id).toBe("ramp");- expect(provider.capabilities).toEqual({- role: "spend",- transport: "rest",- supportsWebhooks: true,- ownsRemoteCodingSurface: true,- ownsLedgerFamilies: [],- // Ramp cannot create a spend vendor without a contact email, so- // connecting it turns `requireSupplierContactAndLocation` on — see- // `sync/party-contact.ts`. Declared on the MODE profile, so this is also- // what stops the requirement being a Ramp-shaped special case.- requiresPartyContactAndLocation: ["supplier"]- });- });-it("maps the stored push flags onto the entities it syncs", () => {const { provider } = makeProvider({ pushInvoices: false });diff --git a/packages/ee/src/ramp/lib/__tests__/suppliers.test.ts b/packages/ee/src/ramp/lib/__tests__/suppliers.test.tsdeleted file mode 100644index c673f14dbf..0000000000--- a/packages/ee/src/ramp/lib/__tests__/suppliers.test.ts+++ /dev/null@@ -1,181 +0,0 @@-// SPDX-License-Identifier: LicenseRef-Carbon-Commercial-// Carbon Enterprise file, licensed only under the Carbon Commercial License-// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.--import type { SupabaseClient } from "@supabase/supabase-js";-import { beforeEach, describe, expect, it, vi } from "vitest";-import { resolveMerchantSupplier } from "../suppliers";--// Mock the Kysely-side mapping service the resolver constructs. The path is the-// one `suppliers.ts` imports (`../../accounting/core/external-mapping`), resolved-// relative to THIS test file.-const getEntityId = vi.fn();-const link = vi.fn();-vi.mock("../../../accounting/core/external-mapping", () => ({- createMappingService: () => ({ getEntityId, link })-}));--type Result = { data: unknown; error: unknown };--/** Recorded across a run so a test can assert what the resolver did. */-type Recorder = {- ilikeArgs: unknown[];- supplierInserts: number;-};--/**- * A minimal chainable Supabase stub. `route(table, calls)` returns the terminal- * result for a chain; `select/eq/ilike/insert` are pass-through recorders.- */-function makeClient(- route: (table: string, calls: { m: string; a: unknown[] }[]) => Result,- rec: Recorder-): SupabaseClient {- const from = vi.fn((table: string) => {- const calls: { m: string; a: unknown[] }[] = [];- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const builder: any = {};- for (const m of ["select", "eq", "insert", "update"]) {- builder[m] = vi.fn((...a: unknown[]) => {- calls.push({ m, a });- if (m === "insert" && table === "supplier") rec.supplierInserts += 1;- return builder;- });- }- builder.ilike = vi.fn((...a: unknown[]) => {- calls.push({ m: "ilike", a });- if (table === "supplier") rec.ilikeArgs.push(a[1]);- return builder;- });- const terminal = (m: string) =>- vi.fn((...a: unknown[]) => {- calls.push({ m, a });- return Promise.resolve(route(table, calls));- });- builder.maybeSingle = terminal("maybeSingle");- builder.single = terminal("single");- builder.limit = terminal("limit");- return builder;- });- // eslint-disable-next-line @typescript-eslint/no-explicit-any- return { from } as any;-}--type Scenario = {- mappingHit?: string; // getEntityId returns this id- nameMatch?: string; // an existing supplier matches by name- catchAllExisting?: string; // the house "Card Merchant" supplier already exists- catchAllInsertId?: string; // id returned when the house supplier is created-};--function router(scenario: Scenario, rec: Recorder) {- return (table: string, calls: { m: string; a: unknown[] }[]): Result => {- if (table === "supplierType") {- // ensureSupplierTypeId: the "Card Merchant" type already exists.- return { data: { id: "st_card" }, error: null };- }- if (table === "supplier") {- const hasInsert = calls.some((c) => c.m === "insert");- const hasIlike = calls.some((c) => c.m === "ilike");- if (hasInsert) {- return {- data: { id: scenario.catchAllInsertId ?? "sup_new" },- error: null- };- }- if (hasIlike) {- return {- data: scenario.nameMatch ? [{ id: scenario.nameMatch }] : [],- error: null- };- }- // catch-all find (eq name + eq supplierTypeId + maybeSingle)- return {- data: scenario.catchAllExisting- ? { id: scenario.catchAllExisting }- : null,- error: null- };- }- throw new Error(`unexpected table ${table}`);- };-}--function runResolve(- scenario: Scenario,- merchant: { id?: string | null; name: string }-): { promise: Promise<string>; rec: Recorder } {- const rec: Recorder = { ilikeArgs: [], supplierInserts: 0 };- getEntityId.mockResolvedValue(scenario.mappingHit ?? null);- const client = makeClient(router(scenario, rec), rec);- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const kysely = {} as any;- return {- promise: resolveMerchantSupplier(client, kysely, "company-1", merchant),- rec- };-}--describe("resolveMerchantSupplier", () => {- beforeEach(() => {- getEntityId.mockReset();- link.mockReset();- });-- it("returns the mapped supplier when the merchant is already mapped", async () => {- const { promise, rec } = runResolve(- { mappingHit: "sup_mapped" },- { id: "ramp-merchant-1", name: "Shell Oil" }- );- expect(await promise).toBe("sup_mapped");- expect(rec.supplierInserts).toBe(0);- expect(rec.ilikeArgs).toHaveLength(0); // no name query when mapped- expect(link).not.toHaveBeenCalled();- });-- it("links an existing supplier matched by exact name", async () => {- const { promise, rec } = runResolve(- { nameMatch: "sup_mcmaster" },- { id: "ramp-merchant-2", name: "McMaster-Carr" }- );- expect(await promise).toBe("sup_mcmaster");- expect(rec.supplierInserts).toBe(0);- expect(link).toHaveBeenCalledWith(- "merchant",- "sup_mcmaster",- expect.anything(),- "ramp-merchant-2",- expect.objectContaining({ createdBy: "system" })- );- });-- it("creates the single house supplier when there is no mapping or name match", async () => {- const { promise, rec } = runResolve(- { catchAllInsertId: "sup_catchall" },- { id: "ramp-merchant-3", name: "Some Gas Station" }- );- expect(await promise).toBe("sup_catchall");- expect(rec.supplierInserts).toBe(1);- // The catch-all fallback must NOT write a per-merchant mapping.- expect(link).not.toHaveBeenCalled();- });-- it("reuses the existing house supplier without a second insert", async () => {- const { promise, rec } = runResolve(- { catchAllExisting: "sup_catchall" },- { id: "ramp-merchant-4", name: "Another One-Off" }- );- expect(await promise).toBe("sup_catchall");- expect(rec.supplierInserts).toBe(0);- expect(link).not.toHaveBeenCalled();- });-- it("escapes ilike wildcards in the merchant name", async () => {- const { promise, rec } = runResolve(- { catchAllExisting: "sup_catchall" },- { id: "ramp-merchant-5", name: "50% Off Supply" }- );- await promise;- expect(rec.ilikeArgs).toEqual(["50\\% Off Supply"]);- });-});diff --git a/packages/ee/src/ramp/lib/convergence.test.ts b/packages/ee/src/ramp/lib/convergence.test.tsnew file mode 100644index 0000000000..6a8548033f--- /dev/null+++ b/packages/ee/src/ramp/lib/convergence.test.ts@@ -0,0 +1,99 @@+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial+// Carbon Enterprise file, licensed only under the Carbon Commercial License+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.++import { describe, expect, it } from "vitest";+import {+ extractEntityIds,+ planRampConvergence,+ type RampConvergencePlan+} from "./convergence";++type Metadata = Parameters<typeof planRampConvergence>[0];++function base(overrides: Partial<Metadata> = {}): Metadata {+ return {+ syncMode: "provider",+ cardLiabilityAccountId: "account-1",+ ...overrides+ };+}++const providerReady: RampConvergencePlan = {+ claimConnection: true,+ refreshConnectionOwner: false,+ validateEntityId: null,+ pushCodingMasters: true,+ launchSync: true+};++describe("planRampConvergence", () => {+ it("claims the connection, pushes coding masters and syncs in provider mode", () => {+ expect(planRampConvergence(base())).toEqual(providerReady);+ });++ it("treats an install with no stored mode as provider", () => {+ // Every install predating modes must keep claiming its connection.+ expect(planRampConvergence(base({ syncMode: undefined }))).toEqual(+ providerReady+ );+ });++ it("connects but pushes and syncs nothing until the card liability account is mapped", () => {+ expect(+ planRampConvergence(+ base({ cardLiabilityAccountId: undefined, entityId: "entity-1" })+ )+ ).toEqual({+ claimConnection: true,+ refreshConnectionOwner: false,+ validateEntityId: null,+ pushCodingMasters: false,+ launchSync: false+ });+ });++ it.each([["account-1"], [undefined]])(+ "in push-only never claims the connection or pushes masters, but still syncs (card liability %s)",+ (cardLiabilityAccountId) => {+ // Ramp allows one accounting connection; push-only leaves it to the+ // customer's other system, and has no card journal to need the account.+ expect(+ planRampConvergence(+ base({ syncMode: "push-only", cardLiabilityAccountId })+ )+ ).toEqual({+ claimConnection: false,+ refreshConnectionOwner: true,+ validateEntityId: null,+ pushCodingMasters: false,+ launchSync: true+ });+ }+ );++ it("validates a configured entity before pushing", () => {+ expect(planRampConvergence(base({ entityId: "entity-1" }))).toEqual({+ ...providerReady,+ validateEntityId: "entity-1"+ });+ });+});++describe("extractEntityIds", () => {+ it.each([+ ["{ data }", { data: [{ id: "a" }, { id: "b" }] }],+ ["{ entities }", { entities: [{ id: "a" }, { id: "b" }] }],+ ["a bare array", [{ id: "a" }, { id: "b" }]]+ ])("reads ids from %s", (_shape, response) => {+ expect(extractEntityIds(response)).toEqual(new Set(["a", "b"]));+ });++ it("skips rows without a string id and unknown shapes", () => {+ expect(+ extractEntityIds({ data: [{ id: 7 }, null, { name: "x" }, { id: "a" }] })+ ).toEqual(new Set(["a"]));+ expect(extractEntityIds({ rows: [{ id: "a" }] })).toEqual(new Set());+ expect(extractEntityIds(null)).toEqual(new Set());+ });+});diff --git a/packages/ee/src/ramp/lib/convergence.ts b/packages/ee/src/ramp/lib/convergence.tsnew file mode 100644index 0000000000..b0e6f8c59b--- /dev/null+++ b/packages/ee/src/ramp/lib/convergence.ts@@ -0,0 +1,65 @@+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial+// Carbon Enterprise file, licensed only under the Carbon Commercial License+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.++import type { RampIntegrationMetadata } from "./models";+import { rampOwnsCodingSurface } from "./modes";++/**+ * What `convergeRamp` does for one install, decided from its stored metadata.+ * Subscriptions and the webhook always converge, so they are not in the plan.+ */+export type RampConvergencePlan = {+ /** Create Ramp's accounting connection (an `accounting:write` call). */+ claimConnection: boolean;+ /** Re-read which other system holds the seat. */+ refreshConnectionOwner: boolean;+ /** Entity to check against the business before anything is pushed. */+ validateEntityId: string | null;+ /** Push chart of accounts, cost centers and projects. */+ pushCodingMasters: boolean;+ launchSync: boolean;+};++export function planRampConvergence(+ metadata: Pick<+ RampIntegrationMetadata,+ "syncMode" | "cardLiabilityAccountId" | "entityId"+ >+): RampConvergencePlan {+ // Only the seat-holder may write accounting masters: in push-only another+ // system holds Ramp's single accounting connection.+ const owns = rampOwnsCodingSurface(metadata);+ // The seat-holder posts card journals against this account, so nothing is+ // pushed or synced until it is mapped. Push-only posts no card journal.+ const ready = !owns || Boolean(metadata.cardLiabilityAccountId);+ return {+ claimConnection: owns,+ refreshConnectionOwner: !owns,+ validateEntityId: ready ? (metadata.entityId ?? null) : null,+ pushCodingMasters: owns && ready,+ launchSync: ready+ };+}++/** Extract entity ids from Ramp's `{ data }`, `{ entities }`, or bare-array shape. */+export function extractEntityIds(response: unknown): Set<string> {+ let rows: unknown[] = [];+ if (Array.isArray(response)) {+ rows = response;+ } else if (response && typeof response === "object") {+ const value = response as { data?: unknown; entities?: unknown };+ if (Array.isArray(value.data)) rows = value.data;+ else if (Array.isArray(value.entities)) rows = value.entities;+ }++ return new Set(+ rows.flatMap((row) =>+ row &&+ typeof row === "object" &&+ typeof (row as { id?: unknown }).id === "string"+ ? [(row as { id: string }).id]+ : []+ )+ );+}diff --git a/packages/ee/src/ramp/lib/suppliers.ts b/packages/ee/src/ramp/lib/suppliers.tsindex 42e2bb5c9e..19282e658e 100644--- a/packages/ee/src/ramp/lib/suppliers.ts+++ b/packages/ee/src/ramp/lib/suppliers.ts@@ -4,6 +4,7 @@import type { Database } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import { escapeLike } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { createMappingService } from "../../accounting/core/external-mapping";import { RAMP } from "./connection";@@ -44,7 +45,7 @@ export async function resolveRampSupplier(// `%`/`_` must be escaped before `ilike` — otherwise a merchant like// "50% Off Supply" becomes a wildcard pattern and matches an unrelated// supplier, linking the two permanently.- const escapedName = vendor.name.replace(/[\\%_]/g, (m) => `\\${m}`);+ const escapedName = escapeLike(vendor.name);const { data: matches } = await serviceRole.from("supplier").select("id")@@ -156,7 +157,7 @@ export async function resolveMerchantSupplier(// 2. Exact-name match to an EXISTING supplier. If the merchant is a real// vendor you already trade with, link card spend to it. `%`/`_` escaped so a// merchant like "50% Off Supply" cannot become a wildcard pattern.- const escapedName = merchant.name.replace(/[\\%_]/g, (m) => `\\${m}`);+ const escapedName = escapeLike(merchant.name);const { data: matches } = await serviceRole.from("supplier").select("id")diff --git a/packages/ee/src/spend/push-only-syncer.test.ts b/packages/ee/src/spend/push-only-syncer.test.tsindex 32b09346be..12411d2c41 100644--- a/packages/ee/src/spend/push-only-syncer.test.ts+++ b/packages/ee/src/spend/push-only-syncer.test.ts@@ -3,32 +3,28 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.import type { KyselyTx } from "@carbon/database/client";-import { describe, expect, it, vi } from "vitest";--/**- * The ONE stub, and it is the real external boundary: `withTriggersDisabled`- * opens a Postgres transaction and issues `SET LOCAL app.sync_in_progress`. The- * behaviour under test is WHEN the mapping write happens relative to the next- * platform call, not what a Kysely transaction does — so the wrapper hands the- * callback a sentinel and everything else below runs real.- */-const TX = { sentinel: true } as unknown as KyselyTx;--vi.mock("../accounting/core/utils", async (importOriginal) => {- const actual =- await importOriginal<typeof import("../accounting/core/utils")>();- return {- ...actual,- withTriggersDisabled: async <T>(- _db: unknown,- operation: (tx: KyselyTx) => Promise<T>- ) => operation(TX)- };-});-+import {+ DummyDriver,+ Kysely,+ PostgresAdapter,+ PostgresIntrospector,+ PostgresQueryCompiler+} from "kysely";+import { describe, expect, it } from "vitest";import type { EntityConfig, SyncContext } from "../accounting/core/types";import { SpendPushOnlyEntitySyncer } from "./push-only-syncer";+// The Postgres wire is the boundary: a Kysely over a driver that answers every+// statement with no rows, so the trigger-disabled transaction really opens.+const database = new Kysely({+ dialect: {+ createAdapter: () => new PostgresAdapter(),+ createDriver: () => new DummyDriver(),+ createIntrospector: (db) => new PostgresIntrospector(db),+ createQueryCompiler: () => new PostgresQueryCompiler()+ }+});+type TestLocal = { id: string; updatedAt: string };type TestRemote = { name: string };@@ -118,7 +114,7 @@ function makeSyncer(): TestSpendSyncer {return new TestSpendSyncer({- database: {} as never,+ database: database as never,companyId: "company-1",provider: { id: "ramp" } as never,entityType: "purchaseOrder",@@ -161,7 +157,7 @@ describe("SpendPushOnlyEntitySyncer.pushBatchToAccounting", () => {expect(syncer.linked.map((entry) => entry.localId)).toEqual(["a", "c"]);expect(syncer.linked[0]?.remoteId).toBe("remote-a");// Written through the trigger-disabled transaction, not the bare database.- expect(syncer.linked[0]?.tx).toBe(TX);+ expect(syncer.linked[0]?.tx.isTransaction).toBe(true);});it("does not report an already-pushed document as failed", async () => {diff --git a/packages/ee/src/sso/sso.server.test.ts b/packages/ee/src/sso/sso.server.test.tsindex ab15288723..42c0bffab0 100644--- a/packages/ee/src/sso/sso.server.test.ts+++ b/packages/ee/src/sso/sso.server.test.ts@@ -3,7 +3,7 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.import type { User, UserIdentity } from "@supabase/supabase-js";-import type { CompiledQuery, DatabaseConnection, Driver } from "kysely";+import type { DatabaseConnection, Driver } from "kysely";import {Kysely,PostgresAdapter,@@ -306,28 +306,6 @@ describe("isSsoRequiredForEmail", () => {await expect(isSsoRequiredForEmail(client, "jane")).resolves.toBe(false);expect(calls.from).toBeUndefined();});-- it("matches the domain case-insensitively (lowercased before the lookup)", async () => {- const { client, calls } = makeSsoClient({- data: { requireSso: true },- error: null- });- await expect(isSsoRequiredForEmail(client, "[email protected]")).resolves.toBe(- true- );- expect(calls.eq).toContainEqual(["ssoDomain.domain", "acme.com"]);- });-- it("only matches VERIFIED domain claims (pending claims must not enforce)", async () => {- const { client, calls } = makeSsoClient({- data: { requireSso: true },- error: null- });- await expect(isSsoRequiredForEmail(client, "[email protected]")).resolves.toBe(- true- );- expect(calls.eq).toContainEqual(["ssoDomain.status", "verified"]);- });});describe("getSsoConnection domains mapping", () => {@@ -498,13 +476,21 @@ describe("isSsoEnabled gate (AUTH_PROVIDERS half toggled off)", () => {});});-// --- auth.identities write coverage ------------------------------------------// The pre-seed helpers issue raw `sql` writes to the auth schema — the load--// bearing half of provider-agnostic linking. A stubbed db handle proves nothing,-// so drive Kysely's REAL Postgres compiler with a fake driver that captures the-// compiled SQL + parameters. A revert of the target table, columns, ON CONFLICT-// clause, email/domain lowercasing, or RETURNING would fail these.-function makeKysely(connection: DatabaseConnection) {+// The pre-seed helpers write raw SQL to auth.identities; what they write is a+// database-test concern. These pin only how a driver result becomes the reply.+function fakeDb(+ result: { rows?: unknown[]; numAffectedRows?: bigint } | Error+) {+ const connection: DatabaseConnection = {+ async executeQuery() {+ if (result instanceof Error) throw result;+ return {+ rows: result.rows ?? [],+ numAffectedRows: result.numAffectedRows+ } as never;+ },+ async *streamQuery() {}+ };const driver: Driver = {async init() {},async acquireConnection() {@@ -523,142 +509,45 @@ function makeKysely(connection: DatabaseConnection) {createIntrospector: (db) => new PostgresIntrospector(db),createQueryCompiler: () => new PostgresQueryCompiler()}- });-}--function makeCapturingDb(result: {- rows?: unknown[];- numAffectedRows?: bigint;-}) {- const captured: { sql: string; parameters: readonly unknown[] }[] = [];- const connection: DatabaseConnection = {- async executeQuery(compiledQuery: CompiledQuery) {- captured.push({- sql: compiledQuery.sql,- parameters: compiledQuery.parameters- });- return {- rows: result.rows ?? [],- numAffectedRows: result.numAffectedRows- } as never;- },- async *streamQuery() {}- };- return { db: makeKysely(connection) as never, captured };-}--function makeThrowingDb(message: string) {- const connection: DatabaseConnection = {- async executeQuery() {- throw new Error(message);- },- async *streamQuery() {}- };- return makeKysely(connection) as never;+ }) as never;}-describe("pre-seed identity writes (auth.identities SQL)", () => {- it("seedSsoIdentityForUser inserts a link row keyed on the lowercased email", async () => {- const { db, captured } = makeCapturingDb({ numAffectedRows: 1n });- const result = await seedSsoIdentityForUser(db, {- userId: "11111111-1111-1111-1111-111111111111",- email: "[email protected]",- providerId: "prov-1"- });+describe("pre-seed identity writes", () => {+ const seed = { userId: "u1", email: "[email protected]", providerId: "prov-1" };+ const domain = { providerId: "prov-1", domain: "acme.com" };- expect(result.error).toBeNull();- expect(result.data).toEqual({ seeded: true });- expect(captured).toHaveLength(1);-- const { sql, parameters } = captured[0]!;- expect(sql).toContain("INSERT INTO auth.identities");- expect(sql).toContain("(provider_id, provider) DO NOTHING");- // email is lowercased before it becomes provider_id and identity_data- expect(parameters).toContain("[email protected]");- expect(parameters).not.toContain("[email protected]");- expect(parameters).toContain("11111111-1111-1111-1111-111111111111");- expect(parameters).toContain("sso:prov-1");- });-- it("seedSsoIdentityForUser reports seeded:false when the row already exists", async () => {- const { db } = makeCapturingDb({ numAffectedRows: 0n });- const result = await seedSsoIdentityForUser(db, {- userId: "u1",- email: "[email protected]",- providerId: "prov-1"- });- expect(result).toEqual({ data: { seeded: false }, error: null });- });-- it("canonicalizes a mixed-case IdP email to lowercase in every seeded slot", async () => {- // GoTrue's account-linking fallback matches on the GENERATED email column- // (lower(identity_data->>'email')), so a case-preserving NameID must still- // resolve to the seeded row. Every occurrence — provider_id and both- // identity_data keys — must be the lowercased email, and the mixed-case- // form must never reach the parameters.- const { db, captured } = makeCapturingDb({ numAffectedRows: 1n });- await seedSsoIdentityForUser(db, {- userId: "u1",- email: "[email protected]",- providerId: "prov-1"- });- const { parameters } = captured[0]!;- const lower = "[email protected]";- // provider_id + jsonb 'sub' + jsonb 'email' = three lowercased copies- expect(parameters.filter((p) => p === lower)).toHaveLength(3);- expect(- parameters.some((p) => typeof p === "string" && p !== p.toLowerCase())- ).toBe(false);- });+ it.each([+ [1n, true],+ [0n, false]+ ])(+ "seedSsoIdentityForUser reports %s affected rows as seeded: %s",+ async (numAffectedRows, seeded) => {+ await expect(+ seedSsoIdentityForUser(fakeDb({ numAffectedRows }), seed)+ ).resolves.toEqual({+ data: { seeded },+ error: null+ });+ }+ );- it("backfillSsoIdentitiesForDomain selects on-domain non-SSO users and returns their ids", async () => {- const { db, captured } = makeCapturingDb({- rows: [{ user_id: "u1" }, { user_id: "u2" }]- });- const result = await backfillSsoIdentitiesForDomain(db, {- providerId: "prov-1",- domain: "Acme.com"+ it("backfillSsoIdentitiesForDomain returns the linked user ids", async () => {+ const db = fakeDb({ rows: [{ user_id: "u1" }, { user_id: "u2" }] });+ await expect(backfillSsoIdentitiesForDomain(db, domain)).resolves.toEqual({+ data: { linkedUserIds: ["u1", "u2"] },+ error: null});-- expect(result.error).toBeNull();- expect(result.data).toEqual({ linkedUserIds: ["u1", "u2"] });-- const { sql, parameters } = captured[0]!;- expect(sql).toContain("INSERT INTO auth.identities");- expect(sql).toContain("FROM auth.users");- expect(sql).toContain("is_sso_user = false");- expect(sql).toContain("RETURNING user_id");- expect(parameters).toContain("acme.com"); // domain lowercased- expect(parameters).toContain("sso:prov-1");});- it("removeSsoIdentitiesForDomain deletes by provider + domain and counts affected rows", async () => {- const { db, captured } = makeCapturingDb({ numAffectedRows: 3n });- const result = await removeSsoIdentitiesForDomain(db, {- providerId: "prov-1",- domain: "ACME.com"- });-- expect(result.error).toBeNull();- expect(result.data).toEqual({ removed: 3 });-- const { sql, parameters } = captured[0]!;- expect(sql).toContain("DELETE FROM auth.identities");- expect(sql).toContain("split_part(email, '@', 2)");- expect(parameters).toContain("acme.com");- expect(parameters).toContain("sso:prov-1");+ it("removeSsoIdentitiesForDomain counts the removed rows", async () => {+ await expect(+ removeSsoIdentitiesForDomain(fakeDb({ numAffectedRows: 3n }), domain)+ ).resolves.toEqual({ data: { removed: 3 }, error: null });});- it("returns an error (never throws) when the auth-schema write fails", async () => {- const result = await seedSsoIdentityForUser(- makeThrowingDb("connection reset"),- {- userId: "u1",- email: "[email protected]",- providerId: "prov-1"- }- );- expect(result.data).toBeNull();- expect(result.error).toBe("connection reset");+ it("returns an error instead of throwing when the auth-schema write fails", async () => {+ await expect(+ seedSsoIdentityForUser(fakeDb(new Error("connection reset")), seed)+ ).resolves.toEqual({ data: null, error: "connection reset" });});});diff --git a/packages/ee/src/sync/topology.delegation.test.ts b/packages/ee/src/sync/topology.delegation.test.tsindex f605a237ab..6c6d3067ff 100644--- a/packages/ee/src/sync/topology.delegation.test.ts+++ b/packages/ee/src/sync/topology.delegation.test.ts@@ -9,15 +9,8 @@ import { RAMP_MODE_PROFILES } from "../ramp/lib/modes";import { applyLedgerDelegation } from "./delegation";import { buildIntegrationTopology } from "./topology";-/**- * End-to-end proof that a push-only spend install delegates AP — through the- * real descriptor resolver and the real POSTING_POLICY derivation, not a- * hand-built topology.- *- * Slice 2 built the derivation and left it dormant because nothing declared- * `ownsLedgerFamilies`. Push-only mode is what first declares it, so this is the- * first test that can observe the whole chain.- */+// The whole chain: a push-only Ramp install declares that it owns AP, the+// topology resolves it, and delegation turns AP posting off for Carbon.const DESCRIPTORS = [{integrationId: "rillet",@@ -58,58 +51,24 @@ describe("push-only delegates the AP ledger family", () => {it("hands AP to the spend platform and leaves AR with Carbon", () => {const { settings, syncConfig, delegated } = delegate("push-only");- expect(settings.families.ap).toBe("none");expect(delegated).toEqual([{ family: "ap", integrationId: "ramp" }]);-- // AR is untouched — Carbon still owns customer invoicing, and its payment- // sync-back must keep working while AP stops.+ expect(settings.families.ap).toBe("none");expect(settings.families.ar).toBe(resolvePostingSyncSettings({}).families.ar);-- // The backing entity moves WITH the family. Each half alone is wrong:- // families-only leaves the bill still pushing; entity-only parks a- // DOC_SYNC_DISABLED warning forever.expect(syncConfig.entities.bill.enabled).toBe(false);});- it("derives the backing entity from POSTING_POLICY, not a hard-coded 'bill'", () => {- const { syncConfig } = delegate("push-only");-- // `reimbursement` is also an AP-family document, so it must move too — that- // is only true if the derivation reads POSTING_POLICY.- expect(syncConfig.entities.reimbursement.enabled).toBe(false);- });-- it("does NOT disable payment", () => {- // `Payment` is a per-line family: disabling it wholesale would break the AR- // side, which push-only explicitly keeps.- const { syncConfig } = delegate("push-only");- expect(syncConfig.entities.payment.enabled).toBe(- DEFAULT_SYNC_CONFIG.entities.payment.enabled- );- });-- it("delegates nothing in provider mode", () => {- const { settings, syncConfig, delegated } = delegate("provider");-- expect(delegated).toEqual([]);- expect(settings.families.ap).toBe(- resolvePostingSyncSettings({}).families.ap- );- expect(syncConfig.entities.bill.enabled).toBe(- DEFAULT_SYNC_CONFIG.entities.bill.enabled- );- });+ it.each(["provider", undefined])(+ "delegates nothing when the stored mode is %s",+ (syncMode) => {+ const { settings, syncConfig, delegated } = delegate(syncMode);- it("treats an install with no stored mode as provider", () => {- // Every install that predates modes must be untouched.- expect(delegate(undefined).delegated).toEqual([]);- });-- it("marks the settings as delegation-applied", () => {- // The branded type is what stops a posting decision being made from raw- // settings — `getJournalPostingPolicyDecision` accepts only these.- expect(delegate("push-only").settings.ledgerDelegationApplied).toBe(true);- });+ expect(delegated).toEqual([]);+ expect(settings.families).toEqual(+ resolvePostingSyncSettings({}).families+ );+ expect(syncConfig.entities).toEqual(DEFAULT_SYNC_CONFIG.entities);+ }+ );});diff --git a/packages/ee/src/workflows/AGENTS.md b/packages/ee/src/workflows/AGENTS.mdindex dfa2070133..36764edc45 100644--- a/packages/ee/src/workflows/AGENTS.md+++ b/packages/ee/src/workflows/AGENTS.md@@ -330,7 +330,7 @@ event id still exists in the catalog.```bashpnpm --filter @carbon/ee test # vitest-pnpm --filter @carbon/ee exec tsgo --noEmit # typecheck+pnpm --filter @carbon/ee exec tsc --noEmit # typecheckpnpm exec biome check packages/ee/src/workflows # lintpnpm run generate:workflow-catalog # after editing entities/moments/actions/operations.tspnpm run check:workflow-catalog # the CI `catalog` jobdiff --git a/packages/ee/src/workflows/catalog/build.test.ts b/packages/ee/src/workflows/catalog/build.test.tsindex a3ccab1b52..498cfe734a 100644--- a/packages/ee/src/workflows/catalog/build.test.ts+++ b/packages/ee/src/workflows/catalog/build.test.ts@@ -109,17 +109,15 @@ describe("buildCatalog — record events", () => {const ids = Object.keys(built.events).filter((id) =>id.startsWith("order."));- expect(ids).toEqual(- expect.arrayContaining([- "order.created",- "order.deleted",- "order.status.changed",- "order.supplierId.changed",- "order.buyerId.changed"- ])- );- // 3 watched columns => 5 record events, plus the moment keyed "order.approved".- expect(ids).toHaveLength(6);+ // The moment keyed "order.approved" shares the prefix.+ expect(ids.sort()).toEqual([+ "order.approved",+ "order.buyerId.changed",+ "order.created",+ "order.deleted",+ "order.status.changed",+ "order.supplierId.changed"+ ]);});it("emits no generic updated event", () => {@@ -224,21 +222,12 @@ describe("buildCatalog — labels", () => {);});- it("passes a moment's hand-written label through unchanged", () => {- expect(built.labels["order.approved"]).toBe("An order is approved");- });-it("emits a label for every event", () => {for (const id of Object.keys(built.events)) {expect(built.labels[id]).toBeDefined();}});- it("emits an entity label for each registry entity", () => {- expect(built.labels["entity.order"]).toBe("Order");- expect(built.labels["entity.person"]).toBe("Person");- });-it("sentence-cases a hand-written column label", () => {// supplierId is in `watch` with label "supplier"expect(built.labels["entity.order.supplierId"]).toBe("Supplier");@@ -646,53 +635,46 @@ describe("validateCatalogInputs", () => {).toEqual([]);});- it("rejects a fixed set of values on a list of anything but text", () => {- const problems = multi({- type: { kind: "list", of: { kind: "primitive", of: "number" } },- required: false,- label: "channels",- choices: ["inApp"]- });- expect(problems).toHaveLength(1);- expect(problems[0]).toMatch(/is not a list of text/);- });-- it("rejects a default that is not one of a multi-select's values", () => {- const problems = multi({- type: LIST_OF_TEXT,- required: false,- label: "channels",- choices: ["inApp", "email"],- defaultValue: ["inApp", "carrier-pigeon"]- });- expect(problems).toHaveLength(1);- expect(problems[0]).toMatch(/"carrier-pigeon", which is not one/);- });-- it("rejects a single default on a multi-select", () => {- const problems = multi({- type: LIST_OF_TEXT,- required: false,- label: "channels",- choices: ["inApp", "email"],- defaultValue: "inApp"- });- expect(problems).toHaveLength(1);- expect(problems[0]).toMatch(/defaults to one value but holds a set/);- });-- it("rejects a set of defaults on an input that holds one value", () => {- const problems = multi({- type: { kind: "primitive", of: "string" },- required: false,- label: "channels",- choices: ["inApp", "email"],- defaultValue: ["inApp"]- });- expect(problems).toHaveLength(1);- expect(problems[0]).toMatch(+ it.each([+ [+ "a fixed set of values on a list of anything but text",+ {+ type: { kind: "list", of: { kind: "primitive", of: "number" } },+ choices: ["inApp"]+ },+ /is not a list of text/+ ],+ [+ "a default that is not one of a multi-select's values",+ {+ type: LIST_OF_TEXT,+ choices: ["inApp", "email"],+ defaultValue: ["inApp", "carrier-pigeon"]+ },+ /"carrier-pigeon", which is not one/+ ],+ [+ "a single default on a multi-select",+ {+ type: LIST_OF_TEXT,+ choices: ["inApp", "email"],+ defaultValue: "inApp"+ },+ /defaults to one value but holds a set/+ ],+ [+ "a set of defaults on an input that holds one value",+ {+ type: { kind: "primitive", of: "string" },+ choices: ["inApp", "email"],+ defaultValue: ["inApp"]+ },/defaults to a set of values but only holds one/- );+ ]+ ])("rejects %s", (_, input, problem) => {+ const problems = multi({ required: false, label: "channels", ...input });+ expect(problems).toHaveLength(1);+ expect(problems[0]).toMatch(problem);});const gated = (@@ -729,22 +711,31 @@ describe("validateCatalogInputs", () => {schema);- it("rejects a showWhen naming an input the action does not have", () => {- const problems = gated({ input: "verb", equals: ["POST"] }, ["POST"]);+ it.each<+ [string, { input: string; equals: string[] }, string[] | undefined, RegExp]+ >([+ [+ "naming an input the action does not have",+ { input: "verb", equals: ["POST"] },+ ["POST"],+ /not an input of "order.archive"/+ ],+ [+ "against an input with no fixed set of values",+ { input: "method", equals: ["POST"] },+ undefined,+ /has no fixed set of values/+ ],+ [+ "expecting a value the gating input cannot hold",+ { input: "method", equals: ["TRACE"] },+ ["POST"],+ /which is not one of its values/+ ]+ ])("rejects a showWhen %s", (_, showWhen, methodChoices, problem) => {+ const problems = gated(showWhen, methodChoices);expect(problems).toHaveLength(1);- expect(problems[0]).toMatch(/not an input of "order.archive"/);- });-- it("rejects a showWhen against an input with no fixed set of values", () => {- const problems = gated({ input: "method", equals: ["POST"] });- expect(problems).toHaveLength(1);- expect(problems[0]).toMatch(/has no fixed set of values/);- });-- it("rejects a showWhen expecting a value the gating input cannot hold", () => {- const problems = gated({ input: "method", equals: ["TRACE"] }, ["POST"]);- expect(problems).toHaveLength(1);- expect(problems[0]).toMatch(/which is not one of its values/);+ expect(problems[0]).toMatch(problem);});it("accepts a well-formed showWhen", () => {@@ -763,18 +754,13 @@ describe("buildCatalog — the real hand-written inputs", () => {{ definitions: realDefinitions() });- it("accepts the real registry, moments, actions and operations", () => {- expect(Object.keys(WORKFLOW_MOMENTS)).toHaveLength(9);- // 77 watched columns + 10 created + 10 deleted + 9 moments.- expect(Object.keys(built.events)).toHaveLength(106);- expect(Object.keys(built.entities)).toHaveLength(17);- // 10 generated `<entity>.update` plus the 6 hand-written.- expect(Object.keys(built.actions)).toHaveLength(16);- expect(Object.keys(built.operations)).toHaveLength(15);- // 106 events + 16 actions + 15 operations + 17 entity labels + 95 column labels- // + 28 action input labels + 15 operation input labels- // + 44 generated update-action input labels (10 record inputs + 34 writable columns)- expect(Object.keys(built.labels)).toHaveLength(336);+ it("labels every real event, action and operation", () => {+ const unlabelled = [+ ...Object.keys(built.events),+ ...Object.keys(built.actions),+ ...Object.keys(built.operations)+ ].filter((id) => !built.labels[id]);+ expect(unlabelled).toEqual([]);});it("sets template: true on inputs marked as templates", () => {@@ -787,21 +773,6 @@ describe("buildCatalog — the real hand-written inputs", () => {expect(built.actions.webhook?.inputs.url?.template).toBeUndefined();expect(built.actions.notify?.inputs.user?.template).toBeUndefined();});-- it("emits action input labels", () => {- expect(built.labels["action.notify.input.subject"]).toBe("Subject");- expect(built.labels["action.webhook.input.url"]).toBe("URL");- expect(built.labels["action.job.create.input.dueDate"]).toBe("Due date");- });-- it("emits operation input labels", () => {- expect(- built.labels["operation.purchaseOrder.total.input.purchaseOrder"]- ).toBe("Record");- expect(built.labels["operation.job.scrapPercentage.input.job"]).toBe(- "Record"- );- });});describe("buildCatalog — enums from real schema", () => {diff --git a/packages/ee/src/workflows/definition/schema.test.ts b/packages/ee/src/workflows/definition/schema.test.tsindex 157998d4fb..2430c76361 100644--- a/packages/ee/src/workflows/definition/schema.test.ts+++ b/packages/ee/src/workflows/definition/schema.test.ts@@ -6,169 +6,108 @@ import { describe, expect, it } from "vitest";import { getNodeHandles } from "./nodes";import {CURRENT_DEFINITION_FORMAT_VERSION,- edgeSchema,nodeSchema,workflowDefinitionSchema} from "./schema";import { scheduleSchema, valueTypeSchema, variableRefSchema } from "./types";-const triggerNode = {+const node = (+ type: string,+ data: Record<string, unknown> = {},+ overrides: Record<string, unknown> = {}+) => ({id: "n1",- name: "trigger_0",- type: "trigger",+ name: `${type}_0`,+ type,position: { x: 0, y: 0 },- data: { events: ["purchaseOrder.status.changed"] }-};+ data,+ ...overrides+});describe("workflowDefinitionSchema", () => {- it("parses a minimal definition", () => {+ it("stamps the current format version on a definition that has none", () => {const parsed = workflowDefinitionSchema.parse({- nodes: [triggerNode],+ nodes: [node("trigger")],edges: []});- expect(parsed.nodes).toHaveLength(1);expect(parsed.formatVersion).toBe(CURRENT_DEFINITION_FORMAT_VERSION);});- it("parses an empty canvas", () => {- const parsed = workflowDefinitionSchema.parse({ nodes: [], edges: [] });- expect(parsed.nodes).toEqual([]);- expect(parsed.edges).toEqual([]);- });-it("rejects an unknown node type", () => {- const result = workflowDefinitionSchema.safeParse({- nodes: [{ ...triggerNode, type: "teleport" }],- edges: []- });- expect(result.success).toBe(false);- });-- it("rejects a node with an empty id", () => {- const result = nodeSchema.safeParse({ ...triggerNode, id: "" });- expect(result.success).toBe(false);+ expect(+ workflowDefinitionSchema.safeParse({+ nodes: [node("teleport")],+ edges: []+ }).success+ ).toBe(false);});});-describe("node defaults", () => {+describe("nodeSchema", () => {it("defaults a trigger's events and origin", () => {- const parsed = nodeSchema.parse({- id: "n1",- name: "trigger_0",- type: "trigger",- position: { x: 0, y: 0 },- data: {}- });- expect(parsed.type).toBe("trigger");+ const parsed = nodeSchema.parse(node("trigger"));if (parsed.type !== "trigger") throw new Error("expected a trigger node");- expect(parsed.data.events).toEqual([]);- expect(parsed.data.origin).toBe("Both");+ expect(parsed.data).toMatchObject({ events: [], origin: "Both" });});- // Repeating used to be a stored flag, and rows written then still carry it. Reading- // one has to drop it rather than fail, or those workflows become unopenable.+ // Rows written when repeating was a stored flag still carry it; reading one+ // must drop it rather than fail, or those workflows become unopenable.it("drops the batch flag an older row still carries", () => {- const parsed = nodeSchema.parse({- id: "n2",- name: "action_0",- type: "action",- position: { x: 0, y: 0 },- data: { action: "notify", batch: true }- });- if (parsed.type !== "action") throw new Error("expected an action node");+ const parsed = nodeSchema.parse(+ node("action", { action: "notify", batch: true })+ );expect(parsed.data).toEqual({ action: "notify", inputs: {} });});- it("round-trips a node with a name", () => {- const parsed = nodeSchema.parse({- id: "n1",- name: "check_order",- type: "trigger",- position: { x: 0, y: 0 },- data: {}- });- expect(parsed.name).toBe("check_order");- });-it("rejects a name with uppercase letters", () => {- const result = nodeSchema.safeParse({- id: "n1",- name: "CheckOrder",- type: "trigger",- position: { x: 0, y: 0 },- data: {}- });- expect(result.success).toBe(false);- });-- it("rejects a node without a name", () => {- const result = nodeSchema.safeParse({- id: "n1",- type: "trigger",- position: { x: 0, y: 0 },- data: {}- });- expect(result.success).toBe(false);+ expect(+ nodeSchema.safeParse(node("trigger", {}, { name: "CheckOrder" })).success+ ).toBe(false);});it("defaults a variable reference's property path to empty", () => {- const parsed = variableRefSchema.parse({- kind: "ref",- nodeId: "n1",- output: "result"- });- expect(parsed.path).toEqual([]);+ expect(+ variableRefSchema.parse({ kind: "ref", nodeId: "n1", output: "result" })+ .path+ ).toEqual([]);});});describe("getNodeHandles", () => {- it("gives an action success and failure handles", () => {- const node = nodeSchema.parse({- id: "n2",- name: "action_0",- type: "action",- position: { x: 0, y: 0 },- data: { action: "notify" }- });- expect(getNodeHandles(node)).toEqual(["success", "failure"]);- });-- it("gives a condition one handle per path", () => {- const node = nodeSchema.parse({- id: "n3",- name: "condition_0",- type: "condition",- position: { x: 0, y: 0 },- data: {+ it.each([+ [+ "an action success and failure",+ node("action", { action: "notify" }),+ ["success", "failure"]+ ],+ [+ "a condition one handle per path",+ node("condition", {paths: [{ id: "p1", kind: "if" },{ id: "p2", kind: "else" }]- }- });- expect(getNodeHandles(node)).toEqual(["p1", "p2"]);- });-- it("gives a trigger a single default handle", () => {- expect(getNodeHandles(nodeSchema.parse(triggerNode))).toEqual(["out"]);+ }),+ ["p1", "p2"]+ ],+ ["a trigger a single default handle", node("trigger"), ["out"]]+ ])("gives %s", (_, raw, handles) => {+ expect(getNodeHandles(nodeSchema.parse(raw))).toEqual(handles);});});describe("valueTypeSchema", () => {- it("accepts a list of entities", () => {- const parsed = valueTypeSchema.parse({- kind: "list",- of: { kind: "entity", of: "part" }- });- expect(parsed.kind).toBe("list");- });-- it("rejects a list of lists", () => {- const result = valueTypeSchema.safeParse({- kind: "list",- of: { kind: "list", of: { kind: "entity", of: "part" } }- });- expect(result.success).toBe(false);+ it("accepts a list of entities but not a list of lists", () => {+ const entity = { kind: "entity", of: "part" };+ expect(+ valueTypeSchema.safeParse({ kind: "list", of: entity }).success+ ).toBe(true);+ expect(+ valueTypeSchema.safeParse({+ kind: "list",+ of: { kind: "list", of: entity }+ }).success+ ).toBe(false);});});@@ -183,48 +122,4 @@ describe("scheduleSchema", () => {});expect(parsed.day).toBe("last");});-- it("rejects an out-of-range hour", () => {- const result = scheduleSchema.safeParse({- freq: "Daily",- hour: 24,- minute: 0,- tz: "America/Chicago"- });- expect(result.success).toBe(false);- });-- it("rejects a weekday outside 0-6", () => {- const result = scheduleSchema.safeParse({- freq: "Weekly",- hour: 9,- minute: 0,- weekdays: [7],- tz: "America/Chicago"- });- expect(result.success).toBe(false);- });-});--describe("edgeSchema", () => {- it("requires a source handle", () => {- const result = edgeSchema.safeParse({- id: "e1",- source: "n1",- target: "n2",- targetHandle: "in"- });- expect(result.success).toBe(false);- });-- it("parses a complete edge", () => {- const parsed = edgeSchema.parse({- id: "e1",- source: "n1",- sourceHandle: "out",- target: "n2",- targetHandle: "in"- });- expect(parsed.source).toBe("n1");- });});diff --git a/packages/ee/src/workflows/definition/validate.test.ts b/packages/ee/src/workflows/definition/validate.test.tsindex c555165876..4982768967 100644--- a/packages/ee/src/workflows/definition/validate.test.ts+++ b/packages/ee/src/workflows/definition/validate.test.ts@@ -3,8 +3,7 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.import { describe, expect, it } from "vitest";-import { createFixtureCatalog } from "./catalog";-import type { WorkflowIssueCode } from "./issues";+import { createFixtureCatalog, type WorkflowCatalog } from "./catalog";import { NODE_KINDS } from "./nodes";import {nodeSchema,@@ -19,26 +18,77 @@ function define(nodes: unknown[], edges: unknown[] = []): WorkflowDefinition {return workflowDefinitionSchema.parse({ nodes, edges });}-function codes(definition: WorkflowDefinition): WorkflowIssueCode[] {- return validateDefinition(definition, catalog).map((issue) => issue.code);-}+const codes = (definition: unknown, against: WorkflowCatalog = catalog) =>+ validateDefinition(definition, against).map((issue) => issue.code);-const trigger = (data: Record<string, unknown> = {}) => ({- id: "trigger",- name: "trigger",- type: "trigger",- position: { x: 0, y: 0 },- data: { events: ["purchaseOrder.status.changed"], ...data }-});+/** Code and field of every issue, for cases where the field is the point. */+const issuesAt = (definition: unknown, against: WorkflowCatalog = catalog) =>+ validateDefinition(definition, against).map(({ code, field }) => ({+ code,+ field+ }));++// --- node and value builders --------------------------------------------------const action = (id: string, data: Record<string, unknown> = {}) => ({+type Node = { id: string; type: string } & Record<string, unknown>;++const node = (type: string, id: string, data: Record<string, unknown>) => ({id,name: id,- type: "action",+ type,position: { x: 0, y: 0 },- data: { action: "createIssue", inputs: {}, ...data }+ data+});++const trigger = (data: Record<string, unknown> = {}) =>+ node("trigger", "trigger", {+ events: ["purchaseOrder.status.changed"],+ ...data+ });++const secondTrigger = (data: Record<string, unknown> = {}) =>+ node("trigger", "trigger2", {+ events: ["purchaseOrder.status.changed"],+ ...data+ });++const action = (id: string, data: Record<string, unknown> = {}) =>+ node("action", id, { action: "createIssue", inputs: {}, ...data });++const condition = (id: string, paths: unknown[]) =>+ node("condition", id, { paths });++const lookup = (+ id: string,+ entity: string,+ returns: "one" | "list",+ match: unknown[] = []+) => node("lookup", id, { entity, returns, match });++const filter = (id: string, data: Record<string, unknown>) =>+ node("filter", id, data);++const ifPath = (id: string, clauses: unknown[]) => ({+ id,+ kind: "if",+ clauses+});++const ref = (nodeId: string, output: string, path: string[] = []) => ({+ kind: "ref" as const,+ nodeId,+ output,+ path});+const literal = (of: string, value: unknown) => ({+ kind: "literal" as const,+ type: { kind: "primitive" as const, of },+ value+});++const item = (path: string[] = []) => ({ kind: "item" as const, path });+const edge = (id: string,source: string,@@ -46,24 +96,79 @@ const edge = (target: string) => ({ id, source, sourceHandle, target, targetHandle: "in" });+const EXIT_HANDLE: Record<string, string> = {+ trigger: "out",+ compute: "out",+ filter: "out",+ lookup: "success",+ action: "success"+};++/** The trigger, then each step wired to the next on its default exit. */+function wired(...steps: Node[]): WorkflowDefinition {+ const chain: Node[] = [trigger(), ...steps];+ return define(+ chain,+ steps.map((step, i) => {+ const from = chain[i] as Node;+ return edge(+ `e${i + 1}`,+ from.id,+ EXIT_HANDLE[from.type] ?? "out",+ step.id+ );+ })+ );+}++/** "When a purchase order over $10,000 is sent, tell the buyer's manager." */+function purchaseOrderWorkflow(+ overClause: Record<string, unknown> = {+ left: ref("trigger", "purchaseOrder", ["amount"]),+ operator: "gt",+ right: literal("number", 10000)+ }+): WorkflowDefinition {+ return define(+ [+ trigger(),+ condition("check", [+ { id: "over", kind: "if", combinator: "and", clauses: [overClause] },+ { id: "otherwise", kind: "else", combinator: "and", clauses: [] }+ ]),+ action("notify", {+ action: "notify",+ inputs: {+ recipient: ref("trigger", "purchaseOrder", ["assignee", "manager"]),+ message: literal("string", "This order is over $10,000.")+ }+ })+ ],+ [+ edge("e1", "trigger", "out", "check"),+ edge("e2", "check", "over", "notify")+ ]+ );+}++// --- tests --------------------------------------------------------------------+describe("shape", () => {it("accepts a trigger-only workflow", () => {- expect(validateDefinition(define([trigger()]), catalog)).toEqual([]);+ expect(codes(define([trigger()]))).toEqual([]);});it("rejects two nodes sharing an id", () => {- const definition = define([trigger(), { ...trigger(), type: "trigger" }]);- expect(codes(definition)).toContain("MALFORMED_DEFINITION");+ expect(codes(define([trigger(), trigger()]))).toContain(+ "MALFORMED_DEFINITION"+ );});- it("reports DUPLICATE_NODE_NAME for two nodes with the same name", () => {+ it("reports DUPLICATE_NODE_NAME on both nodes sharing a name", () => {const definition = define([trigger(),- {- ...condition("cond_a", [{ id: "p1", kind: "if", clauses: [] }]),- name: "shared"- },+ { ...condition("cond_a", [ifPath("p1", [])]), name: "shared" },{ ...action("cond_b"), name: "shared" }],[@@ -71,8 +176,7 @@ describe("shape", () => {edge("e2", "trigger", "out", "cond_b")]);- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual([+ expect(codes(definition)).toEqual(["DUPLICATE_NODE_NAME","DUPLICATE_NODE_NAME"]);@@ -81,123 +185,133 @@ describe("shape", () => {it("does not report DUPLICATE_NODE_NAME when all names are unique", () => {const definition = define([trigger(),- condition("condition_0", [{ id: "p1", kind: "if", clauses: [] }]),- condition("condition_1", [{ id: "p2", kind: "if", clauses: [] }])+ condition("condition_0", [ifPath("p1", [])]),+ condition("condition_1", [ifPath("p2", [])])]);expect(codes(definition)).not.toContain("DUPLICATE_NODE_NAME");});++ it("declares a node kind for every node type in the schema", () => {+ const inSchema = nodeSchema.options+ .map((option) => option.shape.type.value)+ .sort();+ expect(Object.keys(NODE_KINDS).sort()).toEqual(inSchema);+ });++ it("validates a definition that has never been through the schema", () => {+ const found = codes({ nodes: "not a list" });+ expect(found.length).toBeGreaterThan(0);+ expect(found.every((code) => code === "MALFORMED_DEFINITION")).toBe(true);+ });++ // A definition that skipped the schema is parsed first; a bad value fails it.+ it.each([+ [+ "a literal whose value contradicts its declared type",+ action("a", {+ inputs: {+ title: {+ kind: "literal",+ type: { kind: "primitive", of: "string" },+ value: { not: "a string" }+ }+ }+ })+ ],+ [+ "an operator outside the shared vocabulary",+ condition("a", [+ ifPath("p1", [+ {+ left: ref("trigger", "purchaseOrder", ["status"]),+ operator: "banana",+ right: literal("string", "Sent")+ }+ ])+ ])+ ]+ ])("rejects %s as MALFORMED_DEFINITION", (_, step) => {+ const definition = {+ formatVersion: 1,+ nodes: [trigger(), step],+ edges: [edge("e1", "trigger", "out", "a")]+ };+ expect(codes(definition)).toEqual(["MALFORMED_DEFINITION"]);+ });++ it("accepts an unparsed literal whose value matches its declared type", () => {+ const definition = {+ formatVersion: 1,+ nodes: [+ trigger(),+ action("a", { inputs: { title: literal("string", "Look into this") } })+ ],+ edges: [edge("e1", "trigger", "out", "a")]+ };+ expect(codes(definition)).toEqual([]);+ });});describe("trigger", () => {+ const daily = { freq: "Daily", hour: 9, minute: 0, tz: "America/Chicago" };+it("reports NO_TRIGGER when nothing can start the workflow", () => {expect(codes(define([action("a1")]))).toEqual(["NO_TRIGGER"]);});it("accepts two triggers watching different events", () => {- const definition = define([- trigger(),- {- ...trigger(),- id: "trigger2",- name: "trigger2",- data: { events: ["part.created"] }- }- ]);- expect(codes(definition)).toEqual([]);+ expect(+ codes(define([trigger(), secondTrigger({ events: ["part.created"] })]))+ ).toEqual([]);});it("reports DUPLICATE_TRIGGER_EVENT when two triggers share an event", () => {- const definition = define([- trigger(),- { ...trigger(), id: "trigger2", name: "trigger2" }+ expect(codes(define([trigger(), secondTrigger()]))).toEqual([+ "DUPLICATE_TRIGGER_EVENT"]);- expect(codes(definition)).toEqual(["DUPLICATE_TRIGGER_EVENT"]);});it("reports CONFLICTING_TRIGGER for a schedule alongside another trigger", () => {- const definition = define([- trigger({- events: [],- schedule: { freq: "Daily", hour: 9, minute: 0, tz: "America/Chicago" }- }),- { ...trigger(), id: "trigger2", name: "trigger2" }+ expect(+ codes(define([trigger({ events: [], schedule: daily }), secondTrigger()]))+ ).toEqual(["CONFLICTING_TRIGGER"]);+ });++ it("reports CONFLICTING_TRIGGER for both events and a schedule", () => {+ expect(codes(define([trigger({ schedule: daily })]))).toEqual([+ "CONFLICTING_TRIGGER"]);- expect(codes(definition)).toEqual(["CONFLICTING_TRIGGER"]);});it("reports EMPTY_TRIGGER naming the unconfigured trigger of two", () => {- const definition = define([- trigger(),- { ...trigger(), id: "trigger2", name: "trigger2", data: { events: [] } }+ const issues = validateDefinition(+ define([trigger(), secondTrigger({ events: [] })]),+ catalog+ );+ expect(issues.map(({ code, nodeId }) => ({ code, nodeId }))).toEqual([+ { code: "EMPTY_TRIGGER", nodeId: "trigger2" }]);- const issues = validateDefinition(definition, catalog);- expect(issues.map((issue) => issue.code)).toEqual(["EMPTY_TRIGGER"]);- expect(issues[0]?.nodeId).toBe("trigger2");});it("reports EMPTY_TRIGGER for neither events nor a schedule", () => {expect(codes(define([trigger({ events: [] })]))).toEqual(["EMPTY_TRIGGER"]);});- it("reports CONFLICTING_TRIGGER for both events and a schedule", () => {- const definition = define([- trigger({- schedule: { freq: "Daily", hour: 9, minute: 0, tz: "America/Chicago" }- })- ]);- expect(codes(definition)).toEqual(["CONFLICTING_TRIGGER"]);- });-it("accepts a well-formed schedule", () => {- const definition = define([- trigger({- events: [],- schedule: { freq: "Daily", hour: 9, minute: 0, tz: "America/Chicago" }- })- ]);- expect(validateDefinition(definition, catalog)).toEqual([]);- });-- it("reports INVALID_SCHEDULE for a weekly schedule with no weekdays", () => {- const definition = define([- trigger({- events: [],- schedule: { freq: "Weekly", hour: 9, minute: 0, tz: "America/Chicago" }- })- ]);- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["INVALID_SCHEDULE"]);- expect(issues[0]?.field).toBe("weekdays");- });-- it("reports INVALID_SCHEDULE for a daily schedule carrying a day", () => {- const definition = define([- trigger({- events: [],- schedule: {- freq: "Daily",- hour: 9,- minute: 0,- day: 5,- tz: "America/Chicago"- }- })- ]);- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["INVALID_SCHEDULE"]);- expect(issues[0]?.field).toBe("day");+ expect(codes(define([trigger({ events: [], schedule: daily })]))).toEqual(+ []+ );});- it("reports INVALID_SCHEDULE for an unrecognised time zone", () => {+ it.each([+ ["a weekly schedule with no weekdays", { freq: "Weekly" }, "weekdays"],+ ["a daily schedule carrying a day", { day: 5 }, "day"],+ ["an unrecognised time zone", { tz: "Mars/Olympus" }, "tz"]+ ])("reports INVALID_SCHEDULE for %s", (_, schedule, field) => {const definition = define([- trigger({- events: [],- schedule: { freq: "Daily", hour: 9, minute: 0, tz: "Mars/Olympus" }- })+ trigger({ events: [], schedule: { ...daily, ...schedule } })]);- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["INVALID_SCHEDULE"]);- expect(issues[0]?.field).toBe("tz");+ expect(issuesAt(definition)).toEqual([{ code: "INVALID_SCHEDULE", field }]);});});@@ -208,25 +322,20 @@ describe("edges", () => {[edge("e1", "trigger", "out", "ghost")]);const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["DANGLING_EDGE"]);- expect(issues[0]?.edgeId).toBe("e1");+ expect(issues.map(({ code, edgeId }) => ({ code, edgeId }))).toEqual([+ { code: "DANGLING_EDGE", edgeId: "e1" }+ ]);});it("reports UNKNOWN_HANDLE for a condition path the node does not declare", () => {- const condition = {- id: "c1",- name: "c1",- type: "condition",- position: { x: 0, y: 0 },- data: { paths: [{ id: "p1", kind: "if", clauses: [] }] }- };const definition = define(- [trigger(), condition, action("a1")],+ [trigger(), condition("c1", [ifPath("p1", [])]), action("a1")],[edge("e1", "trigger", "out", "c1"), edge("e2", "c1", "p2", "a1")]);const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["UNKNOWN_HANDLE"]);- expect(issues[0]?.edgeId).toBe("e2");+ expect(issues.map(({ code, edgeId }) => ({ code, edgeId }))).toEqual([+ { code: "UNKNOWN_HANDLE", edgeId: "e2" }+ ]);});it("accepts an action's failure handle", () => {@@ -234,32 +343,43 @@ describe("edges", () => {[trigger(), action("a1"), action("a2")],[edge("e1", "trigger", "out", "a1"), edge("e2", "a1", "failure", "a2")]);- expect(- validateDefinition(definition, catalog).map((i) => i.code)- ).not.toContain("UNKNOWN_HANDLE");+ expect(codes(definition)).not.toContain("UNKNOWN_HANDLE");});});describe("graph", () => {- it("reports CYCLE when steps loop back on each other", () => {- const definition = define(- [trigger(), action("a1"), action("a2")],+ const cycle = (a1: Node) =>+ define(+ [trigger(), a1, action("a2")],[edge("e1", "trigger", "out", "a1"),edge("e2", "a1", "success", "a2"),edge("e3", "a2", "success", "a1")]);++ it("reports CYCLE when steps loop back on each other", () => {+ expect(codes(cycle(action("a1")))).toEqual(["CYCLE"]);+ });++ it("referenceIssues reports a broken variable a cycle would hide", () => {+ // `validateDefinition` stops at the cycle and never looks at values.+ const definition = cycle(+ action("a1", { inputs: { title: ref("ghost", "result") } })+ );expect(codes(definition)).toEqual(["CYCLE"]);+ expect(referenceIssues(definition, catalog).map((i) => i.code)).toEqual([+ "UNKNOWN_VARIABLE"+ ]);+ });++ it("referenceIssues says nothing about a definition it cannot read", () => {+ expect(referenceIssues({ nodes: "not a list" }, catalog)).toEqual([]);});- // A step parked on the canvas is not part of the workflow — the engine never runs it.+ // A step parked on the canvas is not part of the workflow; the engine never runs it.it("ignores a step with no path from the trigger, however broken", () => {- const definition = define([- trigger(),- action("a1", { action: "createIssue", inputs: {} })- ]);- expect(validateDefinition(definition, catalog)).toEqual([]);+ expect(codes(define([trigger(), action("a1")]))).toEqual([]);});it("accepts a fan-out of two actions off one handle", () => {@@ -272,179 +392,64 @@ describe("graph", () => {it("does not call a node unreachable when a second trigger feeds it", () => {const definition = define(- [- trigger(),- {- ...trigger(),- id: "trigger2",- name: "trigger2",- data: { events: ["part.created"] }- },- action("a1")- ],+ [trigger(), secondTrigger({ events: ["part.created"] }), action("a1")],[edge("e1", "trigger2", "out", "a1")]);expect(codes(definition)).not.toContain("UNREACHABLE_NODE");});});-const ref = (nodeId: string, output: string, path: string[] = []) => ({- kind: "ref" as const,- nodeId,- output,- path-});--const literal = (of: string, value: unknown) => ({- kind: "literal" as const,- type: { kind: "primitive" as const, of },- value-});--const condition = (id: string, paths: unknown[]) => ({- id,- name: id,- type: "condition",- position: { x: 0, y: 0 },- data: { paths }-});--const lookup = (id: string, entity: string, returns: "one" | "list") => ({- id,- name: id,- type: "lookup",- position: { x: 0, y: 0 },- data: { entity, returns, match: [] }-});--/** "When a purchase order over $10,000 is sent, tell the buyer's manager." */-function purchaseOrderWorkflow(): WorkflowDefinition {- return define(- [- trigger(),- condition("check", [- {- id: "over",- kind: "if",- combinator: "and",- clauses: [- {- left: ref("trigger", "purchaseOrder", ["amount"]),- operator: "gt",- right: literal("number", 10000)- }- ]- },- { id: "otherwise", kind: "else", combinator: "and", clauses: [] }- ]),- action("notify", {- action: "notify",- inputs: {- recipient: ref("trigger", "purchaseOrder", ["assignee", "manager"]),- message: literal("string", "This order is over $10,000.")- }- })- ],- [- edge("e1", "trigger", "out", "check"),- edge("e2", "check", "over", "notify")- ]- );-}-describe("references", () => {it("accepts a property path through two entities", () => {- expect(validateDefinition(purchaseOrderWorkflow(), catalog)).toEqual([]);+ expect(codes(purchaseOrderWorkflow())).toEqual([]);});- it("reports UNKNOWN_VARIABLE for a step that does not exist", () => {- const definition = define(- [- trigger(),- action("a1", {- action: "createIssue",- inputs: { title: ref("ghost", "result") }- })- ],- [edge("e1", "trigger", "out", "a1")]- );- expect(codes(definition)).toEqual(["UNKNOWN_VARIABLE"]);+ it.each([+ ["a step that does not exist", ref("ghost", "result")],+ [+ "a property the record does not have",+ ref("trigger", "purchaseOrder", ["nickname"])+ ],+ ["an output the step no longer hands out", ref("trigger", "salesOrder")]+ ])("reports UNKNOWN_VARIABLE for %s", (_, title) => {+ expect(codes(wired(action("a1", { inputs: { title } })))).toEqual([+ "UNKNOWN_VARIABLE"+ ]);});- it("reports UNKNOWN_VARIABLE for a property the record does not have", () => {+ it("reports REF_NOT_UPSTREAM across two branches of a condition", () => {const definition = define([trigger(),- action("a1", {- action: "createIssue",- inputs: { title: ref("trigger", "purchaseOrder", ["nickname"]) }+ condition("check", [+ ifPath("yes", []),+ { id: "no", kind: "else", clauses: [] }+ ]),+ lookup("on_if", "part", "one"),+ action("on_else", {+ action: "updatePart",+ inputs: { part: ref("on_if", "result") }})],- [edge("e1", "trigger", "out", "a1")]- );- expect(codes(definition)).toEqual(["UNKNOWN_VARIABLE"]);- });-- it("referenceIssues reports a broken variable the layers above would hide", () => {- // A cycle, so `validateDefinition` stops at layer 4 and never looks at values.- const definition = define(- [- trigger(),- action("a1", {- action: "createIssue",- inputs: { title: ref("ghost", "result") }- }),- action("a2")- ],[- edge("e1", "trigger", "out", "a1"),- edge("e2", "a1", "success", "a2"),- edge("e3", "a2", "success", "a1")+ edge("e1", "trigger", "out", "check"),+ edge("e2", "check", "yes", "on_if"),+ edge("e3", "check", "no", "on_else")]);- expect(codes(definition)).toEqual(["CYCLE"]);- expect(referenceIssues(definition, catalog).map((i) => i.code)).toEqual([- "UNKNOWN_VARIABLE"- ]);+ expect(codes(definition)).toEqual(["REF_NOT_UPSTREAM"]);});- it("referenceIssues says nothing about a definition it cannot read", () => {- expect(referenceIssues({ nodes: "not a list" }, catalog)).toEqual([]);- });-- it("reports UNKNOWN_VARIABLE for an output the step no longer hands out", () => {- const definition = define(- [- trigger(),- action("a1", {- action: "createIssue",- inputs: { title: ref("trigger", "salesOrder") }- })- ],- [edge("e1", "trigger", "out", "a1")]- );- expect(codes(definition)).toEqual(["UNKNOWN_VARIABLE"]);+ it("rejects a filter whose source is its own output", () => {+ expect(+ codes(wired(filter("f", { source: ref("f", "result"), clauses: [] })))+ ).toEqual(["REF_NOT_UPSTREAM"]);});- it("reports REF_NOT_UPSTREAM across two branches of a condition", () => {- const definition = define(- [- trigger(),- condition("check", [- { id: "yes", kind: "if", clauses: [] },- { id: "no", kind: "else", clauses: [] }- ]),- lookup("on_if", "part", "one"),- action("on_else", {- action: "updatePart",- inputs: { part: ref("on_if", "result") }- })- ],- [- edge("e1", "trigger", "out", "check"),- edge("e2", "check", "yes", "on_if"),- edge("e3", "check", "no", "on_else")- ]+ it("rejects two filters that read each other", () => {+ const definition = wired(+ filter("f1", { source: ref("f2", "result"), clauses: [] }),+ filter("f2", { source: ref("f1", "result"), clauses: [] }));expect(codes(definition)).toEqual(["REF_NOT_UPSTREAM"]);});@@ -452,1093 +457,495 @@ describe("references", () => {describe("types", () => {it("reports MISSING_INPUT when a required input has no value", () => {- const definition = define(- [trigger(), action("a1", { action: "createIssue", inputs: {} })],- [edge("e1", "trigger", "out", "a1")]- );- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["MISSING_INPUT"]);- expect(issues[0]?.field).toBe("title");- });-- it("reports TYPE_MISMATCH for a string supplied to a number input", () => {- const definition = define(- [- trigger(),- action("a1", {- action: "updatePart",- inputs: {- part: ref("trigger", "purchaseOrder"),- name: literal("number", 12)- }- })- ],- [edge("e1", "trigger", "out", "a1")]- );- const codesFound = codes(definition);- expect(codesFound).toContain("TYPE_MISMATCH");- });-- // A whole record reads as its readable id, which is what "…for PO000123" means, and- // is what a notification body turns into a link. A LIST of records still does not.- it("accepts a record written into a sentence", () => {- const definition = define(- [- trigger(),- action("a1", {- action: "createIssue",- inputs: {- title: {- kind: "template",- parts: [- { kind: "text", text: "Check " },- ref("trigger", "purchaseOrder")- ]- }- }- })- ],- [edge("e1", "trigger", "out", "a1")]- );- expect(validateDefinition(definition, catalog)).toEqual([]);+ expect(issuesAt(wired(action("a1")))).toEqual([+ { code: "MISSING_INPUT", field: "title" }+ ]);});- it("accepts a property of that record in the same sentence", () => {- const definition = define(- [- trigger(),- action("a1", {- action: "createIssue",- inputs: {- title: {- kind: "template",- parts: [- { kind: "text", text: "Check " },- ref("trigger", "purchaseOrder", ["status"])- ]- }- }- })- ],- [edge("e1", "trigger", "out", "a1")]+ it("reports TYPE_MISMATCH for a number supplied to a text input", () => {+ const definition = wired(+ action("a1", {+ action: "updatePart",+ inputs: {+ part: ref("trigger", "purchaseOrder"),+ name: literal("number", 12)+ }+ }));- expect(validateDefinition(definition, catalog)).toEqual([]);+ expect(issuesAt(definition)).toContainEqual({+ code: "TYPE_MISMATCH",+ field: "name"+ });});- it("reports TYPE_MISMATCH for an operator that does not fit the type", () => {- const definition = define(- [- trigger(),- condition("check", [- {- id: "p1",- kind: "if",- clauses: [- {- left: ref("trigger", "purchaseOrder", ["status"]),- operator: "gt",- right: literal("string", "Sent")- }- ]- }- ])- ],- [edge("e1", "trigger", "out", "check")]- );- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["TYPE_MISMATCH"]);- expect(issues[0]?.field).toBe("paths.p1.clauses.0.operator");+ // A whole record reads as its readable id ("…for PO000123"), which a+ // notification body turns into a link. A LIST of records still does not.+ it.each([+ ["a record", []],+ ["a property of that record", ["status"]]+ ])("accepts %s written into a sentence", (_, path) => {+ const title = {+ kind: "template",+ parts: [+ { kind: "text", text: "Check " },+ ref("trigger", "purchaseOrder", path)+ ]+ };+ expect(codes(wired(action("a1", { inputs: { title } })))).toEqual([]);});- it("reports TYPE_MISMATCH when the two sides of a clause differ", () => {- const definition = define(- [- trigger(),- condition("check", [- {- id: "p1",- kind: "if",- clauses: [- {- left: ref("trigger", "purchaseOrder", ["amount"]),- operator: "gt",- right: literal("string", "lots")- }- ]- }+ it.each([+ [+ "an operator that does not fit the type",+ ["status"],+ literal("string", "Sent"),+ "paths.p1.clauses.0.operator"+ ],+ [+ "two sides of a clause that differ",+ ["amount"],+ literal("string", "lots"),+ "paths.p1.clauses.0.right"+ ]+ ])("reports TYPE_MISMATCH for %s", (_, path, right, field) => {+ const definition = wired(+ condition("check", [+ ifPath("p1", [+ { left: ref("trigger", "purchaseOrder", path), operator: "gt", right }])- ],- [edge("e1", "trigger", "out", "check")]+ ]));- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["TYPE_MISMATCH"]);- expect(issues[0]?.field).toBe("paths.p1.clauses.0.right");+ expect(issuesAt(definition)).toEqual([{ code: "TYPE_MISMATCH", field }]);});- function listIntoSingle(- actionId: string,- inputName: string- ): WorkflowDefinition {- return define(- [- trigger(),- lookup("find", "part", "list"),- action("a1", {- action: actionId,- inputs: { [inputName]: ref("find", "result") }- })- ],- [- edge("e1", "trigger", "out", "find"),- edge("e2", "find", "success", "a1")- ]+ const listInto = (actionId: string, inputName: string) =>+ wired(+ lookup("find", "part", "list"),+ action("a1", {+ action: actionId,+ inputs: { [inputName]: ref("find", "result") }+ }));- }it("reports LIST_INTO_SINGLE when a list feeds a step that cannot repeat", () => {- const issues = validateDefinition(- listIntoSingle("createIssue", "title"),- catalog- );- expect(issues.map((i) => i.code)).toEqual(["LIST_INTO_SINGLE"]);- expect(issues[0]?.field).toBe("title");+ expect(issuesAt(listInto("createIssue", "title"))).toEqual([+ { code: "LIST_INTO_SINGLE", field: "title" }+ ]);});it("accepts the same wiring when the action can repeat", () => {- expect(- validateDefinition(listIntoSingle("updatePart", "part"), catalog)- ).toEqual([]);+ expect(codes(listInto("updatePart", "part"))).toEqual([]);});- it("reports INCOMPLETE_CONFIG when two lists leave the repeat ambiguous", () => {- const definition = define(- [- trigger(),- lookup("parts", "part", "list"),- lookup("users", "user", "list"),- action("a1", {- action: "assignPart",- inputs: {- part: ref("parts", "result"),- user: ref("users", "result")- }- })- ],- [- edge("e1", "trigger", "out", "parts"),- edge("e2", "parts", "success", "users"),- edge("e3", "users", "success", "a1")- ]+ it("accepts a step fed one record, with nothing to repeat", () => {+ const definition = wired(+ lookup("find", "part", "one"),+ action("a1", {+ action: "updatePart",+ inputs: { part: ref("find", "result") }+ }));- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["INCOMPLETE_CONFIG"]);- // Blamed on the second list; neither list is also rejected on its own.- expect(issues[0]?.field).toBe("user");+ expect(codes(definition)).toEqual([]);+ });++ it("reports INCOMPLETE_CONFIG on the second list when two leave the repeat ambiguous", () => {+ const definition = wired(+ lookup("parts", "part", "list"),+ lookup("users", "user", "list"),+ action("a1", {+ action: "assignPart",+ inputs: { part: ref("parts", "result"), user: ref("users", "result") }+ })+ );+ // Neither list is also rejected on its own.+ expect(issuesAt(definition)).toEqual([+ { code: "INCOMPLETE_CONFIG", field: "user" }+ ]);});it("reports TYPE_MISMATCH when a filter's source is not a list", () => {- const definition = define(- [- trigger(),- lookup("find", "part", "one"),- {- id: "f1",- name: "f1",- type: "filter",- position: { x: 0, y: 0 },- data: { source: ref("find", "result"), clauses: [] }- }- ],- [- edge("e1", "trigger", "out", "find"),- edge("e2", "find", "success", "f1")- ]+ const definition = wired(+ lookup("find", "part", "one"),+ filter("f1", { source: ref("find", "result"), clauses: [] }));- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["TYPE_MISMATCH"]);- expect(issues[0]?.field).toBe("source");+ expect(issuesAt(definition)).toEqual([+ { code: "TYPE_MISMATCH", field: "source" }+ ]);});});describe("configuration", () => {it("reports UNKNOWN_EVENT for an event the catalog does not know", () => {- const definition = define([trigger({ events: ["part.exploded"] })]);- expect(codes(definition)).toEqual(["UNKNOWN_EVENT"]);+ expect(codes(define([trigger({ events: ["part.exploded"] })]))).toEqual([+ "UNKNOWN_EVENT"+ ]);});it("reports UNKNOWN_OPERATION for an operation the catalog does not know", () => {- const definition = define(- [- trigger(),- {- id: "e1",- name: "e1",- type: "compute",- position: { x: 0, y: 0 },- data: { operation: "job.vibes", inputs: {} }- }- ],- [edge("x1", "trigger", "out", "e1")]- );- expect(codes(definition)).toEqual(["UNKNOWN_OPERATION"]);+ expect(+ codes(+ wired(node("compute", "c1", { operation: "job.vibes", inputs: {} }))+ )+ ).toEqual(["UNKNOWN_OPERATION"]);});it("reports UNKNOWN_ENTITY for a record type the catalog does not know", () => {- const definition = define(- [trigger(), lookup("l1", "unicorn", "one")],- [edge("e1", "trigger", "out", "l1")]- );- expect(codes(definition)).toEqual(["UNKNOWN_ENTITY"]);+ expect(codes(wired(lookup("l1", "unicorn", "one")))).toEqual([+ "UNKNOWN_ENTITY"+ ]);});- it("reports UNKNOWN_INPUT for a lookup matching on a property the record has not got", () => {- const definition = define(- [- trigger(),- {- ...lookup("l1", "part", "one"),- data: {- entity: "part",- returns: "one",- match: [- {- field: "colour",- operator: "eq",- value: literal("string", "red")- }- ]- }- }- ],- [edge("e1", "trigger", "out", "l1")]- );- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["UNKNOWN_INPUT"]);- expect(issues[0]?.field).toBe("match.0.field");+ it.each([+ [+ "UNKNOWN_INPUT",+ "a property the record has not got",+ { field: "colour", operator: "eq", value: literal("string", "red") },+ "match.0.field"+ ],+ [+ "TYPE_MISMATCH",+ "a property against the wrong type",+ { field: "name", operator: "eq", value: literal("number", 7) },+ "match.0.value"+ ]+ ])("reports %s for a lookup matching on %s", (code, _, match, field) => {+ expect(issuesAt(wired(lookup("l1", "part", "one", [match])))).toEqual([+ { code, field }+ ]);});- it("reports TYPE_MISMATCH for a lookup comparing a property against the wrong type", () => {- const definition = define(- [- trigger(),- {- ...lookup("l1", "part", "one"),- data: {- entity: "part",- returns: "one",- match: [- { field: "name", operator: "eq", value: literal("number", 7) }- ]- }- }- ],- [edge("e1", "trigger", "out", "l1")]- );- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["TYPE_MISMATCH"]);- expect(issues[0]?.field).toBe("match.0.value");+ it("accepts a lookup matching a real property at a matching type", () => {+ const match = {+ field: "name",+ operator: "eq",+ value: literal("string", "Bolt")+ };+ expect(codes(wired(lookup("l1", "part", "one", [match])))).toEqual([]);});- it("accepts a lookup matching a real property at a matching type", () => {- const definition = define(- [- trigger(),- {- ...lookup("l1", "part", "one"),- data: {- entity: "part",- returns: "one",- match: [- {- field: "name",- operator: "eq",- value: literal("string", "Bolt")- }- ]- }- }- ],- [edge("e1", "trigger", "out", "l1")]- );- expect(validateDefinition(definition, catalog)).toEqual([]);+ it("does not check a lookup's enum match when the catalog carries no enums", () => {+ const match = {+ field: "status",+ operator: "eq",+ value: literal("string", "InvalidStatus")+ };+ const definition = wired(lookup("l1", "purchaseOrder", "one", [match]));+ expect(+ codes(definition, createFixtureCatalog({ omitEnums: true }))+ ).not.toContain("INCOMPLETE_CONFIG");});it("reports UNKNOWN_INPUT for an input the catalog does not declare", () => {- const definition = define(- [- trigger(),- action("a1", {- action: "createIssue",- inputs: {- title: literal("string", "Something went wrong"),- severity: literal("string", "high")- }- })- ],- [edge("e1", "trigger", "out", "a1")]+ const definition = wired(+ action("a1", {+ inputs: {+ title: literal("string", "Something went wrong"),+ severity: literal("string", "high")+ }+ }));- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["UNKNOWN_INPUT"]);- expect(issues[0]?.field).toBe("severity");+ expect(issuesAt(definition)).toEqual([+ { code: "UNKNOWN_INPUT", field: "severity" }+ ]);});it("reports INCOMPLETE_CONFIG when no input from a required group is supplied", () => {- const definition = define(- [trigger(), action("a1", { action: "alertSomeone", inputs: {} })],- [edge("e1", "trigger", "out", "a1")]- );- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["INCOMPLETE_CONFIG"]);- expect(issues[0]?.message).toBe(- "This step needs at least one of: user, role."+ const issues = validateDefinition(+ wired(action("a1", { action: "alertSomeone" })),+ catalog);+ expect(issues.map(({ code, message }) => ({ code, message }))).toEqual([+ {+ code: "INCOMPLETE_CONFIG",+ message: "This step needs at least one of: user, role."+ }+ ]);});- it("accepts a required group when one of its inputs is supplied", () => {- const definition = define(- [- trigger(),- action("a1", {- action: "alertSomeone",- inputs: { role: literal("string", "Buyer") }- })- ],- [edge("e1", "trigger", "out", "a1")]- );- expect(validateDefinition(definition, catalog)).toEqual([]);+ const alert = (inputs: Record<string, unknown>) =>+ wired(action("a1", { action: "alertSomeone", inputs }));++ const channels = (value: string[]) => ({+ kind: "literal",+ type: { kind: "list", of: { kind: "primitive", of: "string" } },+ value});- it("reports INCOMPLETE_CONFIG for an action with nothing chosen", () => {- const definition = define(- [trigger(), action("a1", { action: "" })],- [edge("e1", "trigger", "out", "a1")]- );- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["INCOMPLETE_CONFIG"]);- expect(issues[0]?.field).toBe("action");+ it.each([+ ["one input of a required group", { role: literal("string", "Buyer") }],+ [+ "an in-list literal for a choices input",+ { role: literal("string", "Manager") }+ ],+ [+ "a multi-select whose members are all offered",+ {+ role: literal("string", "Manager"),+ channels: channels(["inApp", "slack"])+ }+ ],+ // A variable's value is unknown until the run, so there is nothing to check.+ [+ "a ref for a choices input",+ { role: ref("trigger", "purchaseOrder", ["status"]) }+ ]+ ])("accepts %s", (_, inputs) => {+ expect(codes(alert(inputs))).toEqual([]);});- it("reports INCOMPLETE_CONFIG for an if branch with nothing to check", () => {- const definition = define(- [trigger(), condition("check", [{ id: "p1", kind: "if", clauses: [] }])],- [edge("e1", "trigger", "out", "check")]- );- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["INCOMPLETE_CONFIG"]);+ it.each([+ [+ "an out-of-list literal for a choices input",+ { role: literal("string", "CEO") },+ "inputs.role"+ ],+ [+ "a member of a multi-select that is not offered",+ {+ role: literal("string", "Manager"),+ channels: channels(["inApp", "carrier-pigeon"])+ },+ "inputs.channels"+ ]+ ])("reports INCOMPLETE_CONFIG for %s", (_, inputs, field) => {+ expect(issuesAt(alert(inputs))).toContainEqual({+ code: "INCOMPLETE_CONFIG",+ field+ });});- it("reports INCOMPLETE_CONFIG for a filter with no list chosen", () => {- const definition = define(- [- trigger(),- {- id: "f1",- name: "f1",- type: "filter",- position: { x: 0, y: 0 },- data: { clauses: [] }- }- ],- [edge("e1", "trigger", "out", "f1")]- );- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["INCOMPLETE_CONFIG"]);- expect(issues[0]?.field).toBe("source");+ it("reports INCOMPLETE_CONFIG for an action with nothing chosen", () => {+ expect(issuesAt(wired(action("a1", { action: "" })))).toEqual([+ { code: "INCOMPLETE_CONFIG", field: "action" }+ ]);});- it("reports INCOMPLETE_CONFIG for a choices input given an out-of-list literal", () => {- const definition = define(- [- trigger(),- action("a1", {- action: "alertSomeone",- inputs: { role: literal("string", "CEO") }- })- ],- [edge("e1", "trigger", "out", "a1")]- );- const issues = validateDefinition(definition, catalog);- const choicesIssue = issues.find(- (i) => i.code === "INCOMPLETE_CONFIG" && i.field === "inputs.role"- );- expect(choicesIssue).toBeDefined();- expect(choicesIssue?.field).toBe("inputs.role");+ it("reports INCOMPLETE_CONFIG for an if branch with nothing to check", () => {+ expect(codes(wired(condition("check", [ifPath("p1", [])])))).toEqual([+ "INCOMPLETE_CONFIG"+ ]);});- it("accepts a choices input given an in-list literal", () => {- const definition = define(- [- trigger(),- action("a1", {- action: "alertSomeone",- inputs: { role: literal("string", "Manager") }- })- ],- [edge("e1", "trigger", "out", "a1")]- );- const issues = validateDefinition(definition, catalog);- expect(issues.filter((i) => i.code === "INCOMPLETE_CONFIG")).toEqual([]);+ it("reports INCOMPLETE_CONFIG for a filter with no list chosen", () => {+ expect(issuesAt(wired(filter("f1", { clauses: [] })))).toEqual([+ { code: "INCOMPLETE_CONFIG", field: "source" }+ ]);});-- it("reports INCOMPLETE_CONFIG for a member of a multi-select that is not offered", () => {- const definition = define(- [- trigger(),- action("a1", {- action: "alertSomeone",- inputs: {- role: literal("string", "Manager"),- channels: {- kind: "literal",- type: { kind: "list", of: { kind: "primitive", of: "string" } },- value: ["inApp", "carrier-pigeon"]- }- }- })- ],- [edge("e1", "trigger", "out", "a1")]- );- const issues = validateDefinition(definition, catalog);- expect(- issues.filter(- (i) => i.code === "INCOMPLETE_CONFIG" && i.field === "inputs.channels"- )- ).toHaveLength(1);- });-- it("accepts a multi-select whose members are all offered", () => {- const definition = define(- [- trigger(),- action("a1", {- action: "alertSomeone",- inputs: {- role: literal("string", "Manager"),- channels: {- kind: "literal",- type: { kind: "list", of: { kind: "primitive", of: "string" } },- value: ["inApp", "slack"]- }- }- })- ],- [edge("e1", "trigger", "out", "a1")]- );- const issues = validateDefinition(definition, catalog);- expect(issues.filter((i) => i.code === "INCOMPLETE_CONFIG")).toEqual([]);- });-- it("does not check choices when the value is a ref", () => {- const definition = define(- [- trigger(),- action("a1", {- action: "alertSomeone",- inputs: { role: ref("trigger", "purchaseOrder", ["status"]) }- })- ],- [edge("e1", "trigger", "out", "a1")]- );- const issues = validateDefinition(definition, catalog);- expect(issues.filter((i) => i.code === "INCOMPLETE_CONFIG")).toEqual([]);- });-- it("does not emit INCOMPLETE_CONFIG for an enum-valued lookup match when omitEnums is true", () => {- const thin = createFixtureCatalog({ omitEnums: true });- const definition = define(- [- trigger(),- {- ...lookup("l1", "purchaseOrder", "one"),- data: {- entity: "purchaseOrder",- returns: "one",- match: [- {- field: "status",- operator: "eq",- value: literal("string", "InvalidStatus")- }- ]- }- }- ],- [edge("e1", "trigger", "out", "l1")]- );- expect(- validateDefinition(definition, thin).filter(- (i) => i.code === "INCOMPLETE_CONFIG"- )- ).toEqual([]);- });-});+});// A draft is saved as-is, so these shapes reach the validator. Each must parse// (so autosave never fails) and block publishing (so no half-filled node runs).describe("half-filled drafts", () => {- it("parses a condition clause with no right-hand side, but blocks publishing", () => {- const definition = define(- [- trigger(),- condition("check", [- {- id: "over",- kind: "if",- combinator: "and",- clauses: [- {- left: ref("trigger", "purchaseOrder", ["amount"]),- operator: "gt"- }- ]- }- ]),- action("notify", {- action: "notify",- inputs: {- recipient: ref("trigger", "purchaseOrder", ["assignee", "manager"]),- message: literal("string", "This order is over $10,000.")- }- })- ],- [- edge("e1", "trigger", "out", "check"),- edge("e2", "check", "over", "notify")- ]- );- expect(workflowDefinitionSchema.safeParse(definition).success).toBe(true);-- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["INCOMPLETE_CONFIG"]);- expect(issues[0]?.field).toBe("paths.over.clauses.0.right");- });-- it("parses a lookup match with a blank field, but blocks publishing", () => {- const definition = define(- [- trigger(),- {- ...lookup("l1", "part", "one"),- data: {- entity: "part",- returns: "one",- match: [{ field: "", operator: "eq" }]- }- }- ],- [edge("e1", "trigger", "out", "l1")]- );- expect(workflowDefinitionSchema.safeParse(definition).success).toBe(true);-- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["INCOMPLETE_CONFIG"]);- expect(issues[0]?.field).toBe("match.0.field");- });-- it("parses a lookup match with a named field but no value, but blocks publishing", () => {- const definition = define(- [- trigger(),- {- ...lookup("l1", "part", "one"),- data: {- entity: "part",- returns: "one",- match: [{ field: "name", operator: "eq" }]- }- }- ],- [edge("e1", "trigger", "out", "l1")]- );+ it.each([+ [+ "a condition clause with no right-hand side",+ purchaseOrderWorkflow({+ left: ref("trigger", "purchaseOrder", ["amount"]),+ operator: "gt"+ }),+ "paths.over.clauses.0.right"+ ],+ [+ "a lookup match with a blank field",+ wired(lookup("l1", "part", "one", [{ field: "", operator: "eq" }])),+ "match.0.field"+ ],+ [+ "a lookup match with a named field but no value",+ wired(lookup("l1", "part", "one", [{ field: "name", operator: "eq" }])),+ "match.0.value"+ ]+ ])("parses %s, but blocks publishing", (_, definition, field) => {expect(workflowDefinitionSchema.safeParse(definition).success).toBe(true);-- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["INCOMPLETE_CONFIG"]);- expect(issues[0]?.field).toBe("match.0.value");+ expect(issuesAt(definition)).toEqual([+ { code: "INCOMPLETE_CONFIG", field }+ ]);});});describe("the current item", () => {- const item = (path: string[] = []) => ({ kind: "item" as const, path });+ const overTen = {+ left: item(["unitPrice"]),+ operator: "gt",+ right: literal("number", 10)+ };const filterOn = (clauses: unknown[]) =>- define(- [- trigger(),- lookup("find", "part", "list"),- {- id: "f1",- name: "f1",- type: "filter",- position: { x: 0, y: 0 },- data: { source: ref("find", "result"), clauses }- }- ],- [- edge("e1", "trigger", "out", "find"),- edge("e2", "find", "success", "f1")- ]+ wired(+ lookup("find", "part", "list"),+ filter("f1", { source: ref("find", "result"), clauses }));it("accepts a filter testing a property of the item it is on", () => {- const definition = filterOn([- {- left: item(["unitPrice"]),- operator: "gt",- right: literal("number", 10)- }- ]);- expect(validateDefinition(definition, catalog)).toEqual([]);+ expect(codes(filterOn([overTen]))).toEqual([]);});it("reports ITEM_OUTSIDE_LOOP on a node that works through no list", () => {- const definition = define(- [- trigger(),- condition("check", [- {- id: "p1",- kind: "if",- clauses: [- {- left: item(["unitPrice"]),- operator: "gt",- right: literal("number", 10)- }- ]- }- ])- ],- [edge("e1", "trigger", "out", "check")]+ expect(codes(wired(condition("check", [ifPath("p1", [overTen])])))).toEqual(+ ["ITEM_OUTSIDE_LOOP"]);- expect(codes(definition)).toEqual(["ITEM_OUTSIDE_LOOP"]);});it("reports UNKNOWN_VARIABLE for a property the items do not have", () => {const definition = filterOn([{ left: item(["nope"]), operator: "eq", right: literal("string", "x") }]);- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["UNKNOWN_VARIABLE"]);- expect(issues[0]?.message).toBe(- "This property does not exist on the items in that list."- );+ expect(codes(definition)).toEqual(["UNKNOWN_VARIABLE"]);});- // The next three assert ITEM_OUTSIDE_LOOP is suppressed when a deeper cause exists.+ // ITEM_OUTSIDE_LOOP is suppressed when a deeper cause exists.it("reports only UNKNOWN_ENTITY when the list's record type is gone", () => {const thin = createFixtureCatalog({ omitEntities: ["part"] });- const definition = filterOn([- {- left: item(["unitPrice"]),- operator: "gt",- right: literal("number", 10)- }- ]);- expect(validateDefinition(definition, thin).map((i) => i.code)).toEqual([- "UNKNOWN_ENTITY"- ]);+ expect(codes(filterOn([overTen]), thin)).toEqual(["UNKNOWN_ENTITY"]);});it("reports only INCOMPLETE_CONFIG when the filter has no list chosen", () => {- const definition = define(- [- trigger(),- {- id: "f1",- name: "f1",- type: "filter",- position: { x: 0, y: 0 },- data: {- clauses: [- {- left: item(["unitPrice"]),- operator: "gt",- right: literal("number", 10)- }- ]- }- }- ],- [edge("e1", "trigger", "out", "f1")]- );- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["INCOMPLETE_CONFIG"]);- expect(issues[0]?.field).toBe("source");+ expect(issuesAt(wired(filter("f1", { clauses: [overTen] })))).toEqual([+ { code: "INCOMPLETE_CONFIG", field: "source" }+ ]);});it("reports only UNKNOWN_ACTION when a repeating action's action is gone", () => {const thin = createFixtureCatalog({ omitActions: ["updatePart"] });- const definition = define(- [- trigger(),- action("a1", {- action: "updatePart",- inputs: { name: item(["name"]) }- })- ],- [edge("e1", "trigger", "out", "a1")]+ const definition = wired(+ action("a1", { action: "updatePart", inputs: { name: item(["name"]) } }));- expect(validateDefinition(definition, thin).map((i) => i.code)).toEqual([- "UNKNOWN_ACTION"- ]);- });-- it("accepts a step fed one record, with nothing to repeat", () => {- const definition = define(- [- trigger(),- lookup("find", "part", "one"),- action("a1", {- action: "updatePart",- inputs: { part: ref("find", "result") }- })- ],- [- edge("e1", "trigger", "out", "find"),- edge("e2", "find", "success", "a1")- ]- );- expect(validateDefinition(definition, catalog)).toEqual([]);+ expect(codes(definition, thin)).toEqual(["UNKNOWN_ACTION"]);});});describe("the catalog is injected, not baked in", () => {- it("validates the purchase-order workflow against the full catalog", () => {- expect(validateDefinition(purchaseOrderWorkflow(), catalog)).toEqual([]);- });-- it("reports exactly one UNKNOWN_ACTION when notify is missing", () => {+ it("reports exactly one UNKNOWN_ACTION, on the step, when notify is missing", () => {const thin = createFixtureCatalog({ omitActions: ["notify"] });const issues = validateDefinition(purchaseOrderWorkflow(), thin);- expect(issues).toHaveLength(1);- expect(issues[0]?.code).toBe("UNKNOWN_ACTION");- expect(issues[0]?.nodeId).toBe("notify");+ expect(issues.map(({ code, nodeId }) => ({ code, nodeId }))).toEqual([+ { code: "UNKNOWN_ACTION", nodeId: "notify" }+ ]);});it("reports UNKNOWN_EVENT when the trigger's event is missing", () => {const thin = createFixtureCatalog({omitEvents: ["purchaseOrder.status.changed"]});- const issues = validateDefinition(purchaseOrderWorkflow(), thin);- expect(issues.map((i) => i.code)).toEqual(["UNKNOWN_EVENT"]);- });-});--describe("regressions", () => {- it("rejects a filter whose source is its own output", () => {- const definition = define(- [- trigger(),- {- id: "f",- name: "f",- type: "filter",- position: { x: 0, y: 0 },- data: {- source: { kind: "ref", nodeId: "f", output: "result", path: [] },- clauses: []- }- }- ],- [edge("e1", "trigger", "out", "f")]- );- expect(codes(definition)).toEqual(["REF_NOT_UPSTREAM"]);- });-- it("rejects two filters that read each other", () => {- const filter = (id: string, sourceNode: string) => ({- id,- name: id,- type: "filter",- position: { x: 0, y: 0 },- data: {- source: { kind: "ref", nodeId: sourceNode, output: "result", path: [] },- clauses: []- }- });- const definition = define(- [trigger(), filter("f1", "f2"), filter("f2", "f1")],- [edge("e1", "trigger", "out", "f1"), edge("e2", "f1", "out", "f2")]- );- expect(codes(definition)).toEqual(["REF_NOT_UPSTREAM"]);- });-- it("rejects a literal whose value contradicts its declared type", () => {- const definition = {- formatVersion: 1,- nodes: [- trigger(),- action("a", {- inputs: {- title: {- kind: "literal",- type: { kind: "primitive", of: "string" },- value: { not: "a string" }- }- }- })- ],- edges: [edge("e1", "trigger", "out", "a")]- };- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["MALFORMED_DEFINITION"]);- });-- it("accepts a literal whose value matches its declared type", () => {- const definition = {- formatVersion: 1,- nodes: [- trigger(),- action("a", {- inputs: {- title: {- kind: "literal",- type: { kind: "primitive", of: "string" },- value: "Look into this"- }- }- })- ],- edges: [edge("e1", "trigger", "out", "a")]- };- expect(validateDefinition(definition, catalog)).toEqual([]);- });-- it("rejects an operator outside the shared vocabulary at parse time", () => {- const definition = {- formatVersion: 1,- nodes: [- trigger(),- {- id: "c",- name: "c",- type: "condition",- position: { x: 0, y: 0 },- data: {- paths: [- {- id: "p1",- kind: "if",- clauses: [- {- left: {- kind: "ref",- nodeId: "trigger",- output: "purchaseOrder",- path: ["status"]- },- operator: "banana",- right: {- kind: "literal",- type: { kind: "primitive", of: "string" },- value: "Sent"- }- }- ]- }- ]- }- }- ],- edges: [edge("e1", "trigger", "out", "c")]- };- const issues = validateDefinition(definition, catalog);- expect(issues.map((i) => i.code)).toEqual(["MALFORMED_DEFINITION"]);- });-- it("declares a node kind for every node type in the schema", () => {- const inSchema = nodeSchema.options- .map((option) => option.shape.type.value)- .sort();- expect(Object.keys(NODE_KINDS).sort()).toEqual(inSchema);- });-- it("validates a definition that has never been through the schema", () => {- const issues = validateDefinition({ nodes: "not a list" }, catalog);- expect(issues.length).toBeGreaterThan(0);- expect(issues.every((i) => i.code === "MALFORMED_DEFINITION")).toBe(true);+ expect(codes(purchaseOrderWorkflow(), thin)).toEqual(["UNKNOWN_EVENT"]);});});describe("pairs and showWhen", () => {- const literal = (value: string) => ({- kind: "literal",- type: { kind: "primitive", of: "string" },- value- });+ const text = (value: string) => literal("string", value);+ const url = text("https://example.com");+ const headers = (...entries: unknown[]) => ({ kind: "pairs", entries });const callUrl = (inputs: Record<string, unknown>) =>- define(- [trigger(), action("call", { action: "callUrl", inputs })],- [edge("e1", "trigger", "out", "call")]- );-- const issuesFor = (inputs: Record<string, unknown>) =>- validateDefinition(callUrl(inputs), catalog);-- it("accepts named rows on an input declared for them", () => {- expect(- issuesFor({- url: literal("https://example.com"),- method: literal("POST"),- body: literal("hi"),- headers: {- kind: "pairs",- entries: [{ name: "X-Company-Key", value: literal("abc") }]- }- })- ).toEqual([]);- });-- it("rejects named rows on an input that does not take them", () => {- const issues = issuesFor({- url: { kind: "pairs", entries: [] },- method: literal("GET")- });- expect(issues[0]?.code).toBe("TYPE_MISMATCH");- expect(issues[0]?.message).toMatch(- /does not take a list of names and values/+ validateDefinition(+ wired(action("call", { action: "callUrl", inputs })),+ catalog);- });-- it("rejects a plain value on an input that takes named rows", () => {- const issues = issuesFor({- url: literal("https://example.com"),- method: literal("GET"),- headers: literal("nope")- });- expect(issues[0]?.code).toBe("TYPE_MISMATCH");- expect(issues[0]?.message).toMatch(/takes a list of names and values/);- });- it("reports a row with no name", () => {- const issues = issuesFor({- url: literal("https://example.com"),- method: literal("GET"),- headers: { kind: "pairs", entries: [{ name: " ", value: literal("a") }] }- });- expect(issues[0]?.code).toBe("INCOMPLETE_CONFIG");- expect(issues[0]?.field).toBe("headers.entries.0");- expect(issues[0]?.message).toBe("This row needs a name.");- });-- it("refuses a header name Carbon sets itself", () => {- const issues = issuesFor({- url: literal("https://example.com"),- method: literal("GET"),- headers: {- kind: "pairs",- entries: [{ name: "Host", value: literal("evil.example") }]+ it.each([+ [+ "named rows on an input declared for them",+ {+ url,+ method: text("POST"),+ body: text("hi"),+ headers: headers({ name: "X-Company-Key", value: text("abc") })}- });- expect(issues[0]?.code).toBe("INCOMPLETE_CONFIG");- expect(issues[0]?.message).toMatch(/is set by Carbon/);- });-- it("reports the same name set twice, ignoring case", () => {- const issues = issuesFor({- url: literal("https://example.com"),- method: literal("GET"),- headers: {- kind: "pairs",- entries: [- { name: "X-Key", value: literal("a") },- { name: "x-key", value: literal("b") }- ]+ ],+ ["a gated-off input left empty", { url, method: text("GET") }],+ // A record in a header reads as its readable id, as anywhere else in text.+ [+ "a whole record as a row's value",+ {+ url,+ method: text("GET"),+ headers: headers({+ name: "X-Key",+ value: ref("trigger", "purchaseOrder")+ })}- });- expect(issues[0]?.code).toBe("INCOMPLETE_CONFIG");- expect(issues[0]?.field).toBe("headers.entries.1");- expect(issues[0]?.message).toMatch(/is set twice/);- });-- it("does not require a gated-off input", () => {- expect(- issuesFor({ url: literal("https://example.com"), method: literal("GET") })- ).toEqual([]);- });-- it("requires a gated-on input", () => {- const issues = issuesFor({- url: literal("https://example.com"),- method: literal("POST")- });- expect(issues[0]?.code).toBe("MISSING_INPUT");- expect(issues[0]?.field).toBe("body");+ ],+ [+ "an already-published webhook with only url and body",+ { url, body: text("hi") }+ ]+ ])("accepts %s", (_, inputs) => {+ expect(callUrl(inputs)).toEqual([]);});- it("reports a value left behind on a gated-off input", () => {- const issues = issuesFor({- url: literal("https://example.com"),- method: literal("GET"),- body: literal("leftover")- });- expect(issues[0]?.code).toBe("INCOMPLETE_CONFIG");- expect(issues[0]?.message).toBe(- '"body" does not apply when method is "GET". Clear it to continue.'- );+ it.each([+ [+ "named rows on an input that does not take them",+ { url: headers(), method: text("GET") },+ "TYPE_MISMATCH",+ /does not take a list of names and values/+ ],+ [+ "a plain value on an input that takes named rows",+ { url, method: text("GET"), headers: text("nope") },+ "TYPE_MISMATCH",+ /takes a list of names and values/+ ],+ [+ "a header name Carbon sets itself",+ {+ url,+ method: text("GET"),+ headers: headers({ name: "Host", value: text("evil.example") })+ },+ "INCOMPLETE_CONFIG",+ /is set by Carbon/+ ],+ [+ "a value left behind on a gated-off input",+ { url, method: text("GET"), body: text("leftover") },+ "INCOMPLETE_CONFIG",+ /"body" does not apply when method is "GET"/+ ]+ ])("refuses %s", (_, inputs, code, message) => {+ const [first] = callUrl(inputs);+ expect(first?.code).toBe(code);+ expect(first?.message).toMatch(message);});- it("opens the gate when the gating input holds a variable", () => {- const issues = issuesFor({- url: literal("https://example.com"),- method: {- kind: "ref",- nodeId: "trigger",- output: "purchaseOrder",- path: ["status"]- }- });- expect(issues[0]?.code).toBe("MISSING_INPUT");- expect(issues[0]?.field).toBe("body");+ it.each([+ [+ "a row with no name",+ headers({ name: " ", value: text("a") }),+ "INCOMPLETE_CONFIG",+ "headers.entries.0"+ ],+ [+ "the same name set twice, ignoring case",+ headers(+ { name: "X-Key", value: text("a") },+ { name: "x-key", value: text("b") }+ ),+ "INCOMPLETE_CONFIG",+ "headers.entries.1"+ ],+ [+ "a reference to a missing step inside a row",+ headers({ name: "X-Key", value: ref("gone", "record") }),+ "UNKNOWN_VARIABLE",+ "headers.entries.0"+ ]+ ])("reports %s on that row", (_, rows, code, field) => {+ const [first] = callUrl({ url, method: text("GET"), headers: rows });+ expect({ code: first?.code, field: first?.field }).toEqual({ code, field });});- it("reports a reference to a missing step inside a row", () => {- const issues = issuesFor({- url: literal("https://example.com"),- method: literal("GET"),- headers: {- kind: "pairs",- entries: [- {- name: "X-Key",- value: { kind: "ref", nodeId: "gone", output: "record", path: [] }- }- ]- }- });- expect(issues[0]?.code).toBe("UNKNOWN_VARIABLE");- expect(issues[0]?.field).toBe("headers.entries.0");- });-- // A record in a header reads as its readable id, same as anywhere else in text —- // and a webhook body gets no `linkFor`, so it stays a bare id with no markdown.- it("accepts a whole record as a row's value", () => {- const issues = issuesFor({- url: literal("https://example.com"),- method: literal("GET"),- headers: {- kind: "pairs",- entries: [- {- name: "X-Key",- value: {- kind: "ref",- nodeId: "trigger",- output: "purchaseOrder",- path: []- }- }- ]- }+ it.each([+ ["a literal that opens the gate", text("POST")],+ [+ "a variable, which may open it",+ ref("trigger", "purchaseOrder", ["status"])+ ]+ ])("requires a gated input when the gating input holds %s", (_, method) => {+ const [first] = callUrl({ url, method });+ expect({ code: first?.code, field: first?.field }).toEqual({+ code: "MISSING_INPUT",+ field: "body"});- expect(issues).toEqual([]);- });-- it("leaves an already-published webhook with only url and body alone", () => {- expect(- issuesFor({ url: literal("https://example.com"), body: literal("hi") })- ).toEqual([]);});});diff --git a/packages/ee/src/workflows/runtime/executors.test.ts b/packages/ee/src/workflows/runtime/executors.test.tsindex 03a2c6483c..f05434e62d 100644--- a/packages/ee/src/workflows/runtime/executors.test.ts+++ b/packages/ee/src/workflows/runtime/executors.test.ts@@ -2,51 +2,21 @@// Carbon Enterprise file, licensed only under the Carbon Commercial License// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.-import { describe, expect, it } from "vitest";+import { expect, it } from "vitest";import type { WorkflowNode, WorkflowNodeType } from "../definition/schema";-import { actionExecutor } from "./action";-import { computeExecutor } from "./compute";-import { conditionExecutor } from "./condition";import { executorFor } from "./executors";-import { filterExecutor } from "./filter";-import { lookupExecutor } from "./lookup";const nodeOf = (type: WorkflowNodeType) =>({ id: "n1", type, position: { x: 0, y: 0 }, data: {} }) as WorkflowNode;-const RUNNABLE: WorkflowNodeType[] = [- "condition",- "filter",- "lookup",- "compute",- "action"-];--describe("executorFor", () => {- it("hands back the executor for every kind that can run", () => {- expect(executorFor(nodeOf("condition"))).toBe(conditionExecutor);- expect(executorFor(nodeOf("filter"))).toBe(filterExecutor);- expect(executorFor(nodeOf("lookup"))).toBe(lookupExecutor);- expect(executorFor(nodeOf("compute"))).toBe(computeExecutor);- expect(executorFor(nodeOf("action"))).toBe(actionExecutor);- });-- it("has nothing for a trigger, which the walk starts from rather than runs", () => {- expect(executorFor(nodeOf("trigger"))).toBeUndefined();- });-- it("covers every node kind except the trigger", () => {- for (const type of RUNNABLE) {- expect(executorFor(nodeOf(type))).toBeDefined();- }- });-- it("never offers work without a permission check beside it", () => {- for (const type of RUNNABLE) {- const executor = executorFor(nodeOf(type));- if (executor === undefined) continue;- expect(typeof executor.permission).toBe("function");- expect(typeof executor.execute).toBe("function");- }- });+// The walk starts from the trigger rather than running it; every other kind must run.+it.each<[WorkflowNodeType, boolean]>([+ ["trigger", false],+ ["condition", true],+ ["filter", true],+ ["lookup", true],+ ["compute", true],+ ["action", true]+])("a %s node has an executor: %s", (type, runs) => {+ expect(executorFor(nodeOf(type)) !== undefined).toBe(runs);});diff --git a/packages/env/AGENTS.md b/packages/env/AGENTS.mdindex 99dc10dabb..6b86317b91 100644--- a/packages/env/AGENTS.md+++ b/packages/env/AGENTS.md@@ -13,7 +13,7 @@ Single source of truth for all environment variable access. Validates at module## Ask First-- Adding a `required: "error"` variable, or flipping `"warn"` to `"error"` — this changes boot requirements for every deployment. `src/deployments.test.ts` must pass for each of them first.+- Adding a `required: "error"` variable, or flipping `"warn"` to `"error"` — this changes boot requirements for every deployment. the `deployments-set-required-env` check (`@carbon/checks`) must pass for each of them first.- Changing `getAppUrl()` / `getMESUrl()` resolution logic — affects cross-app links across all editions.## Neverdiff --git a/packages/env/package.json b/packages/env/package.jsonindex f85600d12a..743ef5c336 100644--- a/packages/env/package.json+++ b/packages/env/package.json@@ -5,7 +5,8 @@"private": true,"exports": {".": "./src/index.ts",- "./push.server": "./src/push.server.ts"+ "./push.server": "./src/push.server.ts",+ "./validate": "./src/validate.ts"},"main": "./src/index.ts","types": "./src/index.ts",@@ -13,16 +14,16 @@"scripts": {"clean": "rimraf .turbo node_modules","lint": "biome lint --fix",- "typecheck": "tsgo --noEmit",+ "typecheck": "tsc --noEmit","test": "vitest run"},"dependencies": {"@carbon/utils": "workspace:*",- "@types/node": "20.19.39","zod": "catalog:"},"devDependencies": {"@carbon/config": "workspace:*",+ "@types/node": "20.19.39","typescript": "catalog:","vitest": "catalog:"}diff --git a/packages/env/src/deployments.test.ts b/packages/env/src/deployments.test.tsdeleted file mode 100644index ab1fe9661c..0000000000--- a/packages/env/src/deployments.test.ts+++ /dev/null@@ -1,52 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { readFileSync } from "node:fs";-import { describe, expect, it } from "vitest";-import { validateEnv } from "./validate";-import vercel from "./vercel-production.json";--// What each real deployment sets today, read from the file that sets it. A-// variable that starts stopping startup must already be set by all of them.-const root = new URL("../../../", import.meta.url);-const read = (path: string) => readFileSync(new URL(path, root), "utf8");-const set = (keys: Iterable<string>) =>- Object.fromEntries([...keys].map((key) => [key, "set"]));-const errors = (env: Record<string, string>) =>- validateEnv(env)- .problems.filter((p) => p.level === "error")- .map((p) => p.name);--describe("deployments keep starting", () => {- const services = read("sst.config.ts").split("environment: {").slice(1);-- it.each(["erp", "mes"].map((name, i) => [name, services[i]]))(- "SST %s service",- (_, block = "") => {- const keys = [- ...(block.split("\n },")[0] ?? "").matchAll(/^\s+([A-Z0-9_]+):/gm)- ];- expect(keys.length).toBeGreaterThan(20);- expect(errors(set(keys.map((m) => m[1] as string)))).toEqual([]);- }- );-- it("local crbn up", () => {- const written = read("packages/dev/src/env.ts").matchAll(- /[`"]([A-Z0-9_]+)=/g- );- const example = read(".env.example").matchAll(/^([A-Z0-9_]+)=/gm);- const keys = [...written, ...example].map((m) => m[1] as string);- expect(keys).toContain("SUPABASE_DB_URL");- expect(errors(set(keys))).toEqual([]);- });-- // Names only, from `vercel env ls production` plus the team's shared- // variables, on 2026-10-07. Vercel itself adds NODE_ENV at runtime.- it.each(Object.entries(vercel))("Vercel %s project", (_, keys) => {- expect(errors(set([...keys, "NODE_ENV"]))).toEqual([]);- });-- it.todo("BYOC Helm chart: the chart is not in this repository");-});diff --git a/packages/env/src/schema.ts b/packages/env/src/schema.tsindex f94325ce40..f62a585d36 100644--- a/packages/env/src/schema.ts+++ b/packages/env/src/schema.ts@@ -49,7 +49,8 @@ export type EnvVar = {browser?: boolean;/*** "error" stops startup. "warn" is reported and becomes an error in the next- * release; do not flip one without updating deployments.test.ts.+ * release; do not flip one until every deployment sets it (the+ * `deployments-set-required-env` check in @carbon/checks).*/required?: "error" | "warn";/** Lifts `required` when it returns true. */diff --git a/packages/files/package.json b/packages/files/package.jsonindex 3e0e9a9067..36f554fc80 100644--- a/packages/files/package.json+++ b/packages/files/package.json@@ -17,7 +17,7 @@"clean": "rimraf .turbo node_modules dist","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"dependencies": {"@carbon/database": "workspace:*",@@ -27,7 +27,6 @@"@jsquash/resize": "2.1.1","@jsquash/webp": "1.5.0","@supabase/storage-js": "catalog:",- "@supabase/supabase-js": "catalog:","@tiptap/pm": "catalog:","libheif-js": "1.23.2","nanoid": "catalog:",@@ -37,6 +36,7 @@},"devDependencies": {"@carbon/config": "workspace:*",+ "@supabase/supabase-js": "catalog:","@types/papaparse": "5.5.2","typescript": "catalog:","vitest": "catalog:"diff --git a/packages/files/src/vite-env.d.ts b/packages/files/src/vite-env.d.tsindex 6881ef3c5b..8dc38e2de7 100644--- a/packages/files/src/vite-env.d.ts+++ b/packages/files/src/vite-env.d.ts@@ -4,7 +4,7 @@// This package ships raw source compiled by the consuming app's Vite build.// Type the Vite asset queries the source references without depending on vite-// (typecheck runs standalone via tsgo).+// (typecheck runs standalone via tsc).declare module "*.wasm?inline" {const dataUri: string;export default dataUri;diff --git a/packages/form/package.json b/packages/form/package.jsonindex 5d73e6a1df..8ea7dc17e2 100644--- a/packages/form/package.json+++ b/packages/form/package.json@@ -12,13 +12,18 @@},"devDependencies": {"@carbon/config": "workspace:*",+ "@carbon/content": "workspace:*",+ "@internationalized/date": "catalog:","@lingui/react": "catalog:","@types/lodash.get": "4.4.9","@types/react": "catalog:","@types/react-dom": "catalog:",+ "cookie": "catalog:","fetch-blob": "3.2.0",+ "immer": "9.0.21","react": "catalog:","react-dom": "catalog:",+ "sst": "catalog:","ts-toolbelt": "9.6.0","tsconfig": "*","typescript": "catalog:",@@ -26,17 +31,12 @@"zod-form-data": "catalog:"},"dependencies": {- "@carbon/content": "workspace:*","@carbon/logger": "workspace:*",- "@internationalized/date": "catalog:","@react-aria/i18n": "catalog:",- "cookie": "catalog:",- "immer": "9.0.21","lodash.get": "4.4.2","nanoid": "catalog:","react-phone-number-input": "3.4.16","remeda": "1.61.0",- "sst": "catalog:","tiny-invariant": "1.3.3","zod": "catalog:","zustand": "catalog:"@@ -49,7 +49,7 @@"clean": "rimraf .turbo node_modules dist","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"sideEffects": false,"version": "0.0.0"diff --git a/packages/form/src/internal/getInputProps.test.ts b/packages/form/src/internal/getInputProps.test.tsindex fb5d3496d0..0e4a2a0157 100644--- a/packages/form/src/internal/getInputProps.test.ts+++ b/packages/form/src/internal/getInputProps.test.ts@@ -2,252 +2,107 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { describe, expect, it, vi } from "vitest";-import type { CreateGetInputPropsOptions } from "./getInputProps";+import { expect, it, vi } from "vitest";+import type { ValidationBehaviorOptions } from "./getInputProps";import { createGetInputProps } from "./getInputProps";const fakeEvent = { fake: "event" } as any;-describe("getInputProps", () => {- describe("initial", () => {- it("should validate on blur by default", () => {- const options: CreateGetInputPropsOptions = {- name: "some-field",- defaultValue: "test default value",- touched: false,- hasBeenSubmitted: false,- setTouched: vi.fn(),- clearError: vi.fn(),- validate: vi.fn()- };- const getInputProps = createGetInputProps(options);-- const provided = {- onBlur: vi.fn(),- onChange: vi.fn()- };- const { onChange, onBlur } = getInputProps(provided);-- onChange!(fakeEvent);- expect(provided.onChange).toBeCalledTimes(1);- expect(provided.onChange).toBeCalledWith(fakeEvent);- expect(options.setTouched).toBeCalledTimes(1);- expect(options.setTouched).toBeCalledWith(true);- expect(options.validate).not.toBeCalled();-- onBlur!(fakeEvent);- expect(provided.onBlur).toBeCalledTimes(1);- expect(provided.onBlur).toBeCalledWith(fakeEvent);- expect(options.setTouched).toBeCalledTimes(1);- expect(options.validate).toBeCalledTimes(1);- });-- it("should respect provided validation behavior", () => {- const options: CreateGetInputPropsOptions = {- name: "some-field",- defaultValue: "test default value",- touched: false,- hasBeenSubmitted: false,- setTouched: vi.fn(),- clearError: vi.fn(),- validate: vi.fn(),- validationBehavior: {- initial: "onChange"- }- };- const getInputProps = createGetInputProps(options);-- const provided = {- onBlur: vi.fn(),- onChange: vi.fn()- };- const { onChange, onBlur } = getInputProps(provided);-- onChange!(fakeEvent);- expect(provided.onChange).toBeCalledTimes(1);- expect(provided.onChange).toBeCalledWith(fakeEvent);- expect(options.setTouched).toBeCalledTimes(1);- expect(options.setTouched).toBeCalledWith(true);- expect(options.validate).toBeCalledTimes(1);-- onBlur!(fakeEvent);- expect(provided.onBlur).toBeCalledTimes(1);- expect(provided.onBlur).toBeCalledWith(fakeEvent);- expect(options.setTouched).toBeCalledTimes(1);- expect(options.validate).toBeCalledTimes(1);- });-- it("should not validate when behavior is onSubmit", () => {- const options: CreateGetInputPropsOptions = {- name: "some-field",- defaultValue: "test default value",- touched: false,- hasBeenSubmitted: false,- setTouched: vi.fn(),- clearError: vi.fn(),- validate: vi.fn(),- validationBehavior: {- initial: "onSubmit"- }- };- const getInputProps = createGetInputProps(options);-- const provided = {- onBlur: vi.fn(),- onChange: vi.fn()- };- const { onChange, onBlur } = getInputProps(provided);-- onChange!(fakeEvent);- expect(provided.onChange).toBeCalledTimes(1);- expect(provided.onChange).toBeCalledWith(fakeEvent);- expect(options.setTouched).toBeCalledTimes(1);- expect(options.setTouched).toBeCalledWith(true);- expect(options.validate).not.toBeCalled();-- onBlur!(fakeEvent);- expect(provided.onBlur).toBeCalledTimes(1);- expect(provided.onBlur).toBeCalledWith(fakeEvent);- expect(options.setTouched).toBeCalledTimes(1);- expect(options.validate).not.toBeCalled();- });- });-- describe("whenTouched", () => {- it("should validate on change by default", () => {- const options: CreateGetInputPropsOptions = {- name: "some-field",- defaultValue: "test default value",- touched: true,- hasBeenSubmitted: false,- setTouched: vi.fn(),- clearError: vi.fn(),- validate: vi.fn()- };- const getInputProps = createGetInputProps(options);-- const provided = {- onBlur: vi.fn(),- onChange: vi.fn()- };- const { onChange, onBlur } = getInputProps(provided);-- onChange!(fakeEvent);- expect(provided.onChange).toBeCalledTimes(1);- expect(provided.onChange).toBeCalledWith(fakeEvent);- expect(options.setTouched).toBeCalledTimes(1);- expect(options.setTouched).toBeCalledWith(true);- expect(options.validate).toBeCalledTimes(1);-- onBlur!(fakeEvent);- expect(provided.onBlur).toBeCalledTimes(1);- expect(provided.onBlur).toBeCalledWith(fakeEvent);- expect(options.setTouched).toBeCalledTimes(1);- expect(options.validate).toBeCalledTimes(1);- });-- it("should respect provided validation behavior", () => {- const options: CreateGetInputPropsOptions = {- name: "some-field",- defaultValue: "test default value",- touched: true,- hasBeenSubmitted: false,- setTouched: vi.fn(),- clearError: vi.fn(),- validate: vi.fn(),- validationBehavior: {- whenTouched: "onBlur"- }- };- const getInputProps = createGetInputProps(options);-- const provided = {- onBlur: vi.fn(),- onChange: vi.fn()- };- const { onChange, onBlur } = getInputProps(provided);-- onChange!(fakeEvent);- expect(provided.onChange).toBeCalledTimes(1);- expect(provided.onChange).toBeCalledWith(fakeEvent);- expect(options.setTouched).toBeCalledTimes(1);- expect(options.setTouched).toBeCalledWith(true);- expect(options.validate).not.toBeCalled();-- onBlur!(fakeEvent);- expect(provided.onBlur).toBeCalledTimes(1);- expect(provided.onBlur).toBeCalledWith(fakeEvent);- expect(options.setTouched).toBeCalledTimes(1);- expect(options.validate).toBeCalledTimes(1);- });- });-- describe("whenSubmitted", () => {- it("should validate on change by default", () => {- const options: CreateGetInputPropsOptions = {- name: "some-field",- defaultValue: "test default value",- touched: true,- hasBeenSubmitted: true,- setTouched: vi.fn(),- clearError: vi.fn(),- validate: vi.fn()- };- const getInputProps = createGetInputProps(options);-- const provided = {- onBlur: vi.fn(),- onChange: vi.fn()- };- const { onChange, onBlur } = getInputProps(provided);-- onChange!(fakeEvent);- expect(provided.onChange).toBeCalledTimes(1);- expect(provided.onChange).toBeCalledWith(fakeEvent);- expect(options.setTouched).toBeCalledTimes(1);- expect(options.setTouched).toBeCalledWith(true);- expect(options.validate).toBeCalledTimes(1);-- onBlur!(fakeEvent);- expect(provided.onBlur).toBeCalledTimes(1);- expect(provided.onBlur).toBeCalledWith(fakeEvent);- expect(options.setTouched).toBeCalledTimes(1);- expect(options.validate).toBeCalledTimes(1);- });-- it("should respect provided validation behavior", () => {- const options: CreateGetInputPropsOptions = {- name: "some-field",- defaultValue: "test default value",- touched: true,- hasBeenSubmitted: true,- setTouched: vi.fn(),- clearError: vi.fn(),- validate: vi.fn(),- validationBehavior: {- whenSubmitted: "onBlur"- }- };- const getInputProps = createGetInputProps(options);-- const provided = {- onBlur: vi.fn(),- onChange: vi.fn()- };- const { onChange, onBlur } = getInputProps(provided);-- onChange!(fakeEvent);- expect(provided.onChange).toBeCalledTimes(1);- expect(provided.onChange).toBeCalledWith(fakeEvent);- expect(options.setTouched).toBeCalledTimes(1);- expect(options.setTouched).toBeCalledWith(true);- expect(options.validate).not.toBeCalled();-- onBlur!(fakeEvent);- expect(provided.onBlur).toBeCalledTimes(1);- expect(provided.onBlur).toBeCalledWith(fakeEvent);- expect(options.setTouched).toBeCalledTimes(1);- expect(options.validate).toBeCalledTimes(1);- });- });-});+// The composed handlers ARE the output here, so spies are the assertion.+it.each<{+ state: string;+ touched: boolean;+ hasBeenSubmitted: boolean;+ validationBehavior?: Partial<ValidationBehaviorOptions>;+ validatesOnChange: boolean;+ validatesOnBlur: boolean;+}>([+ {+ state: "untouched, default",+ touched: false,+ hasBeenSubmitted: false,+ validatesOnChange: false,+ validatesOnBlur: true+ },+ {+ state: "untouched, initial onChange",+ touched: false,+ hasBeenSubmitted: false,+ validationBehavior: { initial: "onChange" },+ validatesOnChange: true,+ validatesOnBlur: false+ },+ {+ state: "untouched, initial onSubmit",+ touched: false,+ hasBeenSubmitted: false,+ validationBehavior: { initial: "onSubmit" },+ validatesOnChange: false,+ validatesOnBlur: false+ },+ {+ state: "touched, default",+ touched: true,+ hasBeenSubmitted: false,+ validatesOnChange: true,+ validatesOnBlur: false+ },+ {+ state: "touched, whenTouched onBlur",+ touched: true,+ hasBeenSubmitted: false,+ validationBehavior: { whenTouched: "onBlur" },+ validatesOnChange: false,+ validatesOnBlur: true+ },+ {+ state: "submitted, default",+ touched: true,+ hasBeenSubmitted: true,+ validatesOnChange: true,+ validatesOnBlur: false+ },+ {+ state: "submitted, whenSubmitted onBlur",+ touched: true,+ hasBeenSubmitted: true,+ validationBehavior: { whenSubmitted: "onBlur" },+ validatesOnChange: false,+ validatesOnBlur: true+ }+])(+ "$state: validates on change=$validatesOnChange, on blur=$validatesOnBlur, and still calls the provided handlers",+ ({+ touched,+ hasBeenSubmitted,+ validationBehavior,+ validatesOnChange,+ validatesOnBlur+ }) => {+ const options = {+ name: "some-field",+ defaultValue: "test default value",+ touched,+ hasBeenSubmitted,+ validationBehavior,+ setTouched: vi.fn(),+ clearError: vi.fn(),+ validate: vi.fn()+ };+ const provided = { onBlur: vi.fn(), onChange: vi.fn() };+ const { onChange, onBlur } = createGetInputProps(options)(provided);++ onChange!(fakeEvent);+ expect(provided.onChange).toHaveBeenCalledExactlyOnceWith(fakeEvent);+ expect(options.setTouched).toHaveBeenCalledExactlyOnceWith(true);+ expect(options.validate).toHaveBeenCalledTimes(validatesOnChange ? 1 : 0);+ // A change that does not validate clears the stale error instead.+ expect(options.clearError).toHaveBeenCalledTimes(validatesOnChange ? 0 : 1);++ options.validate.mockClear();+ onBlur!(fakeEvent);+ expect(provided.onBlur).toHaveBeenCalledExactlyOnceWith(fakeEvent);+ expect(options.setTouched).toHaveBeenCalledTimes(1);+ expect(options.validate).toHaveBeenCalledTimes(validatesOnBlur ? 1 : 0);+ }+);diff --git a/packages/harness/package.json b/packages/harness/package.jsonindex 4b57cbec0a..dac18454a7 100644--- a/packages/harness/package.json+++ b/packages/harness/package.json@@ -10,7 +10,7 @@"clean": "rimraf .turbo node_modules dist","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit",+ "typecheck": "tsc --noEmit","gates": "tsx src/scripts/run-gates.ts","loop": "tsx src/scripts/run-loop.ts","gc": "tsx src/scripts/prune-runs.ts"diff --git a/packages/harness/src/gates.test.ts b/packages/harness/src/gates.test.tsdeleted file mode 100644index a1135112a8..0000000000--- a/packages/harness/src/gates.test.ts+++ /dev/null@@ -1,29 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { describe, expect, it } from "vitest";-import { type Exec, FLOOR_GATES, runGates } from "./gates";--describe("runGates", () => {- it("runs each gate via the injected exec and reports pass/fail", () => {- const exec: Exec = (cmd) => ({- ok: !cmd.includes("clobbers"),- output: cmd- });- const gates = [- { id: "lint", cmd: "biome check" },- { id: "clobbers", cmd: "pnpm clobbers" }- ];- const results = runGates(gates, exec);- expect(results).toEqual([- { id: "lint", passed: true, output: "biome check" },- { id: "clobbers", passed: false, output: "pnpm clobbers" }- ]);- });-- it("ships a non-empty FLOOR_GATES list", () => {- expect(FLOOR_GATES.length).toBeGreaterThan(0);- expect(FLOOR_GATES.every((g) => g.id && g.cmd)).toBe(true);- });-});diff --git a/packages/harness/src/smoke.test.ts b/packages/harness/src/smoke.test.tsdeleted file mode 100644index 16d9f1769b..0000000000--- a/packages/harness/src/smoke.test.ts+++ /dev/null@@ -1,11 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { describe, expect, it } from "vitest";--describe("@carbon/harness", () => {- it("runs", () => {- expect(true).toBe(true);- });-});diff --git a/packages/jobs/package.json b/packages/jobs/package.jsonindex 981b8782c7..f5db6bee62 100644--- a/packages/jobs/package.json+++ b/packages/jobs/package.json@@ -18,32 +18,32 @@"@carbon/utils": "workspace:*","@carbon/viewer": "workspace:*","@internationalized/date": "catalog:",- "react-email": "catalog:","@react-pdf/renderer": "catalog:","@slack/web-api": "catalog:",- "@supabase/functions-js": "catalog:",- "@supabase/supabase-js": "catalog:","ai": "catalog:","axios": "catalog:","inngest": "^3.54.2","kysely": "catalog:","nanoid": "catalog:",- "react": "catalog:",- "react-dom": "catalog:",- "react-pdf": "catalog:",- "sst": "catalog:",- "supabase": "catalog:",- "tsup": "catalog:",+ "react-email": "catalog:","undici": "^8.10.2","web-push": "^3.6.7","zod": "catalog:"},"devDependencies": {"@carbon/config": "workspace:*",+ "@supabase/functions-js": "catalog:",+ "@supabase/supabase-js": "catalog:","@types/pg": "8.15.6","@types/react": "catalog:","@types/web-push": "^3.6.4","pg": "8.20.0",+ "react": "catalog:",+ "react-dom": "catalog:",+ "react-pdf": "catalog:",+ "sst": "catalog:",+ "supabase": "catalog:",+ "tsup": "catalog:","tsx": "catalog:","typescript": "catalog:","vitest": "catalog:"diff --git a/packages/jobs/src/backups/schema.test.ts b/packages/jobs/src/backups/schema.test.tsindex 9a1e7b4698..7b39758053 100644--- a/packages/jobs/src/backups/schema.test.ts+++ b/packages/jobs/src/backups/schema.test.ts@@ -2,7 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { describe, expect, it, vi } from "vitest";+import { describe, expect, it } from "vitest";import { assertBackupImportable } from "../inngest/functions/tasks/company-backup";import {BACKUP_KIND,@@ -15,23 +15,10 @@ import {type TableInfo} from "./schema";-vi.mock("./renames", () => ({- // A dropped table, a renamed table, and a rename whose target is also gone.- TABLE_RENAMES: {- retiredFeature: null,- oldName: "newName",- danglingRename: "alsoMissing"- },- COLUMN_RENAMES: { oldName: { legacyId: "newId" } },- renameLiveColumns: (table: string, columns: string[]) =>- table === "keptName" && !columns.includes("newPrice")- ? columns.map((c) => (c === "oldPrice" ? "newPrice" : c))- : columns,- renameColumns: (table: string, columns: string[]) =>- table === "oldName"- ? columns.map((c) => (c === "legacyId" ? "newId" : c))- : columns-}));+// Rename cases use real entries from renames.ts: exchangeRateHistory was+// dropped, storageRule became enforcementRule, cardTransaction became charge+// (cardTransactionId → chargeId), and supplierPart kept its name but renamed+// unitPrice → supplierUnitPrice. Entries are permanent history.const col = (name: string, opts: Partial<ColumnInfo> = {}): ColumnInfo => ({name,@@ -212,20 +199,20 @@ describe("reportBackupCompatibility — TABLE_RENAMES", () => {it("treats a null mapping as dropped with its feature — discarded, not blocked", () => {const result = reportBackupCompatibility(catalog([table("item", [col("id")])]),- backup([{ name: "retiredFeature", rows: 2, columns: ["id"] }])+ backup([{ name: "exchangeRateHistory", rows: 2, columns: ["id"] }]));expect(result.blocked).toBe(false);expect(result.findings[0]).toMatchObject({kind: "discarded",- table: "retiredFeature"+ table: "exchangeRateHistory"});});it("follows a rename to the new table and compares columns there", () => {const result = reportBackupCompatibility(- catalog([table("newName", [col("id"), col("name")])]),- backup([{ name: "oldName", rows: 2, columns: ["id", "name"] }])+ catalog([table("enforcementRule", [col("id"), col("name")])]),+ backup([{ name: "storageRule", rows: 2, columns: ["id", "name"] }]));expect(result.findings).toEqual([]);@@ -234,8 +221,14 @@ describe("reportBackupCompatibility — TABLE_RENAMES", () => {it("compares a renamed table's columns under their current names", () => {const result = reportBackupCompatibility(- catalog([table("newName", [col("id"), col("newId")])]),- backup([{ name: "oldName", rows: 2, columns: ["id", "legacyId"] }])+ catalog([table("charge", [col("id"), col("chargeId")])]),+ backup([+ {+ name: "cardTransaction",+ rows: 2,+ columns: ["id", "cardTransactionId"]+ }+ ]));expect(result.findings).toEqual([]);@@ -244,8 +237,8 @@ describe("reportBackupCompatibility — TABLE_RENAMES", () => {it("compares a renamed column on a kept table under its current name", () => {const result = reportBackupCompatibility(- catalog([table("keptName", [col("id"), col("newPrice")])]),- backup([{ name: "keptName", rows: 1, columns: ["id", "oldPrice"] }])+ catalog([table("supplierPart", [col("id"), col("supplierUnitPrice")])]),+ backup([{ name: "supplierPart", rows: 1, columns: ["id", "unitPrice"] }]));expect(result.findings).toEqual([]);@@ -255,11 +248,11 @@ describe("reportBackupCompatibility — TABLE_RENAMES", () => {it("blocks when the rename target is also missing", () => {const result = reportBackupCompatibility(catalog([table("item", [col("id")])]),- backup([{ name: "danglingRename", rows: 2, columns: ["id"] }])+ backup([{ name: "storageRule", rows: 2, columns: ["id"] }]));expect(result.blocked).toBe(true);- expect(result.findings[0]?.reason).toContain("alsoMissing");+ expect(result.findings[0]?.reason).toContain("enforcementRule");});});@@ -313,12 +306,12 @@ describe("assertBackupImportable", () => {it("REFUSES a rename whose target the backup also carries", () => {// Applying the rename would merge two tables; the loader keys off name, so- // letting it through drops oldName's rows in silence.+ // letting it through drops storageRule's rows in silence.const result = gate(- catalog([table("newName", [col("id")])]),+ catalog([table("enforcementRule", [col("id")])]),backup([- { name: "oldName", rows: 2, columns: ["id"] },- { name: "newName", rows: 5, columns: ["id"] }+ { name: "storageRule", rows: 2, columns: ["id"] },+ { name: "enforcementRule", rows: 5, columns: ["id"] }]));expect(result.ok).toBe(false);@@ -327,11 +320,11 @@ describe("assertBackupImportable", () => {);});- it("ACCEPTS a renamed table, the case the hand-kept copy used to refuse", () => {+ it("accepts a renamed table", () => {expect(gate(- catalog([table("newName", [col("id")])]),- backup([{ name: "oldName", rows: 2, columns: ["id"] }])+ catalog([table("enforcementRule", [col("id")])]),+ backup([{ name: "storageRule", rows: 2, columns: ["id"] }]))).toEqual({ ok: true });});@@ -342,7 +335,7 @@ describe("assertBackupImportable", () => {catalog([table("item", [col("id")])]),backup([{ name: "item", rows: 1, columns: ["id"] },- { name: "retiredFeature", rows: 9, columns: ["id"] }+ { name: "exchangeRateHistory", rows: 9, columns: ["id"] }]))).toEqual({ ok: true });diff --git a/packages/jobs/src/inngest/functions/events/embedding.test.ts b/packages/jobs/src/inngest/functions/events/embedding.test.tsindex d2144e6e4c..69382c574a 100644--- a/packages/jobs/src/inngest/functions/events/embedding.test.ts+++ b/packages/jobs/src/inngest/functions/events/embedding.test.ts@@ -4,13 +4,10 @@import { describe, expect, it, vi } from "vitest";+// @carbon/auth builds its Supabase client at import time.vi.mock("@carbon/auth/client.server", () => ({getCarbonServiceRole: vi.fn()}));-vi.mock("../../client.js", () => ({- inngest: { createFunction: () => ({}) }-}));-vi.mock("../../../db", () => ({ getJobDatabaseClient: vi.fn() }));const { embedInBatches, toEmbeddedText } = await import("./embedding");diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-fetch.test.ts b/packages/jobs/src/inngest/functions/integrations/onshape-fetch.test.tsindex e38ea11993..5cf74c7bcc 100644--- a/packages/jobs/src/inngest/functions/integrations/onshape-fetch.test.ts+++ b/packages/jobs/src/inngest/functions/integrations/onshape-fetch.test.ts@@ -2,105 +2,58 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { beforeEach, describe, expect, it, vi } from "vitest";-import { fetchWithAssembler } from "./onshape-fetch";+import { NonRetriableError } from "inngest";+import { describe, expect, it, vi } from "vitest";-const mocks = vi.hoisted(() => ({- runAssemblerJob: vi.fn(),- externalDataDownload: vi.fn()-}));-vi.mock("@carbon/ee/onshape", () => ({- getOnshapeClient: vi.fn(async () => ({- client: { externalDataDownload: mocks.externalDataDownload }- }))-}));-vi.mock("@carbon/utils", () => ({- getFileSizeLimit: () => ({ bytes: 100000 })-}));+// Both connect at import time (Supabase, Redis); neither is called here.vi.mock("@carbon/auth/client.server", () => ({getCarbonServiceRole: vi.fn()}));-vi.mock("../../client", () => ({- inngest: { createFunction: (...args: unknown[]) => args }-}));-vi.mock("../tasks/assembler-client", () => {- class AssemblerJobError extends Error {- constructor(- message: string,- readonly code?: string- ) {- super(message);- }- }- return {- ASSEMBLER_CONCURRENCY: [],- AssemblerJobError,- runAssemblerJob: mocks.runAssemblerJob,- signUploadUrls: vi.fn(async () => ({ raw: "https://storage.test/put" }))- };-});+vi.mock("@carbon/ee/onshape", () => ({ getOnshapeClient: vi.fn() }));-const step = { run: vi.fn(), waitForEvent: vi.fn() };-const carbon = {- storage: { from: () => ({}) }-} as unknown as Parameters<typeof fetchWithAssembler>[1];-const input = {- companyId: "company",- userId: "user",- translationId: "model-t",- documentId: "export-document",- foreignId: "file-1",- stagedPath: "company/models/onshape-fetch-model-t.step"-};+const { AssemblerJobError } = await import("../tasks/assembler-client");+const { isExportTooLarge, stagedModelFromFetch } = await import(+ "./onshape-fetch"+);-beforeEach(() => {- vi.clearAllMocks();- mocks.externalDataDownload.mockReturnValue({- url: "https://cad.onshape.test/api/v10/documents/d/export-document/externaldata/file-1",- authorization: "Bearer onshape-token"+const STAGED = "company/models/onshape-fetch-model-t.step";++describe("stagedModelFromFetch", () => {+ it("reports the staged path, size and content hash", () => {+ expect(+ stagedModelFromFetch(+ { contentHash: "xxh3-hash", outputs: { raw: { bytes: 13 } } },+ STAGED+ )+ ).toEqual({ stagedPath: STAGED, size: 13, contentHash: "xxh3-hash" });});- mocks.runAssemblerJob.mockResolvedValue({- result: { contentHash: "xxh3-hash", outputs: { raw: { bytes: 13 } } },- stats: {}++ it("reads a missing size as zero", () => {+ expect(stagedModelFromFetch({ contentHash: "h" }, STAGED).size).toBe(0);});++ it.each([null, {}, { outputs: { raw: { bytes: 13 } } }])(+ "fails for good when the job reports no content hash: %j",+ (result) => {+ expect(() => stagedModelFromFetch(result, STAGED)).toThrow(+ NonRetriableError+ );+ }+ );});-describe("assembler fetch of an Onshape export", () => {- it("sends Onshape's download and bearer, capped at the upload limit", async () => {- expect(await fetchWithAssembler(step, carbon, input)).toEqual({- stagedPath: input.stagedPath,- size: 13,- contentHash: "xxh3-hash"- });- const spec = mocks.runAssemblerJob.mock.calls[0]![1];- expect(spec).toMatchObject({- action: "fetch",- jobId: "onshape-fetch-model-t"- });- expect(await spec.buildBody()).toEqual({- source: {- url: expect.stringContaining("/externaldata/file-1"),- authorization: "Bearer onshape-token"- },- maxBytes: 100000,- output: { path: input.stagedPath, contentType: "application/step" }- });+describe("isExportTooLarge", () => {+ it("skips an export the assembler refused as past the limit", () => {+ expect(+ isExportTooLarge(new AssemblerJobError("too large", "LIMIT_EXCEEDED"))+ ).toBe(true);});- it("returns tooLarge for an export past the limit, and rethrows anything else", async () => {- const { AssemblerJobError } = await import("../tasks/assembler-client");- mocks.runAssemblerJob.mockRejectedValueOnce(- new AssemblerJobError("too large", "LIMIT_EXCEEDED")- );- expect(await fetchWithAssembler(step, carbon, input)).toEqual({- tooLarge: true- });-- mocks.runAssemblerJob.mockRejectedValueOnce(- new AssemblerJobError("source unreadable", "READ_FAILED")- );- await expect(fetchWithAssembler(step, carbon, input)).rejects.toThrow(- "source unreadable"- );+ it.each([+ new AssemblerJobError("source unreadable", "READ_FAILED"),+ new AssemblerJobError("no code"),+ Object.assign(new Error("lookalike"), { code: "LIMIT_EXCEEDED" })+ ])("rethrows any other failure: %s", (error) => {+ expect(isExportTooLarge(error)).toBe(false);});});diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-fetch.ts b/packages/jobs/src/inngest/functions/integrations/onshape-fetch.tsindex 4762ab6f77..4f817fd052 100644--- a/packages/jobs/src/inngest/functions/integrations/onshape-fetch.ts+++ b/packages/jobs/src/inngest/functions/integrations/onshape-fetch.ts@@ -91,28 +91,39 @@ export async function fetchWithAssembler(}})});- const result = job.result as {- contentHash?: string;- outputs?: { raw?: { bytes?: number } };- } | null;- if (!result?.contentHash) {- throw new NonRetriableError("assembler fetch returned no content hash");- }- return {- stagedPath: input.stagedPath,- size: result.outputs?.raw?.bytes ?? 0,- contentHash: result.contentHash- };+ return stagedModelFromFetch(job.result, input.stagedPath);} catch (error) {// Decided here: an error class does not survive the invoke back to the// caller, a returned value does.- if (error instanceof AssemblerJobError && error.code === "LIMIT_EXCEEDED") {- return { tooLarge: true };- }+ if (isExportTooLarge(error)) return { tooLarge: true };throw error;}}+/** The staged export a finished fetch job reports; no content hash is a permanent failure. */+export function stagedModelFromFetch(+ jobResult: unknown,+ stagedPath: string+): StagedModel {+ const result = jobResult as {+ contentHash?: string;+ outputs?: { raw?: { bytes?: number } };+ } | null;+ if (!result?.contentHash) {+ throw new NonRetriableError("assembler fetch returned no content hash");+ }+ return {+ stagedPath,+ size: result.outputs?.raw?.bytes ?? 0,+ contentHash: result.contentHash+ };+}++/** An export past the raw model cap is skipped for good, never retried. */+export function isExportTooLarge(error: unknown): boolean {+ return error instanceof AssemblerJobError && error.code === "LIMIT_EXCEEDED";+}+export const onshapeFetchFunction = inngest.createFunction({id: "onshape-fetch",diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.test.ts b/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.test.tsindex fe4e7fafdb..e3cedb28a4 100644--- a/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.test.ts+++ b/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.test.ts@@ -14,10 +14,9 @@ import {const mocks = vi.hoisted(() => ({getRevisions: vi.fn(),- getCompanyRevisions: vi.fn(),- sync: vi.fn(),- drawing: vi.fn()+ getCompanyRevisions: vi.fn()}));+// The Onshape API is the network boundary; @carbon/auth connects at import time.vi.mock("@carbon/ee/onshape", () => ({getOnshapeClient: vi.fn(async () => ({ client: mocks })),OnshapeAssetTooLargeError: class extends Error {},@@ -26,16 +25,6 @@ vi.mock("@carbon/ee/onshape", () => ({vi.mock("@carbon/auth/client.server", () => ({getCarbonServiceRole: vi.fn()}));-vi.mock("../../client", () => ({- inngest: { createFunction: (...args: unknown[]) => args }-}));-vi.mock("./onshape-sync-element", () => ({- ONSHAPE_CHECKPOINTING: {},- runOnshapeElementSync: mocks.sync,- runOnshapeDrawingSync: mocks.drawing-}));-vi.mock("./onshape-element-sync", () => ({ onshapeElementSyncFunction: {} }));-vi.mock("../tasks/assembler-client", () => ({ ASSEMBLER_CONCURRENCY: [] }));const input: OnshapeRevisionSyncInput = {companyId: "carbon-company",@@ -95,7 +84,6 @@ beforeEach(() => {vi.clearAllMocks();mocks.getRevisions.mockResolvedValue({ items: [released] });mocks.getCompanyRevisions.mockResolvedValue({ items: [released] });- mocks.sync.mockResolvedValue({ modelUploadId: "selected-model" });});describe("release identity", () => {@@ -167,7 +155,7 @@ describe("release identity", () => {});describe("released drawings", () => {- it("resolves a drawing to the model item sharing its number, exporting nothing yet", async () => {+ it("resolves a drawing to the model item sharing its number", async () => {mocks.getRevisions.mockResolvedValue({items: [{ ...released, partNumber: "DRW-SADDLE", elementType: 2 }]});@@ -189,7 +177,6 @@ describe("released drawings", () => {assetBaseName: "PRT-SADDLE.A"}});- expect(mocks.drawing).not.toHaveBeenCalled();});});diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.test.ts b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.test.tsindex 8b13394d80..017f8b303f 100644--- a/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.test.ts+++ b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.test.ts@@ -2,476 +2,381 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { writeFile } from "node:fs/promises";-import { beforeEach, describe, expect, it, vi } from "vitest";-import type { SyncOnshapeElementInput } from "./onshape-sync-element";+import type { OnshapeClient } from "@carbon/ee/onshape";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {- runOnshapeDrawingSync,- runOnshapeElementSync,- translationEventCondition+ assemblySourceKeyAt,+ assertSelection,+ type ElementSyncStep,+ finishedTranslation,+ modelTranslationRequest,+ partSourceId,+ reusableModelUploadId,+ type SyncOnshapeElementInput,+ translationEventCondition,+ waitForTranslations} from "./onshape-sync-element";-const mocks = vi.hoisted(() => ({- client: {- createPartStudioTranslation: vi.fn(),- createAssemblyTranslation: vi.fn(),- createDrawingTranslation: vi.fn(),- getTranslation: vi.fn(),- downloadExternalData: vi.fn(),- downloadExternalDataToFile: vi.fn(),- externalDataDownload: vi.fn(),- getCurrentMicroversion: vi.fn(),- createWebhook: vi.fn(),- deleteWebhook: vi.fn()- },- attach: vi.fn(),- assemblerEnabled: vi.fn(),- invoke: vi.fn(),- existingModel: null as { id: string; name: string } | null,- modelSource: null as {- externalId: string;- metadata: { modelUploadId: string };- } | null,- itemModelUploadId: null as string | null,- upserts: [] as Record<string, unknown>[]-}));+// Import stubs: both packages open Redis or Supabase clients at import.+vi.mock("@carbon/auth/client.server", () => ({}));vi.mock("@carbon/ee/onshape", () => ({- getOnshapeClient: vi.fn(async () => ({ client: mocks.client })),+ getOnshapeClient: vi.fn(),+ OnshapeApiError: class extends Error {},OnshapeAssetTooLargeError: class extends Error {}}));-vi.mock("@carbon/utils", () => ({- getFileSizeLimit: () => ({ bytes: 100000 }),- datetime: { timestamp: () => "2026-10-20T00:00:00Z" }-}));-vi.mock("@carbon/env", () => ({ getAppUrl: () => "https://app.carbon.test" }));-vi.mock("./onshape-attach", () => ({- attachOnshapeAssetsToItem: mocks.attach-}));-vi.mock("../tasks/assembler-client", () => ({- assemblerEnabled: mocks.assemblerEnabled-}));-vi.mock("./onshape-fetch", () => ({- onshapeFetchFunction: { id: "onshape-fetch" },- RAW_MODEL_MAX_BYTES: 100000-}));-// Runs each step at once, in order: the pipeline's logic, not Inngest's.-const step = {- run: async (_id: string, fn: () => unknown) => fn(),- sleep: vi.fn(async () => undefined),- waitForEvent: vi.fn(async () => null),- invoke: mocks.invoke-};--const carbon = {- from: (table: string) => {- const row = () =>- table === "externalIntegrationMapping"- ? mocks.modelSource- : table === "item"- ? { modelUploadId: mocks.itemModelUploadId }- : mocks.existingModel;- const query = {- select: () => query,- eq: () => query,- maybeSingle: async () => ({ data: row(), error: null }),- upsert: async (values: Record<string, unknown>) => {- mocks.upserts.push(values);- return { error: null };- }- };- return query;- },- storage: {- from: () => ({ upload: vi.fn(async () => ({ data: {}, error: null })) })- }-} as unknown as Parameters<typeof runOnshapeElementSync>[1];--const input = {- companyId: "company",- userId: "user",- itemId: "saddle-item",- sourceDocument: "Part",- documentId: "released-document",- versionId: "released-version",- modelElementId: "multi-part-studio",- modelElementKind: "partstudio",- partId: "saddle-only",- configuration: "Size=Large;Finish=Matte",- assetBaseName: "SADDLE.A"-} as const;--const sync = (args: SyncOnshapeElementInput = input) =>- runOnshapeElementSync(step, carbon, args, "element");--beforeEach(() => {- vi.clearAllMocks();- mocks.existingModel = null;- mocks.modelSource = null;- mocks.itemModelUploadId = null;- mocks.upserts = [];- mocks.client.getCurrentMicroversion.mockResolvedValue("microversion-1");- mocks.client.createWebhook.mockResolvedValue({ id: "webhook-1" });- mocks.assemblerEnabled.mockReturnValue(false);- mocks.client.createPartStudioTranslation.mockResolvedValue({ id: "model-t" });- mocks.client.createAssemblyTranslation.mockResolvedValue({ id: "model-t" });- mocks.client.createDrawingTranslation.mockImplementation(- async (_d: string, _v: string, elementId: string) => ({- id: `drawing-${elementId}`- })- );- mocks.client.getTranslation.mockImplementation(async (id: string) => ({- id,- requestState: "DONE",- resultDocumentId: "export-document",- resultExternalDataIds: [`file-${id}`]- }));- mocks.client.downloadExternalDataToFile.mockImplementation(- async (_document: string, _file: string, path: string) =>- writeFile(path, "ISO-10303-21;")+function base(+ overrides: Partial<SyncOnshapeElementInput> = {}+): SyncOnshapeElementInput {+ return {+ companyId: "company",+ userId: "user",+ itemId: "saddle-item",+ sourceDocument: "Part",+ documentId: "released-document",+ versionId: "released-version",+ modelElementId: "multi-part-studio",+ modelElementKind: "partstudio",+ partId: "saddle-only",+ configuration: "Size=Large;Finish=Matte",+ ...overrides+ };+}++describe("assertSelection", () => {+ it.each([undefined, null, "", " ", "part-one,part-two", "part one"])(+ "refuses a part studio export without exactly one part (%s)",+ (partId) => {+ // A missing selection used to export the whole studio.+ expect(() => assertSelection(base({ partId }))).toThrow(/one partId/);+ });- mocks.client.downloadExternalData.mockResolvedValue(new ArrayBuffer(4));- mocks.client.externalDataDownload.mockReturnValue({- url: "https://cad.onshape.test/api/v10/documents/d/export-document/externaldata/file",- authorization: "Bearer onshape-token"++ it("accepts one part, or a whole assembly with no part", () => {+ expect(() => assertSelection(base())).not.toThrow();+ expect(() =>+ assertSelection(base({ modelElementKind: "assembly", partId: undefined }))+ ).not.toThrow();});- mocks.attach.mockResolvedValue({- modelUploadId: "new-model",- documentIds: [],- preservedPriorModelAsDocument: false++ it("refuses a configuration that is not a string", () => {+ const input = base({ configuration: 7 as unknown as string });+ expect(() => assertSelection(input)).toThrow(/configuration/);});});-const attachedModel = () => mocks.attach.mock.calls.at(-1)![1].model;--describe("released model exports", () => {- it("exports only the released part, in its configuration, as STEP", async () => {- await sync();- expect(mocks.client.createPartStudioTranslation).toHaveBeenCalledWith(- input.documentId,- input.versionId,- input.modelElementId,- expect.objectContaining({+describe("modelTranslationRequest", () => {+ it("exports one part, in its configuration, as STEP", () => {+ expect(modelTranslationRequest(base())).toEqual({+ kind: "partstudio",+ options: {formatName: "STEP",- partIds: "saddle-only",- configuration: input.configuration- })- );- expect(mocks.client.createAssemblyTranslation).not.toHaveBeenCalled();- // A STEP raw is what lets an assembly instruction convert the model.- expect(attachedModel()).toMatchObject({- fileName: "SADDLE.A.step",- stagedPath: "company/models/onshape-fetch-model-t.step",- contentHash: expect.stringMatching(/^sha256:[0-9a-f]{64}$/)+ storeInDocument: false,+ configuration: "Size=Large;Finish=Matte",+ wvm: "v",+ partIds: "saddle-only"+ }});});- it.each([undefined, null, "", " ", "part-one,part-two"])(- "refuses unsafe individual-part selection %s before any export or attach",- async (partId) => {- const invalid = {- ...input,- partId- } as unknown as SyncOnshapeElementInput;- await expect(sync(invalid)).rejects.toThrow(/part/i);- expect(mocks.client.createPartStudioTranslation).not.toHaveBeenCalled();- expect(mocks.attach).not.toHaveBeenCalled();- }- );-- it("keeps whole-assembly exports and forwards their configuration", async () => {- await sync({- ...input,- modelElementKind: "assembly",- partId: undefined+ it("exports a whole assembly from a workspace with no part selection", () => {+ expect(+ modelTranslationRequest(+ base({+ modelElementKind: "assembly",+ partId: undefined,+ configuration: null,+ sourceWvm: "w"+ })+ )+ ).toEqual({+ kind: "assembly",+ options: {+ formatName: "STEP",+ storeInDocument: false,+ configuration: undefined,+ wvm: "w"+ }});- expect(mocks.client.createAssemblyTranslation).toHaveBeenCalledWith(- input.documentId,- input.versionId,- input.modelElementId,- expect.objectContaining({ configuration: input.configuration })- );- expect(mocks.client.createPartStudioTranslation).not.toHaveBeenCalled();});+});- it("gives exact-source replays a stable generation, distinct from another part/configuration", async () => {- for (const variation of [- input,- input,- { ...input, partId: "other-part" },- { ...input, configuration: "Size=Small" }- ]) {- await sync(variation);- }- const ids = mocks.attach.mock.calls.map(([, args]) => args.model.sourceId);- expect(ids[0]).toEqual(expect.any(String));- expect(ids[0]).toBe(ids[1]);+describe("partSourceId", () => {+ it("names a replay of the same released part the same, and another part or configuration differently", () => {+ const ids = [+ base(),+ base(),+ base({ partId: "other-part" }),+ base({ configuration: "Size=Small" })+ ].map(partSourceId);+ expect(ids[0]).toMatch(/^onshape-[0-9a-f]{40}$/);+ expect(ids[1]).toBe(ids[0]);expect(new Set(ids).size).toBe(3);});- it("gives a workspace export a new generation when the part changes", async () => {- const workspace = { ...input, sourceWvm: "w" as const, versionId: "ws-1" };- for (const variation of [- { ...workspace, sourceMicroversionId: "mv-1" },- { ...workspace, sourceMicroversionId: "mv-1" },- { ...workspace, sourceMicroversionId: "mv-2" }- ]) {- await sync(variation);- }- const ids = mocks.attach.mock.calls.map(([, args]) => args.model.sourceId);- expect(ids[0]).toBe(ids[1]);- expect(ids[2]).not.toBe(ids[0]);+ it("names a workspace part by its microversion", () => {+ const workspace = { sourceWvm: "w" as const, versionId: "ws-1" };+ const v1 = partSourceId(+ base({ ...workspace, sourceMicroversionId: "mv-1" })+ );+ expect(+ partSourceId(base({ ...workspace, sourceMicroversionId: "mv-1" }))+ ).toBe(v1);+ expect(+ partSourceId(base({ ...workspace, sourceMicroversionId: "mv-2" }))+ ).not.toBe(v1);});- it("gives a workspace export with no microversion no fixed generation", async () => {- await sync({ ...input, sourceWvm: "w", versionId: "ws-1" });- expect(attachedModel().sourceId).toBeUndefined();+ it.each([+ ["an assembly", { modelElementKind: "assembly", partId: undefined }],+ ["a workspace part with no microversion", { sourceWvm: "w" }]+ ] as const)("gives %s no fixed name", (_case, overrides) => {+ expect(partSourceId(base(overrides))).toBeNull();});});-describe("export economy", () => {- it("skips the export entirely when this source's model already exists", async () => {- mocks.existingModel = { id: "onshape-existing", name: "SADDLE.A.step" };- await sync();- expect(mocks.client.createPartStudioTranslation).not.toHaveBeenCalled();- expect(mocks.client.downloadExternalDataToFile).not.toHaveBeenCalled();- expect(mocks.attach.mock.calls[0]![1]).toMatchObject({- existingModelId: "onshape-existing"- });- });-- it("starts the drawing translations with the model's, before waiting on any", async () => {- await sync({ ...input, drawingElementIds: ["drw-1", "drw-2"] });- const firstPoll = mocks.client.getTranslation.mock.invocationCallOrder[0]!;- for (const create of [- mocks.client.createPartStudioTranslation,- mocks.client.createDrawingTranslation- ]) {- for (const order of create.mock.invocationCallOrder) {- expect(order).toBeLessThan(firstPoll);- }- }- expect(mocks.client.createDrawingTranslation).toHaveBeenCalledTimes(2);- });-- it("sleeps between polls while a translation is still running", async () => {- mocks.client.getTranslation- .mockResolvedValueOnce({ id: "model-t", requestState: "ACTIVE" })- .mockResolvedValueOnce({ id: "model-t", requestState: "ACTIVE" });- await sync();- expect(step.sleep).toHaveBeenCalledTimes(2);- expect(mocks.attach).toHaveBeenCalledOnce();+describe("assemblySourceKeyAt", () => {+ const assembly = base({ modelElementKind: "assembly", partId: undefined });++ it("changes with the document state and the configuration, not otherwise", () => {+ const key = assemblySourceKeyAt(assembly, "microversion-1");+ expect(assemblySourceKeyAt(assembly, "microversion-1")).toBe(key);+ expect(assemblySourceKeyAt(assembly, "microversion-2")).not.toBe(key);+ expect(+ assemblySourceKeyAt(+ { ...assembly, configuration: "Size=Small" },+ "microversion-1"+ )+ ).not.toBe(key);});});-describe("unchanged assemblies", () => {- const workspaceAssembly = {- ...input,- modelElementKind: "assembly",- partId: undefined,- sourceWvm: "w",- versionId: "workspace"- } as const;-- // Pushes once, then points the item at the model that push recorded.- async function pushOnce() {- await sync(workspaceAssembly);- const recorded = mocks.upserts.at(-1)!;- mocks.modelSource = {- externalId: recorded.externalId as string,- metadata: recorded.metadata as { modelUploadId: string }- };- mocks.itemModelUploadId = "new-model";- mocks.existingModel = { id: "new-model", name: "SADDLE.A.step" };- vi.clearAllMocks();- }-- it("records the source an assembly's model was exported from", async () => {- await sync(workspaceAssembly);- expect(mocks.upserts).toEqual([- expect.objectContaining({- entityType: "modelSource",- entityId: "saddle-item",- integration: "onshape",- metadata: { modelUploadId: "new-model" }- })- ]);- });+describe("reusableModelUploadId", () => {+ const recorded = {+ externalId: "source-1",+ metadata: { modelUploadId: "model-1" }+ };- it("skips the export when the workspace has not changed", async () => {- await pushOnce();- await sync(workspaceAssembly);- expect(mocks.client.getCurrentMicroversion).toHaveBeenCalledWith(- "released-document",- "workspace"+ it("reuses the model when the source is unchanged and the item still uses it", () => {+ expect(reusableModelUploadId(recorded, "model-1", "source-1")).toBe(+ "model-1");- expect(mocks.client.createAssemblyTranslation).not.toHaveBeenCalled();- expect(mocks.client.getTranslation).not.toHaveBeenCalled();- expect(mocks.attach.mock.calls[0]![1]).toMatchObject({- existingModelId: "new-model"- });});- it("exports again after any edit to the document", async () => {- await pushOnce();- mocks.client.getCurrentMicroversion.mockResolvedValue("microversion-2");- await sync(workspaceAssembly);- expect(mocks.client.createAssemblyTranslation).toHaveBeenCalledOnce();- });-- it("exports again when the item's model was replaced since", async () => {- await pushOnce();- mocks.itemModelUploadId = "uploaded-by-hand";- await sync(workspaceAssembly);- expect(mocks.client.createAssemblyTranslation).toHaveBeenCalledOnce();- });-- it("exports when the microversion cannot be read", async () => {- await pushOnce();- mocks.client.getCurrentMicroversion.mockRejectedValue(new Error("down"));- await sync(workspaceAssembly);- expect(mocks.client.createAssemblyTranslation).toHaveBeenCalledOnce();+ it.each([+ ["the document changed", recorded, "model-1", "source-2"],+ ["the item's model was replaced", recorded, "uploaded-by-hand", "source-1"],+ ["nothing was recorded", null, "model-1", "source-1"],+ [+ "the record has no model",+ { externalId: "source-1", metadata: {} },+ "model-1",+ "source-1"+ ]+ ] as const)("exports again when %s", (_case, mapping, itemModel, source) => {+ expect(reusableModelUploadId(mapping, itemModel, source)).toBeNull();});});-describe("waiting on a long translation", () => {- const running = { id: "model-t", requestState: "ACTIVE" };+describe("finishedTranslation", () => {+ const done = {+ id: "t1",+ requestState: "DONE",+ resultDocumentId: "export-document",+ resultExternalDataIds: ["file-1", "file-2"],+ name: "SADDLE"+ };- it("waits for the translation webhook once the quick polls are spent", async () => {- for (let i = 0; i < 7; i++) {- mocks.client.getTranslation.mockResolvedValueOnce(running);- }- await sync();- expect(step.sleep).toHaveBeenCalledTimes(5);- expect(mocks.client.createWebhook).toHaveBeenCalledWith({- url: "https://app.carbon.test/api/webhook/onshape/company",- events: ["onshape.model.translation.complete"],- documentId: "released-document",- isTransient: true+ it("reads where a finished export downloads from", () => {+ expect(finishedTranslation(done)).toEqual({+ id: "t1",+ documentId: "export-document",+ foreignId: "file-1",+ name: "SADDLE"});- expect(step.waitForEvent).toHaveBeenCalledOnce();- expect(step.waitForEvent).toHaveBeenCalledWith(- "element-wait-6",- expect.objectContaining({- event: "carbon/onshape-translation-complete",- timeout: 5 * 60 * 1000- })- );- expect(mocks.client.deleteWebhook).toHaveBeenCalledWith("webhook-1");- expect(mocks.attach).toHaveBeenCalledOnce();});- it("keeps polling when no webhook can be registered", async () => {- mocks.client.createWebhook.mockRejectedValue(new Error("unreachable"));- for (let i = 0; i < 8; i++) {- mocks.client.getTranslation.mockResolvedValueOnce(running);- }- await sync();- expect(step.waitForEvent).not.toHaveBeenCalled();- expect(step.sleep).toHaveBeenCalledTimes(8);- expect(mocks.client.deleteWebhook).not.toHaveBeenCalled();+ it("is still waiting on an active translation", () => {+ expect(+ finishedTranslation({ id: "t1", requestState: "ACTIVE" })+ ).toBeNull();});- it("gives up after an hour, and removes its webhook", async () => {- mocks.client.getTranslation.mockResolvedValue(running);- let now = 0;- const clock = vi.spyOn(Date, "now").mockImplementation(() => {- now += 10 * 60 * 1000;- return now;- });- try {- await expect(sync()).rejects.toThrow(/within an hour/);- } finally {- clock.mockRestore();- }- expect(mocks.client.deleteWebhook).toHaveBeenCalledWith("webhook-1");- expect(mocks.attach).not.toHaveBeenCalled();+ it.each([+ ["it failed", { id: "t1", requestState: "FAILED" }],+ ["it is done with no result", { ...done, resultExternalDataIds: [] }]+ ])("fails the sync when %s", (_case, translation) => {+ expect(() => finishedTranslation(translation)).toThrow(/t1/);});+});+describe("translationEventCondition", () => {it("matches only this company's translations", () => {expect(translationEventCondition({ companyId: "co" }, ["t1", "t2"])).toBe('async.data.companyId == "co" && (async.data.translationId == "t1" || async.data.translationId == "t2")');+ });++ it("refuses to interpolate an id that is not plain alphanumeric", () => {expect(translationEventCondition({ companyId: "co" }, ['t" || true'])).toBe(null);});});-describe("with the assembler", () => {+describe("waitForTranslations", () => {+ // Onshape, as far as the wait sees it: each translation finishes after a+ // number of polls, and transient webhooks come and go.+ function onshape(pollsUntilDone: Record<string, number>, webhooks = true) {+ const polls: Record<string, number> = {};+ const state = { polls, created: [] as unknown[], deleted: [] as string[] };+ const client = {+ getTranslation: async (id: string) => {+ polls[id] = (polls[id] ?? 0) + 1;+ return polls[id]! >= (pollsUntilDone[id] ?? Number.POSITIVE_INFINITY)+ ? {+ id,+ requestState: "DONE",+ resultDocumentId: "export-document",+ resultExternalDataIds: [`file-${id}`]+ }+ : { id, requestState: "ACTIVE" };+ },+ createWebhook: async (body: unknown) => {+ if (!webhooks) throw new Error("callback unreachable");+ state.created.push(body);+ return { id: "webhook-1" };+ },+ deleteWebhook: async (id: string) => {+ state.deleted.push(id);+ }+ } as unknown as OnshapeClient;+ return { client, state };+ }++ // Inngest, as far as the wait sees it: step ids are durable (a retry resumes+ // by them), and every wait moves the clock on.+ function inngest() {+ const log: string[] = [];+ const step: Pick<ElementSyncStep, "run" | "sleep" | "waitForEvent"> = {+ run: async (id, fn) => {+ log.push(id);+ return fn();+ },+ sleep: async (id, ms) => {+ log.push(`${id} ${ms}`);+ vi.setSystemTime(Date.now() + ms);+ },+ waitForEvent: async (id, opts) => {+ log.push(`${id} ${opts.event} ${opts.timeout}`);+ vi.setSystemTime(Date.now() + opts.timeout);+ return null;+ }+ };+ return { step, log };+ }++ const input = { companyId: "company", documentId: "released-document" };+beforeEach(() => {- mocks.assemblerEnabled.mockReturnValue(true);- mocks.invoke.mockResolvedValue({- stagedPath: "company/models/onshape-fetch-model-t.step",- size: 13,- contentHash: "xxh3-hash"- });+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(0);});+ afterEach(() => vi.useRealTimers());- it("hands the fetch to its own run; nothing is downloaded here", async () => {- await sync();- expect(mocks.client.downloadExternalDataToFile).not.toHaveBeenCalled();- expect(mocks.invoke).toHaveBeenCalledWith("element-fetch", {- function: { id: "onshape-fetch" },- data: expect.objectContaining({- translationId: "model-t",- documentId: "export-document",- foreignId: "file-model-t",- stagedPath: "company/models/onshape-fetch-model-t.step"- })- });- expect(attachedModel()).toMatchObject({- size: 13,- contentHash: "xxh3-hash"- });+ it("backs off between quick polls and stops polling what has finished", async () => {+ const { client, state } = onshape({ model: 3, drawing: 1 });+ const { step, log } = inngest();++ const finished = await waitForTranslations(+ step,+ async () => client,+ input,+ "SADDLE",+ "el",+ ["model", "drawing"]+ );++ expect(Object.keys(finished).sort()).toEqual(["drawing", "model"]);+ expect(log).toEqual([+ "el-poll-0",+ "el-sleep-0 2000",+ "el-poll-1",+ "el-sleep-1 3000",+ "el-poll-2"+ ]);+ expect(state.polls).toEqual({ model: 3, drawing: 1 });});- it("skips an export the fetch found past the upload limit", async () => {- mocks.invoke.mockResolvedValue({ tooLarge: true });- const result = await sync();- expect(result.tooLarge).toBe(true);- expect(mocks.attach).not.toHaveBeenCalled();+ it("waits on a transient webhook once the six quick polls are spent, then removes it", async () => {+ const { client, state } = onshape({ model: 8 });+ const { step, log } = inngest();++ await waitForTranslations(step, async () => client, input, "SADDLE", "el", [+ "model"+ ]);++ expect(log).toEqual([+ "el-poll-0",+ "el-sleep-0 2000",+ "el-poll-1",+ "el-sleep-1 3000",+ "el-poll-2",+ "el-sleep-2 4500",+ "el-poll-3",+ "el-sleep-3 6750",+ "el-poll-4",+ "el-sleep-4 10125",+ "el-poll-5",+ "el-webhook",+ // One more poll: the export may have finished before the webhook existed.+ "el-poll-6",+ "el-wait-6 carbon/onshape-translation-complete 300000",+ "el-poll-7",+ "el-unwebhook"+ ]);+ expect(state.created).toEqual([+ {+ url: expect.stringMatching(/\/api\/webhook\/onshape\/company$/),+ events: ["onshape.model.translation.complete"],+ documentId: "released-document",+ isTransient: true+ }+ ]);+ expect(state.deleted).toEqual(["webhook-1"]);});-});-describe("released drawing exports", () => {- const drawing = {- companyId: "company",- userId: "user",- itemId: "saddle-item",- sourceDocument: "Part" as const,- documentId: "released-document",- versionId: "released-version",- drawingElementId: "drw-1",- assetBaseName: "SADDLE.A"- };+ it("keeps polling, capped at 30 s, when no webhook can be registered", async () => {+ const { client, state } = onshape({ model: 9 }, false);+ const { step, log } = inngest();- it("translates, waits with step.sleep, then attaches the PDF", async () => {- mocks.client.getTranslation.mockResolvedValueOnce({- id: "drawing-drw-1",- requestState: "ACTIVE"- });- await runOnshapeDrawingSync(step, carbon, drawing, "drawing");- expect(mocks.client.createDrawingTranslation).toHaveBeenCalledOnce();- expect(step.sleep).toHaveBeenCalledOnce();- expect(mocks.attach.mock.calls[0]![1]).toMatchObject({- itemId: "saddle-item",- documents: [{ fileName: "SADDLE.A.pdf" }]- });+ await waitForTranslations(step, async () => client, input, "SADDLE", "el", [+ "model"+ ]);++ expect(log.filter((entry) => entry.includes("-sleep-"))).toEqual([+ "el-sleep-0 2000",+ "el-sleep-1 3000",+ "el-sleep-2 4500",+ "el-sleep-3 6750",+ "el-sleep-4 10125",+ "el-sleep-5 15187.5",+ "el-sleep-6 22781.25",+ "el-sleep-7 30000"+ ]);+ expect(log).not.toContain("el-unwebhook");+ expect(state.deleted).toEqual([]);});- it("skips a PDF past the document limit without failing", async () => {- const { OnshapeAssetTooLargeError } = await import("@carbon/ee/onshape");- mocks.client.downloadExternalData.mockRejectedValue(- new OnshapeAssetTooLargeError("too large")- );- const result = await runOnshapeDrawingSync(- step,- carbon,- drawing,- "drawing"- );- expect(result.tooLarge).toBe(true);- expect(mocks.attach).not.toHaveBeenCalled();+ it("gives up after an hour and still removes its webhook", async () => {+ const { client, state } = onshape({});+ const { step } = inngest();++ await expect(+ waitForTranslations(step, async () => client, input, "SADDLE", "el", [+ "model"+ ])+ ).rejects.toThrow(/model did not finish within an hour/);+ expect(state.deleted).toEqual(["webhook-1"]);});});diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.tsindex acd8f7f02b..ab098c6554 100644--- a/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts+++ b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts@@ -226,7 +226,7 @@ export async function runOnshapeElementSync(const finished = await waitForTranslations(step,- carbon,+ () => onshapeClient(carbon, input),input,label,prefix,@@ -367,7 +367,7 @@ async function onshapeClient(// Missing selection previously exported the entire studio. Fail closed: a// release asset is one part, never an implicit list or whole-studio export.-function assertSelection(input: SyncOnshapeElementInput) {+export function assertSelection(input: SyncOnshapeElementInput) {if (input.modelElementKind === "partstudio" &&(typeof input.partId !== "string" ||@@ -444,6 +444,17 @@ async function assemblySourceKey(return null;}}+ return assemblySourceKeyAt(input, state);+}++/** The assembly source key once its version or microversion (`state`) is known. */+export function assemblySourceKeyAt(+ input: Pick<+ SyncOnshapeElementInput,+ "documentId" | "sourceWvm" | "modelElementId" | "configuration"+ >,+ state: string+): string {return createHash("sha256").update(JSON.stringify([@@ -485,16 +496,12 @@ async function currentModelFromSource(`model source lookup failed: ${(mapping.error ?? item.error)!.message}`);}- const modelUploadId = (- mapping.data?.metadata as { modelUploadId?: unknown } | null- )?.modelUploadId;- if (- mapping.data?.externalId !== source ||- typeof modelUploadId !== "string" ||- item.data?.modelUploadId !== modelUploadId- ) {- return null;- }+ const modelUploadId = reusableModelUploadId(+ mapping.data,+ item.data?.modelUploadId,+ source+ );+ if (!modelUploadId) return null;const model = await carbon.from("modelUpload").select("id, name")@@ -507,6 +514,29 @@ async function currentModelFromSource(return model.data ? { id: model.data.id, name: model.data.name } : null;}+/**+ * The model the last export from `source` produced, when the item still uses+ * it. A different source, or a model replaced since (by hand or another sync),+ * means the export runs again.+ */+export function reusableModelUploadId(+ mapping: { externalId: string | null; metadata: unknown } | null,+ itemModelUploadId: string | null | undefined,+ source: string+): string | null {+ const modelUploadId = (+ mapping?.metadata as { modelUploadId?: unknown } | null+ )?.modelUploadId;+ if (+ mapping?.externalId !== source ||+ typeof modelUploadId !== "string" ||+ itemModelUploadId !== modelUploadId+ ) {+ return null;+ }+ return modelUploadId;+}+/** Remember which source the item's new model came from. Only an* optimization: a failed write means the next push exports again. */async function recordModelSource(@@ -541,10 +571,8 @@ function modelSourceIntegration(input: OnshapeCredentials): string {return input.integrationId ?? "onshape";}-function startModelTranslation(- client: OnshapeClient,- input: SyncOnshapeElementInput-) {+/** The STEP export Onshape is asked for: a whole assembly, or one part. */+export function modelTranslationRequest(input: SyncOnshapeElementInput) {const options = {formatName: "STEP" as const,storeInDocument: false,@@ -552,17 +580,30 @@ function startModelTranslation(wvm: input.sourceWvm ?? "v"};return input.modelElementKind === "assembly"+ ? { kind: "assembly" as const, options }+ : {+ kind: "partstudio" as const,+ options: { ...options, partIds: input.partId! }+ };+}++function startModelTranslation(+ client: OnshapeClient,+ input: SyncOnshapeElementInput+) {+ const request = modelTranslationRequest(input);+ return request.kind === "assembly"? client.createAssemblyTranslation(input.documentId,input.versionId,input.modelElementId,- options+ request.options): client.createPartStudioTranslation(input.documentId,input.versionId,input.modelElementId,- { ...options, partIds: input.partId! }+ request.options);}@@ -575,10 +616,10 @@ function startModelTranslation(* a poll reads the result, so a forged event can do no more than cause a poll.* A failed translation, or an hour without finishing, fails the sync.*/-async function waitForTranslations(+export async function waitForTranslations(step: Pick<ElementSyncStep, "run" | "sleep" | "waitForEvent">,- carbon: CarbonClient,- input: OnshapeCredentials & { documentId: string },+ getClient: () => Promise<OnshapeClient>,+ input: Pick<OnshapeCredentials, "companyId"> & { documentId: string },label: string,prefix: string,ids: string[]@@ -595,7 +636,7 @@ async function waitForTranslations(const poll: { at: number; translations: (FinishedTranslation | null)[] } =await step.run(`${prefix}-poll-${attempt}`, () =>withRateLimitRetry(async () => {- const client = await onshapeClient(carbon, input);+ const client = await getClient();const translations = await Promise.all(waiting.map(async (id) =>finishedTranslation(await client.getTranslation(id))@@ -618,7 +659,7 @@ async function waitForTranslations(if (attempt + 1 >= QUICK_POLLS && webhookId === undefined) {webhookId = await step.run(`${prefix}-webhook`, () =>- registerTranslationWebhook(carbon, input, label)+ registerTranslationWebhook(getClient, input, label));if (webhookId) continue;}@@ -641,7 +682,7 @@ async function waitForTranslations(if (webhookId) {const id = webhookId;await step.run(`${prefix}-unwebhook`, () =>- deleteTranslationWebhook(carbon, input, id, label)+ deleteTranslationWebhook(getClient, id, label));}}@@ -650,12 +691,12 @@ async function waitForTranslations(/** Register a webhook for this document's translation.complete events.* Never throws: without one the sync keeps polling. */async function registerTranslationWebhook(- carbon: CarbonClient,- input: OnshapeCredentials & { documentId: string },+ getClient: () => Promise<OnshapeClient>,+ input: Pick<OnshapeCredentials, "companyId"> & { documentId: string },label: string): Promise<string | null> {try {- const client = await onshapeClient(carbon, input);+ const client = await getClient();const webhook = await client.createWebhook({url: `${getAppUrl()}/api/webhook/onshape/${input.companyId}`,events: ["onshape.model.translation.complete"],@@ -674,13 +715,12 @@ async function registerTranslationWebhook(/** Best-effort: Onshape removes a transient webhook on its own when idle. */async function deleteTranslationWebhook(- carbon: CarbonClient,- input: OnshapeCredentials,+ getClient: () => Promise<OnshapeClient>,webhookId: string,label: string): Promise<void> {try {- const client = await onshapeClient(carbon, input);+ const client = await getClient();await client.deleteWebhook(webhookId);} catch (error) {console.warn(@@ -706,7 +746,7 @@ export function translationEventCondition(return `async.data.companyId == "${input.companyId}" && (${translations})`;}-function finishedTranslation(+export function finishedTranslation(translation: OnshapeTranslation): FinishedTranslation | null {if (translation.requestState === "FAILED") {@@ -853,7 +893,7 @@ export async function runOnshapeDrawingSync();const finished = await waitForTranslations(step,- carbon,+ () => onshapeClient(carbon, input),input,label,prefix,diff --git a/packages/jobs/src/inngest/functions/integrations/ramp-sync-bill.integration.test.ts b/packages/jobs/src/inngest/functions/integrations/ramp-sync-bill.integration.test.tsindex fe4f845ec1..991ef5f3b3 100644--- a/packages/jobs/src/inngest/functions/integrations/ramp-sync-bill.integration.test.ts+++ b/packages/jobs/src/inngest/functions/integrations/ramp-sync-bill.integration.test.ts@@ -20,6 +20,17 @@ import type { RampSyncContext } from "./ramp-sync-shared";// Only the posting operation is substituted. All staging, status transitions,// queries, mappings, FKs and rollback use real Postgres.+const LOCAL_HOSTS = ["localhost", "127.0.0.1", "[::1]"];+const hasLocalDatabase = (() => {+ try {+ return LOCAL_HOSTS.includes(+ new URL(process.env.SUPABASE_DB_URL ?? "").hostname+ );+ } catch {+ return false;+ }+})();+const { post } = vi.hoisted(() => ({ post: vi.fn() }));// A posting with a client runs as the caller behind it, else as the system.vi.mock("@carbon/api/postings.server", () => ({@@ -32,81 +43,52 @@ vi.mock("@carbon/ee/ramp.server", async (original) => ({confirmSyncs: vi.fn()}));-describe.skipIf(process.env.RUN_RAMP_DB_TESTS !== "true")(- "Ramp bill staging (Postgres)",- () => {- let db: ReturnType<typeof getJobDatabaseClient>;- let getCarbonServiceRole: typeof import("@carbon/auth/client.server")["getCarbonServiceRole"];- let syncRampBills: typeof import("./ramp-sync-bill")["syncRampBills"];- const suppliers: string[] = [];- let scope: {- companyId: string;- companyGroupId: string;- currencyCode: string;- accountId: string;- };- beforeAll(async () => {- db = getJobDatabaseClient();- ({ getCarbonServiceRole } = await import("@carbon/auth/client.server"));- ({ syncRampBills } = await import("./ramp-sync-bill"));- scope = (await db- .selectFrom("company")- .innerJoin(- "account",- "account.companyGroupId",- "company.companyGroupId"- )- .select([- "company.id as companyId",- "company.companyGroupId",- "company.baseCurrencyCode as currencyCode",- "account.id as accountId"- ])- .where("account.class", "=", "Expense")- .where("account.active", "=", true)- .where("account.isGroup", "=", false)- .limit(1)- .executeTakeFirstOrThrow()) as typeof scope;- const health = await getCarbonServiceRole()- .from("company")- .select("id")- .eq("id", scope.companyId)- .single();- expect(health.error).toBeNull();- }, 30000);+describe.skipIf(!hasLocalDatabase)("Ramp bill staging (Postgres)", () => {+ let db: ReturnType<typeof getJobDatabaseClient>;+ let getCarbonServiceRole: typeof import("@carbon/auth/client.server")["getCarbonServiceRole"];+ let syncRampBills: typeof import("./ramp-sync-bill")["syncRampBills"];+ const suppliers: string[] = [];+ let scope: {+ companyId: string;+ companyGroupId: string;+ currencyCode: string;+ accountId: string;+ };+ beforeAll(async () => {+ db = getJobDatabaseClient();+ ({ getCarbonServiceRole } = await import("@carbon/auth/client.server"));+ ({ syncRampBills } = await import("./ramp-sync-bill"));+ scope = (await db+ .selectFrom("company")+ .innerJoin("account", "account.companyGroupId", "company.companyGroupId")+ .select([+ "company.id as companyId",+ "company.companyGroupId",+ "company.baseCurrencyCode as currencyCode",+ "account.id as accountId"+ ])+ .where("account.class", "=", "Expense")+ .where("account.active", "=", true)+ .where("account.isGroup", "=", false)+ .limit(1)+ .executeTakeFirstOrThrow()) as typeof scope;+ const health = await getCarbonServiceRole()+ .from("company")+ .select("id")+ .eq("id", scope.companyId)+ .single();+ expect(health.error).toBeNull();+ }, 30000);- afterAll(async () => {- if (!scope || suppliers.length === 0) return;- const invoices = await db- .selectFrom("purchaseInvoice")- .select("id")- .where("companyId", "=", scope.companyId)- .where("supplierId", "in", suppliers)- .execute();- if (invoices.length)- await db- .deleteFrom("externalIntegrationMapping")- .where("companyId", "=", scope.companyId)- .where("integration", "=", "ramp")- .where(- "entityId",- "in",- invoices.map((row) => row.id)- )- .execute();- // These tests only simulate posting by changing status; no edge invocation- // or journal creation is allowed. Reset only this run's exact fixtures.- await db- .updateTable("purchaseInvoice")- .set({ status: "Draft" })- .where("companyId", "=", scope.companyId)- .where("supplierId", "in", suppliers)- .execute();- await db- .deleteFrom("purchaseInvoice")- .where("companyId", "=", scope.companyId)- .where("supplierId", "in", suppliers)- .execute();+ afterAll(async () => {+ if (!scope || suppliers.length === 0) return;+ const invoices = await db+ .selectFrom("purchaseInvoice")+ .select("id")+ .where("companyId", "=", scope.companyId)+ .where("supplierId", "in", suppliers)+ .execute();+ if (invoices.length)await db.deleteFrom("externalIntegrationMapping").where("companyId", "=", scope.companyId)@@ -114,594 +96,610 @@ describe.skipIf(process.env.RUN_RAMP_DB_TESTS !== "true")(.where("entityId","in",- db- .selectFrom("purchaseOrder")- .select("id")- .where("companyId", "=", scope.companyId)- .where("supplierId", "in", suppliers)+ invoices.map((row) => row.id)).execute();- await db- .deleteFrom("purchaseOrder")- .where("companyId", "=", scope.companyId)- .where("supplierId", "in", suppliers)- .execute();- await db- .deleteFrom("supplierInteraction")- .where("companyId", "=", scope.companyId)- .where("supplierId", "in", suppliers)- .execute();- await db- .deleteFrom("supplier")- .where("companyId", "=", scope.companyId)- .where("id", "in", suppliers)- .execute();- }, 30000);+ // These tests only simulate posting by changing status; no edge invocation+ // or journal creation is allowed. Reset only this run's exact fixtures.+ await db+ .updateTable("purchaseInvoice")+ .set({ status: "Draft" })+ .where("companyId", "=", scope.companyId)+ .where("supplierId", "in", suppliers)+ .execute();+ await db+ .deleteFrom("purchaseInvoice")+ .where("companyId", "=", scope.companyId)+ .where("supplierId", "in", suppliers)+ .execute();+ await db+ .deleteFrom("externalIntegrationMapping")+ .where("companyId", "=", scope.companyId)+ .where("integration", "=", "ramp")+ .where(+ "entityId",+ "in",+ db+ .selectFrom("purchaseOrder")+ .select("id")+ .where("companyId", "=", scope.companyId)+ .where("supplierId", "in", suppliers)+ )+ .execute();+ await db+ .deleteFrom("purchaseOrder")+ .where("companyId", "=", scope.companyId)+ .where("supplierId", "in", suppliers)+ .execute();+ await db+ .deleteFrom("supplierInteraction")+ .where("companyId", "=", scope.companyId)+ .where("supplierId", "in", suppliers)+ .execute();+ await db+ .deleteFrom("supplier")+ .where("companyId", "=", scope.companyId)+ .where("id", "in", suppliers)+ .execute();+ }, 30000);- async function fixture() {- const token = `RAMP-BILL-TEST-${crypto.randomUUID()}`;- const supplier = await db- .insertInto("supplier")- .values({- name: token,- companyId: scope.companyId,- createdBy: "system"- })- .returning("id")- .executeTakeFirstOrThrow();- suppliers.push(supplier.id);- const client = getCarbonServiceRole();- post.mockReset();- post.mockImplementation(- async (_fields: unknown, input: { invoiceId: string }) => {- await db- .updateTable("purchaseInvoice")- .set({ status: "Draft" })- .where("companyId", "=", scope.companyId)- .where("id", "=", input.invoiceId)- .execute();- return {- data: null,- error: new ServerFnError("simulated posting failure")- };- }- );- const ctx: RampSyncContext = {- client,- db,+ async function fixture() {+ const token = `RAMP-BILL-TEST-${crypto.randomUUID()}`;+ const supplier = await db+ .insertInto("supplier")+ .values({+ name: token,companyId: scope.companyId,- companyGroupId: scope.companyGroupId,- baseCurrency: scope.currencyCode,- mapping: createMappingService(db, scope.companyId),- decimalsCache: new Map(),- exchangeRateCache: new Map(),- createdBy: "system",- trigger: "event",- metadata: { sync: { pullBills: true } } as RampSyncContext["metadata"]- };- const bill: RampBill = {- id: token,- invoice_number: token,- issued_at: "2026-09-10",- due_at: "2026-09-11",- currency_code: scope.currencyCode,- amount: { amount: 10000, currency_code: scope.currencyCode },- vendor: { name: token },- line_items: [- {- amount: { amount: 10000, currency_code: scope.currencyCode },- memo: token,- accounting_field_selections: [- {- external_id: scope.accountId,- category_info: { type: "GL_ACCOUNT" }- }- ]- }- ]- };- const ramp = {- async *listBills() {- yield [bill];+ createdBy: "system"+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ suppliers.push(supplier.id);+ const client = getCarbonServiceRole();+ post.mockReset();+ post.mockImplementation(+ async (_fields: unknown, input: { invoiceId: string }) => {+ await db+ .updateTable("purchaseInvoice")+ .set({ status: "Draft" })+ .where("companyId", "=", scope.companyId)+ .where("id", "=", input.invoiceId)+ .execute();+ return {+ data: null,+ error: new ServerFnError("simulated posting failure")+ };+ }+ );+ const ctx: RampSyncContext = {+ client,+ db,+ companyId: scope.companyId,+ companyGroupId: scope.companyGroupId,+ baseCurrency: scope.currencyCode,+ mapping: createMappingService(db, scope.companyId),+ decimalsCache: new Map(),+ exchangeRateCache: new Map(),+ createdBy: "system",+ trigger: "event",+ metadata: { sync: { pullBills: true } } as RampSyncContext["metadata"]+ };+ const bill: RampBill = {+ id: token,+ invoice_number: token,+ issued_at: "2026-09-10",+ due_at: "2026-09-11",+ currency_code: scope.currencyCode,+ amount: { amount: 10000, currency_code: scope.currencyCode },+ vendor: { name: token },+ line_items: [+ {+ amount: { amount: 10000, currency_code: scope.currencyCode },+ memo: token,+ accounting_field_selections: [+ {+ external_id: scope.accountId,+ category_info: { type: "GL_ACCOUNT" }+ }+ ]+ }+ ]+ };+ const ramp = {+ async *listBills() {+ yield [bill];+ }+ } as RampClient;+ const args: RampBillDraft = {+ companyId: scope.companyId,+ sourceId: token,+ supplierId: supplier.id,+ supplierReference: token,+ currencyCode: scope.currencyCode,+ exchangeRate: 1,+ decimals: 2,+ totalAmount: 100,+ dateIssued: "2026-09-10",+ dateDue: "2026-09-11",+ lines: [+ {+ accountId: scope.accountId,+ costCenterId: null,+ projectId: null,+ amount: 100,+ description: token}- } as RampClient;- const args: RampBillDraft = {+ ]+ };+ return { token, supplierId: supplier.id, ctx, bill, ramp, args, post };+ }++ async function purchaseOrderFixture() {+ const fixtureData = await fixture();+ const interaction = await db+ .insertInto("supplierInteraction")+ .values({companyId: scope.companyId,- sourceId: token,- supplierId: supplier.id,- supplierReference: token,+ supplierId: fixtureData.supplierId+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ const po = await db+ .insertInto("purchaseOrder")+ .values({+ companyId: scope.companyId,+ createdBy: "system",+ purchaseOrderId: fixtureData.token,+ supplierId: fixtureData.supplierId,+ supplierInteractionId: interaction.id,currencyCode: scope.currencyCode,- exchangeRate: 1,- decimals: 2,- totalAmount: 100,- dateIssued: "2026-09-10",- dateDue: "2026-09-11",- lines: [- {- accountId: scope.accountId,- costCenterId: null,- projectId: null,- amount: 100,- description: token- }- ]- };- return { token, supplierId: supplier.id, ctx, bill, ramp, args, post };- }-- async function purchaseOrderFixture() {- const fixtureData = await fixture();- const interaction = await db- .insertInto("supplierInteraction")- .values({- companyId: scope.companyId,- supplierId: fixtureData.supplierId- })- .returning("id")- .executeTakeFirstOrThrow();- const po = await db- .insertInto("purchaseOrder")- .values({+ status: "To Receive and Invoice"+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ const poLines = await db+ .insertInto("purchaseOrderLine")+ .values(+ [1, 2].map((index) => ({companyId: scope.companyId,createdBy: "system",- purchaseOrderId: fixtureData.token,- supplierId: fixtureData.supplierId,- supplierInteractionId: interaction.id,- currencyCode: scope.currencyCode,- status: "To Receive and Invoice"- })- .returning("id")- .executeTakeFirstOrThrow();- const poLines = await db- .insertInto("purchaseOrderLine")- .values(- [1, 2].map((index) => ({- companyId: scope.companyId,- createdBy: "system",- purchaseOrderId: po.id,- purchaseOrderLineType: "G/L Account" as const,- purchaseQuantity: 10,- supplierUnitPrice: 20,- accountId: scope.accountId,- sortOrder: index- }))- )- .returning("id")- .execute();- const remotePoId = `po-${fixtureData.token}`;- await fixtureData.ctx.mapping.link(- "purchaseOrder",- po.id,- "ramp",- remotePoId- );- fixtureData.bill.purchase_order_id = remotePoId;- fixtureData.bill.line_items![0]!.purchase_order_line_item_id =- "remote-line-1";- const request = vi.fn(async () => ({- line_items: [{ id: "remote-line-1", external_id: poLines[0]!.id }]- }));- Object.assign(fixtureData.ramp, { request });- return { ...fixtureData, po, poLines, remotePoId, request };- }+ purchaseOrderId: po.id,+ purchaseOrderLineType: "G/L Account" as const,+ purchaseQuantity: 10,+ supplierUnitPrice: 20,+ accountId: scope.accountId,+ sortOrder: index+ }))+ )+ .returning("id")+ .execute();+ const remotePoId = `po-${fixtureData.token}`;+ await fixtureData.ctx.mapping.link(+ "purchaseOrder",+ po.id,+ "ramp",+ remotePoId+ );+ fixtureData.bill.purchase_order_id = remotePoId;+ fixtureData.bill.line_items![0]!.purchase_order_line_item_id =+ "remote-line-1";+ const request = vi.fn(async () => ({+ line_items: [{ id: "remote-line-1", external_id: poLines[0]!.id }]+ }));+ Object.assign(fixtureData.ramp, { request });+ return { ...fixtureData, po, poLines, remotePoId, request };+ }- it("keeps one mapped Draft after a posting failure and retries that same Draft", async () => {- const { token, ctx, ramp, post } = await fixture();- await syncRampBills(ctx, ramp, undefined);- await syncRampBills(ctx, ramp, undefined);- const invoices = await db- .selectFrom("purchaseInvoice")- .select(["id", "status"])- .where("companyId", "=", scope.companyId)- .where("supplierReference", "=", token)- .execute();- expect(invoices).toHaveLength(1);- expect(invoices[0]?.status).toBe("Draft");- expect(post).toHaveBeenCalledTimes(2);- expect(await ctx.mapping.getEntityId("ramp", token, "bill")).toBe(- invoices[0]?.id- );- }, 30000);+ it("keeps one mapped Draft after a posting failure and retries that same Draft", async () => {+ const { token, ctx, ramp, post } = await fixture();+ await syncRampBills(ctx, ramp, undefined);+ await syncRampBills(ctx, ramp, undefined);+ const invoices = await db+ .selectFrom("purchaseInvoice")+ .select(["id", "status"])+ .where("companyId", "=", scope.companyId)+ .where("supplierReference", "=", token)+ .execute();+ expect(invoices).toHaveLength(1);+ expect(invoices[0]?.status).toBe("Draft");+ expect(post).toHaveBeenCalledTimes(2);+ expect(await ctx.mapping.getEntityId("ramp", token, "bill")).toBe(+ invoices[0]?.id+ );+ }, 30000);- it("converges simultaneous deliveries of one source bill to one mapped Draft", async () => {- const { token, ctx, ramp } = await fixture();- await Promise.all([- syncRampBills(ctx, ramp, undefined),- syncRampBills(ctx, ramp, undefined)- ]);- const invoices = await db- .selectFrom("purchaseInvoice")- .select("id")- .where("companyId", "=", scope.companyId)- .where("supplierReference", "=", token)- .execute();- expect(invoices).toHaveLength(1);- expect(await ctx.mapping.getEntityId("ramp", token, "bill")).toBe(- invoices[0]?.id- );- }, 30000);+ it("converges simultaneous deliveries of one source bill to one mapped Draft", async () => {+ const { token, ctx, ramp } = await fixture();+ await Promise.all([+ syncRampBills(ctx, ramp, undefined),+ syncRampBills(ctx, ramp, undefined)+ ]);+ const invoices = await db+ .selectFrom("purchaseInvoice")+ .select("id")+ .where("companyId", "=", scope.companyId)+ .where("supplierReference", "=", token)+ .execute();+ expect(invoices).toHaveLength(1);+ expect(await ctx.mapping.getEntityId("ramp", token, "bill")).toBe(+ invoices[0]?.id+ );+ }, 30000);- it("rolls back the header, interaction, delivery and lines when the final mapping write fails", async () => {- const { token, args, supplierId } = await fixture();- const name = `ramp_bill_fail_${crypto.randomUUID().replaceAll("-", "")}`;- // Fault is guarded by this test's unguessable source id, never global.+ it("rolls back the header, interaction, delivery and lines when the final mapping write fails", async () => {+ const { token, args, supplierId } = await fixture();+ const name = `ramp_bill_fail_${crypto.randomUUID().replaceAll("-", "")}`;+ // Fault is guarded by this test's unguessable source id, never global.+ await sql+ .raw(+ `CREATE FUNCTION ${name}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'ramp_bill_mapping_fault'; END $$`+ )+ .execute(db);+ try {await sql.raw(- `CREATE FUNCTION ${name}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'ramp_bill_mapping_fault'; END $$`+ `CREATE TRIGGER ${name} BEFORE INSERT ON "externalIntegrationMapping" FOR EACH ROW WHEN (NEW."externalId" = '${token}') EXECUTE FUNCTION ${name}()`).execute(db);- try {- await sql- .raw(- `CREATE TRIGGER ${name} BEFORE INSERT ON "externalIntegrationMapping" FOR EACH ROW WHEN (NEW."externalId" = '${token}') EXECUTE FUNCTION ${name}()`- )- .execute(db);- await expect(stageOrResumeRampBill(db, args)).rejects.toThrow(- "ramp_bill_mapping_fault"- );- expect(- await db- .selectFrom("purchaseInvoice")- .select("id")- .where("companyId", "=", scope.companyId)- .where("supplierId", "=", supplierId)- .execute()- ).toHaveLength(0);- expect(- await db- .selectFrom("supplierInteraction")- .select("id")- .where("companyId", "=", scope.companyId)- .where("supplierId", "=", supplierId)- .execute()- ).toHaveLength(0);- expect(- await createMappingService(db, scope.companyId).getEntityId(- "ramp",- token,- "bill"- )- ).toBeNull();- } finally {- await sql- .raw(`DROP TRIGGER IF EXISTS ${name} ON "externalIntegrationMapping"`)- .execute(db);- await sql.raw(`DROP FUNCTION ${name}()`).execute(db);- }- }, 30000);-- it("resumes a committed Draft after a crash and confirms only after an observed post", async () => {- const { args, ctx, ramp, post, token } = await fixture();- const staged = await stageOrResumeRampBill(db, args); // crash before posting- post.mockImplementationOnce(async () => {+ await expect(stageOrResumeRampBill(db, args)).rejects.toThrow(+ "ramp_bill_mapping_fault"+ );+ expect(await db- .updateTable("purchaseInvoice")- .set({ status: "Open" })+ .selectFrom("purchaseInvoice")+ .select("id").where("companyId", "=", scope.companyId)- .where("id", "=", staged.invoiceRowId)- .execute();- return {- data: null,- error: new ServerFnError("response lost after commit")- };- });- vi.mocked(confirmSyncs).mockClear();- expect(await syncRampBills(ctx, ramp, undefined)).toMatchObject({- created: 1,- failed: 0- });+ .where("supplierId", "=", supplierId)+ .execute()+ ).toHaveLength(0);expect(- vi.mocked(confirmSyncs).mock.calls.at(-1)?.[2].successful- ).toMatchObject([{ id: token }]);- expect(await ctx.mapping.getEntityId("ramp", token, "bill")).toBe(- staged.invoiceRowId- );- expect(post).toHaveBeenCalledTimes(1);- }, 30000);-- it.each(["Pending", "Voided"] as const)(- "never posts or confirms a mapped %s invoice",- async (status) => {- const { args, ctx, ramp, post } = await fixture();- const staged = await stageOrResumeRampBill(db, args);await db- .updateTable("purchaseInvoice")- .set({ status })+ .selectFrom("supplierInteraction")+ .select("id").where("companyId", "=", scope.companyId)- .where("id", "=", staged.invoiceRowId)- .execute();- vi.mocked(confirmSyncs).mockClear();- expect(await syncRampBills(ctx, ramp, undefined)).toMatchObject({- created: 0,- reconfirmed: 0,- failed: 1- });- expect(- vi.mocked(confirmSyncs).mock.calls.at(-1)?.[2].successful- ).toEqual([]);- expect(post).not.toHaveBeenCalled();- },- 30000- );-- it("adopts one exact legacy system Draft without changing its source mapping on collision", async () => {- const { args, ctx } = await fixture();- const staged = await stageOrResumeRampBill(db, args);- await ctx.mapping.unlink("bill", staged.invoiceRowId, "ramp");- expect((await stageOrResumeRampBill(db, args)).invoiceRowId).toBe(- staged.invoiceRowId- );- await expect(- stageOrResumeRampBill(db, {- ...args,- sourceId: `${args.sourceId}-other`- })- ).rejects.toThrow("different Ramp bill");- expect(await ctx.mapping.getEntityId("ramp", args.sourceId, "bill")).toBe(- staged.invoiceRowId- );- }, 30000);-- it("uses Ramp-covered PO amounts, removes uncovered PO lines and adds an exactly coded adjustment", async () => {- const { ctx, ramp, bill, po, poLines } = await purchaseOrderFixture();- bill.amount = { amount: 10500, currency_code: scope.currencyCode };- await syncRampBills(ctx, ramp, undefined);- const id = await ctx.mapping.getEntityId("ramp", bill.id, "bill");- expect(id).toBeTruthy();- const lines = await db- .selectFrom("purchaseInvoiceLine")- .selectAll()- .where("companyId", "=", scope.companyId)- .where("invoiceId", "=", id!)- .orderBy("sortOrder")- .execute();- expect(lines).toHaveLength(2);- expect(lines[0]).toMatchObject({- purchaseOrderId: po.id,- purchaseOrderLineId: poLines[0]!.id,- quantity: 5,- supplierUnitPrice: 20- });- expect(lines[1]).toMatchObject({- purchaseOrderId: null,- purchaseOrderLineId: null,- accountId: scope.accountId,- quantity: 1,- supplierUnitPrice: 5- });+ .where("supplierId", "=", supplierId)+ .execute()+ ).toHaveLength(0);expect(- lines.reduce(- (sum, line) => sum + line.quantity * line.supplierUnitPrice,- 0+ await createMappingService(db, scope.companyId).getEntityId(+ "ramp",+ token,+ "bill")- ).toBe(105);- }, 30000);+ ).toBeNull();+ } finally {+ await sql+ .raw(`DROP TRIGGER IF EXISTS ${name} ON "externalIntegrationMapping"`)+ .execute(db);+ await sql.raw(`DROP FUNCTION ${name}()`).execute(db);+ }+ }, 30000);- it("posts multi-PO bills standalone with a memo, posting only that bill", async () => {- const { ctx, ramp, bill, remotePoId, request, post } =- await purchaseOrderFixture();- bill.purchase_order_ids = [remotePoId, "another-po"];- await syncRampBills(ctx, ramp, undefined);- const id = await ctx.mapping.getEntityId("ramp", bill.id, "bill");- expect(id).toBeTruthy();- const invoice = await db- .selectFrom("purchaseInvoice")- .select("internalNotes")- .where("companyId", "=", scope.companyId)- .where("id", "=", id!)- .executeTakeFirstOrThrow();- expect(JSON.stringify(invoice.internalNotes)).toContain(- "posted standalone"- );- const lines = await db- .selectFrom("purchaseInvoiceLine")- .select("purchaseOrderId")+ it("resumes a committed Draft after a crash and confirms only after an observed post", async () => {+ const { args, ctx, ramp, post, token } = await fixture();+ const staged = await stageOrResumeRampBill(db, args); // crash before posting+ post.mockImplementationOnce(async () => {+ await db+ .updateTable("purchaseInvoice")+ .set({ status: "Open" }).where("companyId", "=", scope.companyId)- .where("invoiceId", "=", id!)+ .where("id", "=", staged.invoiceRowId).execute();- expect(lines.every((line) => line.purchaseOrderId === null)).toBe(true);- expect(request).not.toHaveBeenCalled();- expect(post.mock.calls.every(([, input]) => input.invoiceId === id)).toBe(- true- );- }, 30000);-- it("does not adopt an unrelated Draft just because it references the same PO", async () => {- const { ctx, ramp, bill, args, po, poLines } =- await purchaseOrderFixture();- const unrelated = await stageOrResumeRampBill(db, {- ...args,- sourceId: `${args.sourceId}-unrelated`,- supplierReference: "Other supplier reference",- purchaseOrderId: po.id,- lines: [{ ...args.lines[0]!, purchaseOrderLineId: poLines[1]!.id }]- });- await syncRampBills(ctx, ramp, undefined);- expect(await ctx.mapping.getEntityId("ramp", bill.id, "bill")).not.toBe(- unrelated.invoiceRowId- );- const preserved = await db- .selectFrom("purchaseInvoice")- .select("supplierReference")- .where("companyId", "=", scope.companyId)- .where("id", "=", unrelated.invoiceRowId)- .executeTakeFirstOrThrow();- expect(preserved.supplierReference).toBe("Other supplier reference");- }, 30000);+ return {+ data: null,+ error: new ServerFnError("response lost after commit")+ };+ });+ vi.mocked(confirmSyncs).mockClear();+ expect(await syncRampBills(ctx, ramp, undefined)).toMatchObject({+ created: 1,+ failed: 0+ });+ expect(+ vi.mocked(confirmSyncs).mock.calls.at(-1)?.[2].successful+ ).toMatchObject([{ id: token }]);+ expect(await ctx.mapping.getEntityId("ramp", token, "bill")).toBe(+ staged.invoiceRowId+ );+ expect(post).toHaveBeenCalledTimes(1);+ }, 30000);- it("rejects an incomplete legacy Draft instead of creating or confirming another invoice", async () => {+ it.each(["Pending", "Voided"] as const)(+ "never posts or confirms a mapped %s invoice",+ async (status) => {const { args, ctx, ramp, post } = await fixture();const staged = await stageOrResumeRampBill(db, args);- await ctx.mapping.unlink("bill", staged.invoiceRowId, "ramp");await db- .deleteFrom("purchaseInvoiceDelivery")+ .updateTable("purchaseInvoice")+ .set({ status }).where("companyId", "=", scope.companyId).where("id", "=", staged.invoiceRowId).execute();+ vi.mocked(confirmSyncs).mockClear();expect(await syncRampBills(ctx, ramp, undefined)).toMatchObject({created: 0,reconfirmed: 0,failed: 1});- expect(- await ctx.mapping.getEntityId("ramp", args.sourceId, "bill")- ).toBeNull();+ expect(vi.mocked(confirmSyncs).mock.calls.at(-1)?.[2].successful).toEqual(+ []+ );expect(post).not.toHaveBeenCalled();- }, 30000);+ },+ 30000+ );- it("refuses ambiguous matching legacy Drafts", async () => {- const { args, ctx } = await fixture();- const first = await stageOrResumeRampBill(db, args);- const second = await stageOrResumeRampBill(db, {+ it("adopts one exact legacy system Draft without changing its source mapping on collision", async () => {+ const { args, ctx } = await fixture();+ const staged = await stageOrResumeRampBill(db, args);+ await ctx.mapping.unlink("bill", staged.invoiceRowId, "ramp");+ expect((await stageOrResumeRampBill(db, args)).invoiceRowId).toBe(+ staged.invoiceRowId+ );+ await expect(+ stageOrResumeRampBill(db, {...args,- sourceId: `${args.sourceId}-second`,- supplierReference: "Initially distinct"- });- await ctx.mapping.unlink("bill", first.invoiceRowId, "ramp");- await ctx.mapping.unlink("bill", second.invoiceRowId, "ramp");- await db- .updateTable("purchaseInvoice")- .set({ supplierReference: args.supplierReference })- .where("companyId", "=", scope.companyId)- .where("id", "=", second.invoiceRowId)- .execute();- await expect(stageOrResumeRampBill(db, args)).rejects.toThrow(- "Ambiguous legacy"- );- expect(- await ctx.mapping.getEntityId("ramp", args.sourceId, "bill")- ).toBeNull();- }, 30000);+ sourceId: `${args.sourceId}-other`+ })+ ).rejects.toThrow("different Ramp bill");+ expect(await ctx.mapping.getEntityId("ramp", args.sourceId, "bill")).toBe(+ staged.invoiceRowId+ );+ }, 30000);- it("allows only one of two concurrent source ids to adopt a valid legacy Draft", async () => {- const { args, ctx } = await fixture();- const staged = await stageOrResumeRampBill(db, args);- await ctx.mapping.unlink("bill", staged.invoiceRowId, "ramp");- const outcomes = await Promise.allSettled([- stageOrResumeRampBill(db, args),- stageOrResumeRampBill(db, {- ...args,- sourceId: `${args.sourceId}-other`- })- ]);- expect(- outcomes.filter((outcome) => outcome.status === "fulfilled")- ).toHaveLength(1);- const failed = outcomes.find(- (outcome) => outcome.status === "rejected"- ) as PromiseRejectedResult;- expect(failed.reason.message).toContain("different Ramp bill");- }, 30000);+ it("uses Ramp-covered PO amounts, removes uncovered PO lines and adds an exactly coded adjustment", async () => {+ const { ctx, ramp, bill, po, poLines } = await purchaseOrderFixture();+ bill.amount = { amount: 10500, currency_code: scope.currencyCode };+ await syncRampBills(ctx, ramp, undefined);+ const id = await ctx.mapping.getEntityId("ramp", bill.id, "bill");+ expect(id).toBeTruthy();+ const lines = await db+ .selectFrom("purchaseInvoiceLine")+ .selectAll()+ .where("companyId", "=", scope.companyId)+ .where("invoiceId", "=", id!)+ .orderBy("sortOrder")+ .execute();+ expect(lines).toHaveLength(2);+ expect(lines[0]).toMatchObject({+ purchaseOrderId: po.id,+ purchaseOrderLineId: poLines[0]!.id,+ quantity: 5,+ supplierUnitPrice: 20+ });+ expect(lines[1]).toMatchObject({+ purchaseOrderId: null,+ purchaseOrderLineId: null,+ accountId: scope.accountId,+ quantity: 1,+ supplierUnitPrice: 5+ });+ expect(+ lines.reduce(+ (sum, line) => sum + line.quantity * line.supplierUnitPrice,+ 0+ )+ ).toBe(105);+ }, 30000);- it("refuses a mapped PO Draft whose equal total hides a different invoiced quantity", async () => {- const { args, po, poLines } = await purchaseOrderFixture();- const linked = {- ...args,- purchaseOrderId: po.id,- lines: [- {- ...args.lines[0]!,- purchaseOrderLineId: poLines[0]!.id,- quantity: 5- }- ]- };- const staged = await stageOrResumeRampBill(db, linked);- await db- .updateTable("purchaseInvoiceLine")- .set({ quantity: 10, supplierUnitPrice: 10 })- .where("companyId", "=", scope.companyId)- .where("invoiceId", "=", staged.invoiceRowId)- .execute();- await expect(stageOrResumeRampBill(db, linked)).rejects.toThrow(- "complete Ramp bill lines"- );- }, 30000);+ it("posts multi-PO bills standalone with a memo, posting only that bill", async () => {+ const { ctx, ramp, bill, remotePoId, request, post } =+ await purchaseOrderFixture();+ bill.purchase_order_ids = [remotePoId, "another-po"];+ await syncRampBills(ctx, ramp, undefined);+ const id = await ctx.mapping.getEntityId("ramp", bill.id, "bill");+ expect(id).toBeTruthy();+ const invoice = await db+ .selectFrom("purchaseInvoice")+ .select("internalNotes")+ .where("companyId", "=", scope.companyId)+ .where("id", "=", id!)+ .executeTakeFirstOrThrow();+ expect(JSON.stringify(invoice.internalNotes)).toContain(+ "posted standalone"+ );+ const lines = await db+ .selectFrom("purchaseInvoiceLine")+ .select("purchaseOrderId")+ .where("companyId", "=", scope.companyId)+ .where("invoiceId", "=", id!)+ .execute();+ expect(lines.every((line) => line.purchaseOrderId === null)).toBe(true);+ expect(request).not.toHaveBeenCalled();+ expect(post.mock.calls.every(([, input]) => input.invoiceId === id)).toBe(+ true+ );+ }, 30000);- it("does not adopt an unmapped posted invoice merely because supplier reference and total match", async () => {- const { args, ctx } = await fixture();- const staged = await stageOrResumeRampBill(db, args);- await ctx.mapping.unlink("bill", staged.invoiceRowId, "ramp");- await db- .updateTable("purchaseInvoiceLine")- .set({ supplierUnitPrice: 50 })- .where("companyId", "=", scope.companyId)- .where("invoiceId", "=", staged.invoiceRowId)- .execute();- await db- .insertInto("purchaseInvoiceLine")- .values({- invoiceId: staged.invoiceRowId,- companyId: scope.companyId,- createdBy: "system",- invoiceLineType: "G/L Account",- accountId: scope.accountId,- quantity: 1,- supplierUnitPrice: 50,- sortOrder: 2- })- .execute();- await db- .updateTable("purchaseInvoice")- .set({ status: "Open" })- .where("companyId", "=", scope.companyId)- .where("id", "=", staged.invoiceRowId)- .execute();- await expect(stageOrResumeRampBill(db, args)).rejects.toThrow(- "not a valid legacy"- );- expect(- await ctx.mapping.getEntityId("ramp", args.sourceId, "bill")- ).toBeNull();- }, 30000);+ it("does not adopt an unrelated Draft just because it references the same PO", async () => {+ const { ctx, ramp, bill, args, po, poLines } = await purchaseOrderFixture();+ const unrelated = await stageOrResumeRampBill(db, {+ ...args,+ sourceId: `${args.sourceId}-unrelated`,+ supplierReference: "Other supplier reference",+ purchaseOrderId: po.id,+ lines: [{ ...args.lines[0]!, purchaseOrderLineId: poLines[1]!.id }]+ });+ await syncRampBills(ctx, ramp, undefined);+ expect(await ctx.mapping.getEntityId("ramp", bill.id, "bill")).not.toBe(+ unrelated.invoiceRowId+ );+ const preserved = await db+ .selectFrom("purchaseInvoice")+ .select("supplierReference")+ .where("companyId", "=", scope.companyId)+ .where("id", "=", unrelated.invoiceRowId)+ .executeTakeFirstOrThrow();+ expect(preserved.supplierReference).toBe("Other supplier reference");+ }, 30000);- it("stores foreign principal in supplier fields and lets generated fields convert to base", async () => {- const { args } = await fixture();- const currency = await db- .selectFrom("currency")- .select("code")- .where("companyGroupId", "=", scope.companyGroupId)- .where("code", "!=", scope.currencyCode)- .executeTakeFirstOrThrow();- const staged = await stageOrResumeRampBill(db, {- ...args,- currencyCode: currency.code,- exchangeRate: 2- });- const line = await db- .selectFrom("purchaseInvoiceLine")- .select([- "supplierUnitPrice",- "unitPrice",- "totalAmount",- "exchangeRate"- ])- .where("companyId", "=", scope.companyId)- .where("invoiceId", "=", staged.invoiceRowId)- .executeTakeFirstOrThrow();- expect(line).toMatchObject({- supplierUnitPrice: 100,- unitPrice: 50,- totalAmount: 50,- exchangeRate: 2- });- }, 30000);+ it("rejects an incomplete legacy Draft instead of creating or confirming another invoice", async () => {+ const { args, ctx, ramp, post } = await fixture();+ const staged = await stageOrResumeRampBill(db, args);+ await ctx.mapping.unlink("bill", staged.invoiceRowId, "ramp");+ await db+ .deleteFrom("purchaseInvoiceDelivery")+ .where("companyId", "=", scope.companyId)+ .where("id", "=", staged.invoiceRowId)+ .execute();+ expect(await syncRampBills(ctx, ramp, undefined)).toMatchObject({+ created: 0,+ reconfirmed: 0,+ failed: 1+ });+ expect(+ await ctx.mapping.getEntityId("ramp", args.sourceId, "bill")+ ).toBeNull();+ expect(post).not.toHaveBeenCalled();+ }, 30000);++ it("refuses ambiguous matching legacy Drafts", async () => {+ const { args, ctx } = await fixture();+ const first = await stageOrResumeRampBill(db, args);+ const second = await stageOrResumeRampBill(db, {+ ...args,+ sourceId: `${args.sourceId}-second`,+ supplierReference: "Initially distinct"+ });+ await ctx.mapping.unlink("bill", first.invoiceRowId, "ramp");+ await ctx.mapping.unlink("bill", second.invoiceRowId, "ramp");+ await db+ .updateTable("purchaseInvoice")+ .set({ supplierReference: args.supplierReference })+ .where("companyId", "=", scope.companyId)+ .where("id", "=", second.invoiceRowId)+ .execute();+ await expect(stageOrResumeRampBill(db, args)).rejects.toThrow(+ "Ambiguous legacy"+ );+ expect(+ await ctx.mapping.getEntityId("ramp", args.sourceId, "bill")+ ).toBeNull();+ }, 30000);- it("rejects a second bill reserving the same unposted PO line", async () => {- const { args, po, poLines } = await purchaseOrderFixture();- const linked = {+ it("allows only one of two concurrent source ids to adopt a valid legacy Draft", async () => {+ const { args, ctx } = await fixture();+ const staged = await stageOrResumeRampBill(db, args);+ await ctx.mapping.unlink("bill", staged.invoiceRowId, "ramp");+ const outcomes = await Promise.allSettled([+ stageOrResumeRampBill(db, args),+ stageOrResumeRampBill(db, {...args,- purchaseOrderId: po.id,- lines: [{ ...args.lines[0]!, purchaseOrderLineId: poLines[0]!.id }]- };- await stageOrResumeRampBill(db, linked);- await expect(- stageOrResumeRampBill(db, {- ...linked,- sourceId: `${args.sourceId}-second`,- supplierReference: "Another bill"- })- ).rejects.toThrow("already reserved");- }, 30000);- }-);+ sourceId: `${args.sourceId}-other`+ })+ ]);+ expect(+ outcomes.filter((outcome) => outcome.status === "fulfilled")+ ).toHaveLength(1);+ const failed = outcomes.find(+ (outcome) => outcome.status === "rejected"+ ) as PromiseRejectedResult;+ expect(failed.reason.message).toContain("different Ramp bill");+ }, 30000);++ it("refuses a mapped PO Draft whose equal total hides a different invoiced quantity", async () => {+ const { args, po, poLines } = await purchaseOrderFixture();+ const linked = {+ ...args,+ purchaseOrderId: po.id,+ lines: [+ {+ ...args.lines[0]!,+ purchaseOrderLineId: poLines[0]!.id,+ quantity: 5+ }+ ]+ };+ const staged = await stageOrResumeRampBill(db, linked);+ await db+ .updateTable("purchaseInvoiceLine")+ .set({ quantity: 10, supplierUnitPrice: 10 })+ .where("companyId", "=", scope.companyId)+ .where("invoiceId", "=", staged.invoiceRowId)+ .execute();+ await expect(stageOrResumeRampBill(db, linked)).rejects.toThrow(+ "complete Ramp bill lines"+ );+ }, 30000);++ it("does not adopt an unmapped posted invoice merely because supplier reference and total match", async () => {+ const { args, ctx } = await fixture();+ const staged = await stageOrResumeRampBill(db, args);+ await ctx.mapping.unlink("bill", staged.invoiceRowId, "ramp");+ await db+ .updateTable("purchaseInvoiceLine")+ .set({ supplierUnitPrice: 50 })+ .where("companyId", "=", scope.companyId)+ .where("invoiceId", "=", staged.invoiceRowId)+ .execute();+ await db+ .insertInto("purchaseInvoiceLine")+ .values({+ invoiceId: staged.invoiceRowId,+ companyId: scope.companyId,+ createdBy: "system",+ invoiceLineType: "G/L Account",+ accountId: scope.accountId,+ quantity: 1,+ supplierUnitPrice: 50,+ sortOrder: 2+ })+ .execute();+ await db+ .updateTable("purchaseInvoice")+ .set({ status: "Open" })+ .where("companyId", "=", scope.companyId)+ .where("id", "=", staged.invoiceRowId)+ .execute();+ await expect(stageOrResumeRampBill(db, args)).rejects.toThrow(+ "not a valid legacy"+ );+ expect(+ await ctx.mapping.getEntityId("ramp", args.sourceId, "bill")+ ).toBeNull();+ }, 30000);++ it("stores foreign principal in supplier fields and lets generated fields convert to base", async () => {+ const { args } = await fixture();+ const currency = await db+ .selectFrom("currency")+ .select("code")+ .where("companyGroupId", "=", scope.companyGroupId)+ .where("code", "!=", scope.currencyCode)+ .executeTakeFirstOrThrow();+ const staged = await stageOrResumeRampBill(db, {+ ...args,+ currencyCode: currency.code,+ exchangeRate: 2+ });+ const line = await db+ .selectFrom("purchaseInvoiceLine")+ .select(["supplierUnitPrice", "unitPrice", "totalAmount", "exchangeRate"])+ .where("companyId", "=", scope.companyId)+ .where("invoiceId", "=", staged.invoiceRowId)+ .executeTakeFirstOrThrow();+ expect(line).toMatchObject({+ supplierUnitPrice: 100,+ unitPrice: 50,+ totalAmount: 50,+ exchangeRate: 2+ });+ }, 30000);++ it("rejects a second bill reserving the same unposted PO line", async () => {+ const { args, po, poLines } = await purchaseOrderFixture();+ const linked = {+ ...args,+ purchaseOrderId: po.id,+ lines: [{ ...args.lines[0]!, purchaseOrderLineId: poLines[0]!.id }]+ };+ await stageOrResumeRampBill(db, linked);+ await expect(+ stageOrResumeRampBill(db, {+ ...linked,+ sourceId: `${args.sourceId}-second`,+ supplierReference: "Another bill"+ })+ ).rejects.toThrow("already reserved");+ }, 30000);+});diff --git a/packages/jobs/src/inngest/functions/integrations/ramp-sync-card.integration.test.ts b/packages/jobs/src/inngest/functions/integrations/ramp-sync-card.integration.test.tsindex 6f099c4476..7d9c79e44d 100644--- a/packages/jobs/src/inngest/functions/integrations/ramp-sync-card.integration.test.ts+++ b/packages/jobs/src/inngest/functions/integrations/ramp-sync-card.integration.test.ts@@ -14,9 +14,18 @@ import { getJobDatabaseClient } from "../../../db";import { stageOrResumeRampCharge } from "./ramp-sync-card-stage";import type { RampSyncContext } from "./ramp-sync-shared";-const runDatabaseTests = process.env.RUN_RAMP_DB_TESTS === "true";-// Only the posting operation is substituted; everything else is real Postgres.+const LOCAL_HOSTS = ["localhost", "127.0.0.1", "[::1]"];+const hasLocalDatabase = (() => {+ try {+ return LOCAL_HOSTS.includes(+ new URL(process.env.SUPABASE_DB_URL ?? "").hostname+ );+ } catch {+ return false;+ }+})();+const { post } = vi.hoisted(() => ({ post: vi.fn() }));// A posting with a client runs as the caller behind it, else as the system.vi.mock("@carbon/api/postings.server", () => ({@@ -29,7 +38,7 @@ vi.mock("@carbon/ee/ramp.server", async (importOriginal) => ({confirmSyncs: vi.fn().mockResolvedValue(undefined)}));-describe.skipIf(!runDatabaseTests)("Ramp card staging (Postgres)", () => {+describe.skipIf(!hasLocalDatabase)("Ramp card staging (Postgres)", () => {let db: Kysely<KyselyDatabase>;let fixture: {companyId: string;diff --git a/packages/jobs/src/inngest/functions/integrations/ramp-sync-discriminators.test.ts b/packages/jobs/src/inngest/functions/integrations/ramp-sync-discriminators.test.tsindex ef40f920bd..486ca42bb9 100644--- a/packages/jobs/src/inngest/functions/integrations/ramp-sync-discriminators.test.ts+++ b/packages/jobs/src/inngest/functions/integrations/ramp-sync-discriminators.test.ts@@ -2,24 +2,17 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import type { RampClient } from "@carbon/ee/ramp.server";-import { afterEach, describe, expect, it, vi } from "vitest";+// Ramp's enum-like fields, read against its OpenAPI contract (2026-09-11). A+// value Carbon has not verified must fail the item, never post a guess.+import { describe, expect, it } from "vitest";+import { rampBillPaymentRoute } from "./ramp-sync-payment";import {- type RampBillPaymentDependencies,- syncRampBillPayment-} from "./ramp-sync-payment";-import {- type RampReimbursementDependencies,- syncRampReimbursement+ mappedReimbursementNeedsPayout,+ rampReimbursementStateKind} from "./ramp-sync-reimbursement";-import { syncRampRepayments } from "./ramp-sync-repayment";-import type { RampSyncContext } from "./ramp-sync-shared";--vi.mock("@carbon/env", () => ({ getAppUrl: () => "http://localhost:3000" }));--afterEach(() => vi.restoreAllMocks());+import { isVerifiedRepaymentFunding } from "./ramp-sync-repayment";-describe("Ramp inbound accounting discriminators", () => {+describe("rampBillPaymentRoute", () => {it.each(["ACH","CHECK",@@ -30,315 +23,82 @@ describe("Ramp inbound accounting discriminators", () => {"LOCAL_BANK_TRANSFER","RTP","SWIFT"- ])(- "continues invoice resolution for verified bank method %s",- async (payment_method) => {- const getMappedInvoiceId = vi.fn().mockResolvedValue(null);- const outcome = await syncRampBillPayment(- { getMappedInvoiceId } as unknown as RampBillPaymentDependencies,- { id: "bill-1" },- { id: "payment-1", payment_method }- );- expect(outcome).toEqual({- fail: {- id: "payment-1",- message: "Bill was never synced to Carbon — sync the bill first"- }- });- expect(getMappedInvoiceId).toHaveBeenCalledWith("bill-1");- }- );-- /**- * A mapped reimbursement's DOCUMENT is never re-read, so the deps only have to- * answer the mapping lookup, the metadata merge, and the durability reread.- */- function mappedReimbursementDeps(- mappingMetadata: Record<string, unknown> | null- ) {- const mappingQuery = {- selectAll: vi.fn().mockReturnThis(),- select: vi.fn().mockReturnThis(),- where: vi.fn().mockReturnThis(),- executeTakeFirst: vi.fn().mockResolvedValue({- id: "mapping-1",- entityId: "reimbursement-row-1",- metadata: mappingMetadata- })- };- const metadataUpdate = {- set: vi.fn().mockReturnThis(),- where: vi.fn().mockReturnThis(),- execute: vi.fn().mockResolvedValue(undefined)- };- const documentQuery = {- select: vi.fn().mockReturnThis(),- eq: vi.fn().mockReturnThis(),- maybeSingle: vi.fn().mockResolvedValue({- data: { id: "reimbursement-row-1", reimbursementId: "REIMB-1" },- error: null- })- };- const normalizeAmount = vi- .fn()- .mockResolvedValue({ ok: true, value: 125.5 });- const from = vi.fn().mockReturnValue(documentQuery);- return {- metadataUpdate,- normalizeAmount,- from,- deps: {- db: {- selectFrom: vi.fn().mockReturnValue(mappingQuery),- updateTable: vi.fn().mockReturnValue(metadataUpdate)- },- client: { from },- companyId: "company-1",- baseCurrency: "USD",- reimbursementBankAccountId: "bank-1",- normalizeAmount,- getExchangeRate: vi.fn().mockResolvedValue(1),- reimbursementDeepLinkUrl: (id: string) =>- `https://carbon.example/x/reimbursements/${id}`- } as unknown as RampReimbursementDependencies- };- }-- const reconfirmed = {- ok: {- id: "reimbursement-1",- referenceId: "REIMB-1",- deepLinkUrl: "https://carbon.example/x/reimbursements/reimbursement-row-1"- }- };-- it.each([- "MANUALLY_REIMBURSED",- "APPROVED",- "AWAITING_PAYMENT",- "AWAITING_PUSH_PAYMENT"- ])(- "re-confirms an already-imported reimbursement in state %s without touching it",- async (state) => {- // Carbon owns the document once it lands. These states record no payout- // intent, so a mapped item does no work at all beyond the reread.- const { deps, metadataUpdate, normalizeAmount, from } =- mappedReimbursementDeps(null);- expect(- await syncRampReimbursement(deps, { id: "reimbursement-1", state })- ).toEqual(reconfirmed);- expect(normalizeAmount).not.toHaveBeenCalled();- expect(metadataUpdate.execute).not.toHaveBeenCalled();- expect(from).toHaveBeenCalledWith("reimbursement");- }- );-- it.each(["REIMBURSED", "REIMBURSED_VIA_PUSH"])(- "records the payout intent on an already-imported reimbursement Ramp has since PAID in state %s",- async (state) => {- // The document still is not touched — but the mapping must gain the- // payout, or Post never creates the `payment`/`invoiceSettlement` and the- // money Ramp moved is never settled in Carbon.- const { deps, metadataUpdate } = mappedReimbursementDeps(null);- expect(- await syncRampReimbursement(deps, {- id: "reimbursement-1",- state,- transaction_date: "2026-09-12",- approved_at: "2026-09-13T10:00:00Z",- entity_amount: { currency: "USD", value: 12550 }- })- ).toEqual(reconfirmed);- expect(metadataUpdate.execute).toHaveBeenCalledTimes(1);- expect(metadataUpdate.set).toHaveBeenCalledTimes(1);- // The merge is a raw jsonb `||` fragment; its one parameter is the intent.- const merged = metadataUpdate.set.mock.calls[0]?.[0] as {- metadata: { toOperationNode: () => { parameters: unknown[] } };- };- const node = merged.metadata.toOperationNode();- expect(node.parameters).toEqual([- {- kind: "ValueNode",- value: JSON.stringify({- rampPaymentId: "reimbursement-payment:reimbursement-1",- paidAt: "2026-09-13",- bankAccountId: "bank-1",- amount: 125.5,- currencyCode: "USD",- exchangeRate: 1- })- }- ]);- }- );-- it("does not record a second payout intent on the next pass", async () => {- // Idempotent, and the FIRST intent wins: it carries the FX snapshot of the- // payout that actually happened.- const { deps, metadataUpdate, normalizeAmount } = mappedReimbursementDeps({- rampPaymentId: "reimbursement-payment:reimbursement-1",- exchangeRate: 0.91- });- expect(- await syncRampReimbursement(deps, {- id: "reimbursement-1",- state: "REIMBURSED",- transaction_date: "2026-09-12",- entity_amount: { currency: "USD", value: 12550 }- })- ).toEqual(reconfirmed);- expect(metadataUpdate.execute).not.toHaveBeenCalled();- expect(normalizeAmount).not.toHaveBeenCalled();- });-- it("fails a PAID reimbursement whose payout intent cannot be built", async () => {- // Ramp has already paid the employee, so an unrecordable payout is the- // operator's problem to see — not something to confirm away silently.- const { deps, metadataUpdate } = mappedReimbursementDeps(null);- expect(- await syncRampReimbursement(deps, {- id: "reimbursement-1",- state: "REIMBURSED",- entity_amount: { currency: "USD", value: 12550 }- })- ).toEqual({- fail: {- id: "reimbursement-1",- message: expect.stringContaining("payment date")- }- });- expect(metadataUpdate.execute).not.toHaveBeenCalled();+ ])("posts bank method %s as a payment", (method) => {+ expect(rampBillPaymentRoute(method)).toBe("bank");});- it("continues original transaction resolution for documented ach repayments", async () => {- vi.spyOn(console, "error").mockImplementation(() => undefined);- const getEntityId = vi.fn().mockResolvedValue(null);- const ctx = {- companyId: "company-1",- metadata: {- sync: { pullReimbursements: true },- statementBankAccountId: "bank-1"- },- mapping: { getEntityId }- } as unknown as RampSyncContext;- const ramp = {- listRepayments: async function* () {- yield [- {- id: "repayment-1",- status: "REPAID",- funding_method: "ach",- original_transaction_id: "charge-1"- }- ];- }- } as unknown as RampClient;- await syncRampRepayments(ctx, ramp, undefined, "card-1", null);- expect(getEntityId).toHaveBeenCalledWith("ramp", "charge-1", "charge");+ it.each([+ "CARD",+ "ONE_TIME_CARD",+ "ONE_TIME_CARD_DELIVERY",+ "AUTOMATIC_CARD_PAYMENT"+ ])("leaves card method %s to the card charge sync", (method) => {+ expect(rampBillPaymentRoute(method)).toBe("card");});it.each([undefined,null,"",+ "ach","NEW_PAYMENT_RAIL","VENDOR_CREDIT","PAID_MANUALLY","UNSPECIFIED"- ])(- "rejects unsupported bill payment method %s before any invoice lookup",- async (payment_method) => {- const getMappedInvoiceId = vi.fn().mockResolvedValue(null);- const outcome = await syncRampBillPayment(- { getMappedInvoiceId } as unknown as RampBillPaymentDependencies,- { id: "bill-1" },- { id: "payment-1", payment_method }- );- expect(outcome).toEqual({- fail: {- id: "payment-1",- message: expect.stringContaining("payment method")- }- });- expect(getMappedInvoiceId).not.toHaveBeenCalled();- }- );-- it("skips one-time card delivery payments instead of posting bank payments", async () => {- const getMappedInvoiceId = vi.fn().mockResolvedValue(null);- expect(- await syncRampBillPayment(- { getMappedInvoiceId } as unknown as RampBillPaymentDependencies,- { id: "bill-1" },- { id: "payment-1", payment_method: "ONE_TIME_CARD_DELIVERY" }- )- ).toEqual({ skip: { id: "payment-1", referenceId: "payment-1" } });- expect(getMappedInvoiceId).not.toHaveBeenCalled();+ ])("refuses unverified method %s", (method) => {+ expect(rampBillPaymentRoute(method)).toBe("unsupported");});+});+describe("rampReimbursementStateKind", () => {it.each([- undefined,- "",- "NEW_STATE",- "PAID",- "PAID_OUT",- "REJECTED",- "DELETED"- ])(- "rejects unsupported reimbursement state %s before any invoice lookup",- async (state) => {- const query = {- select: vi.fn().mockReturnThis(),- where: vi.fn().mockReturnThis(),- executeTakeFirst: vi.fn().mockResolvedValue(null)- };- const selectFrom = vi.fn().mockReturnValue(query);- const outcome = await syncRampReimbursement(- {- db: { selectFrom },- companyId: "company-1"- } as unknown as RampReimbursementDependencies,- { id: "reimbursement-1", state }- );- expect(outcome).toEqual({- fail: {- id: "reimbursement-1",- message: expect.stringContaining("reimbursement state")- }- });- expect(selectFrom).not.toHaveBeenCalled();- }- );+ ["REIMBURSED", "paid"],+ ["REIMBURSED_VIA_PUSH", "paid"],+ ["APPROVED", "invoiceOnly"],+ ["AWAITING_PAYMENT", "invoiceOnly"],+ ["AWAITING_PUSH_PAYMENT", "invoiceOnly"],+ ["MANUALLY_REIMBURSED", "invoiceOnly"],+ [undefined, "unsupported"],+ ["", "unsupported"],+ ["NEW_STATE", "unsupported"],+ ["PAID", "unsupported"],+ ["PAID_OUT", "unsupported"],+ ["REJECTED", "unsupported"],+ ["DELETED", "unsupported"]+ ] as const)("reads state %s as %s", (state, kind) => {+ expect(rampReimbursementStateKind(state)).toBe(kind);+ });+});++describe("mappedReimbursementNeedsPayout", () => {+ const recorded = {+ rampPaymentId: "reimbursement-payment:r-1",+ exchangeRate: 0.91+ };++ it("records the payout on an imported reimbursement Ramp has since paid", () => {+ // Without it Post never settles the money Ramp already moved.+ expect(mappedReimbursementNeedsPayout("paid", null)).toBe(true);+ });++ it("keeps the first recorded payout on the next pass", () => {+ expect(mappedReimbursementNeedsPayout("paid", recorded)).toBe(false);+ });++ it("records nothing while the reimbursement is unpaid", () => {+ expect(mappedReimbursementNeedsPayout("invoiceOnly", null)).toBe(false);+ });+});++describe("isVerifiedRepaymentFunding", () => {+ it("accepts ach, the only funding Ramp documents", () => {+ expect(isVerifiedRepaymentFunding("ach")).toBe(true);+ });- it.each([undefined, null, "", "NEW_FUNDING", "STATEMENT_CREDIT"])(- "rejects unverified repayment funding %s before any transaction lookup",- async (funding_method) => {- vi.spyOn(console, "error").mockImplementation(() => undefined);- const getEntityId = vi.fn().mockResolvedValue(null);- const ctx = {- companyId: "company-1",- metadata: {- sync: { pullReimbursements: true },- statementBankAccountId: "bank-1"- },- mapping: { getEntityId }- } as unknown as RampSyncContext;- const ramp = {- listRepayments: async function* () {- yield [- {- id: "repayment-1",- status: "REPAID",- funding_method,- original_transaction_id: "charge-1"- }- ];- }- } as unknown as RampClient;- expect(- await syncRampRepayments(ctx, ramp, undefined, "card-1", null)- ).toMatchObject({ created: 0, failed: 1 });- expect(getEntityId).not.toHaveBeenCalled();+ it.each([undefined, null, "", "ACH", "NEW_FUNDING", "STATEMENT_CREDIT"])(+ "refuses funding %s",+ (method) => {+ expect(isVerifiedRepaymentFunding(method)).toBe(false);});});diff --git a/packages/jobs/src/inngest/functions/integrations/ramp-sync-payment.ts b/packages/jobs/src/inngest/functions/integrations/ramp-sync-payment.tsindex 5b72cf462e..6b2eab0117 100644--- a/packages/jobs/src/inngest/functions/integrations/ramp-sync-payment.ts+++ b/packages/jobs/src/inngest/functions/integrations/ramp-sync-payment.ts@@ -61,6 +61,19 @@ const BANK_PAYMENT_METHODS = new Set(["SWIFT"]);+/**+ * How a Ramp bill payment is handled: a card payment is the card charge's+ * business (skipped here), a verified bank rail posts a payment, and anything+ * else fails rather than guessing an offset account.+ */+export function rampBillPaymentRoute(+ method: string | null | undefined+): "card" | "bank" | "unsupported" {+ if (CARD_PAYMENT_METHODS.has(method ?? "")) return "card";+ if (BANK_PAYMENT_METHODS.has(method ?? "")) return "bank";+ return "unsupported";+}+export async function ensureRampPaymentPosted(deps: {stage: () => Promise<StageResult>;post: (paymentRowId: string) => Promise<{ error: boolean; message?: string }>;@@ -232,10 +245,11 @@ export async function syncRampBillPayment(}const method = payment.payment_method ?? "";- if (CARD_PAYMENT_METHODS.has(method)) {+ const route = rampBillPaymentRoute(method);+ if (route === "card") {return { skip: { id: paymentRampId, referenceId: paymentRampId } };}- if (!BANK_PAYMENT_METHODS.has(method)) {+ if (route === "unsupported") {return {fail: {id: paymentRampId,diff --git a/packages/jobs/src/inngest/functions/integrations/ramp-sync-reimbursement-create.integration.test.ts b/packages/jobs/src/inngest/functions/integrations/ramp-sync-reimbursement-create.integration.test.tsindex 47662825e6..f9dc84f5a6 100644--- a/packages/jobs/src/inngest/functions/integrations/ramp-sync-reimbursement-create.integration.test.ts+++ b/packages/jobs/src/inngest/functions/integrations/ramp-sync-reimbursement-create.integration.test.ts@@ -12,12 +12,23 @@ import {type RampReimbursementDraft} from "./ramp-sync-reimbursement";+const LOCAL_HOSTS = ["localhost", "127.0.0.1", "[::1]"];+const hasLocalDatabase = (() => {+ try {+ return LOCAL_HOSTS.includes(+ new URL(process.env.SUPABASE_DB_URL ?? "").hostname+ );+ } catch {+ return false;+ }+})();+/*** The create-only rule, against a real Postgres.*- * `RUN_RAMP_DB_TESTS=true SUPABASE_DB_URL=... pnpm --filter @carbon/jobs test`+ * `SUPABASE_DB_URL=… pnpm --filter @carbon/jobs exec vitest run ramp-sync-reimbursement-create`*/-describe.skipIf(process.env.RUN_RAMP_DB_TESTS !== "true")(+describe.skipIf(!hasLocalDatabase)("Ramp reimbursement import (Postgres)",() => {let db: Kysely<KyselyDatabase>;diff --git a/packages/jobs/src/inngest/functions/integrations/ramp-sync-reimbursement.ts b/packages/jobs/src/inngest/functions/integrations/ramp-sync-reimbursement.tsindex a071ba7ced..689a22e8dd 100644--- a/packages/jobs/src/inngest/functions/integrations/ramp-sync-reimbursement.ts+++ b/packages/jobs/src/inngest/functions/integrations/ramp-sync-reimbursement.ts@@ -128,6 +128,31 @@ const REIMBURSEMENT_INVOICE_ONLY_STATES = new Set(["MANUALLY_REIMBURSED"]);+/**+ * What a Ramp reimbursement state means here: Ramp has paid the employee+ * (import with a payout intent), it is payable but unpaid (import the document+ * only), or its accounting meaning is unknown (fail the item).+ */+export function rampReimbursementStateKind(+ state: string | null | undefined+): "paid" | "invoiceOnly" | "unsupported" {+ if (REIMBURSEMENT_PAID_STATES.has(state ?? "")) return "paid";+ if (REIMBURSEMENT_INVOICE_ONLY_STATES.has(state ?? "")) return "invoiceOnly";+ return "unsupported";+}++/**+ * Whether an already-imported reimbursement's mapping still needs its payout+ * intent: only once Ramp has paid, and the first recorded intent wins (it+ * carries the FX snapshot of the payout that happened).+ */+export function mappedReimbursementNeedsPayout(+ stateKind: ReturnType<typeof rampReimbursementStateKind>,+ mappingMetadata: unknown+): boolean {+ return stateKind === "paid" && !hasRecordedPayout(mappingMetadata);+}+/*** Atomically create the Draft `reimbursement`, its coding lines, and the Ramp* mapping that is its idempotency anchor.@@ -724,8 +749,9 @@ export async function syncRampReimbursement(reimbursement: RampReimbursement): Promise<{ ok: SyncItem } | { fail: FailItem }> {const state = reimbursement.state ?? "";- const isRampPaid = REIMBURSEMENT_PAID_STATES.has(state);- if (!isRampPaid && !REIMBURSEMENT_INVOICE_ONLY_STATES.has(state)) {+ const stateKind = rampReimbursementStateKind(state);+ const isRampPaid = stateKind === "paid";+ if (stateKind === "unsupported") {return {fail: {id: reimbursement.id,@@ -757,7 +783,7 @@ export async function syncRampReimbursement(// has already paid, so "we cannot record it" is the operator's problem to// see. Nothing else about the mapped path can fail it — the document's// amount and coding are never re-read.- if (isRampPaid && !hasRecordedPayout(mapped.metadata)) {+ if (mappedReimbursementNeedsPayout(stateKind, mapped.metadata)) {const payout = await resolveRampReimbursementPayout(deps, reimbursement);if ("error" in payout) {return { fail: { id: reimbursement.id, message: payout.error } };diff --git a/packages/jobs/src/inngest/functions/integrations/ramp-sync-repayment.ts b/packages/jobs/src/inngest/functions/integrations/ramp-sync-repayment.tsindex da0e3c4827..6dee3dd5c8 100644--- a/packages/jobs/src/inngest/functions/integrations/ramp-sync-repayment.ts+++ b/packages/jobs/src/inngest/functions/integrations/ramp-sync-repayment.ts@@ -29,6 +29,12 @@ const REPAYMENT_REPAID_STATUS = "REPAID";// Ramp's OpenAPI example (2026-09-11). Do not guess an offset for other values.const REPAYMENT_BANK_FUNDING = "ach";+export function isVerifiedRepaymentFunding(+ method: string | null | undefined+): boolean {+ return method === REPAYMENT_BANK_FUNDING;+}+function instantMinusOneSecond(iso: string): string {const ms = Date.parse(iso);if (Number.isNaN(ms)) return iso;@@ -112,7 +118,7 @@ export async function syncRampRepayments(if (repaidAt) failedRepaidAt.push(repaidAt);repaymentFailures.push({ id: repayment.id, message });};- if (repayment.funding_method !== REPAYMENT_BANK_FUNDING) {+ if (!isVerifiedRepaymentFunding(repayment.funding_method)) {const message = `Unsupported funding method: ${repayment.funding_method || "missing"}`;failRepayment(message);result.error ??= `Repayment ${repayment.id} has ${message}`;diff --git a/packages/jobs/src/inngest/functions/integrations/ramp-sync-transaction.integration.test.ts b/packages/jobs/src/inngest/functions/integrations/ramp-sync-transaction.integration.test.tsindex d355c5809d..322568b834 100644--- a/packages/jobs/src/inngest/functions/integrations/ramp-sync-transaction.integration.test.ts+++ b/packages/jobs/src/inngest/functions/integrations/ramp-sync-transaction.integration.test.ts@@ -8,9 +8,18 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";import { getJobDatabaseClient } from "../../../db";import { stageRampPaymentDraft } from "./ramp-sync-payment";-const runDatabaseTests = process.env.RUN_RAMP_DB_TESTS === "true";+const LOCAL_HOSTS = ["localhost", "127.0.0.1", "[::1]"];+const hasLocalDatabase = (() => {+ try {+ return LOCAL_HOSTS.includes(+ new URL(process.env.SUPABASE_DB_URL ?? "").hostname+ );+ } catch {+ return false;+ }+})();-describe.skipIf(!runDatabaseTests)(+describe.skipIf(!hasLocalDatabase)("Ramp transactional staging (Postgres)",() => {let db: Kysely<KyselyDatabase>;diff --git a/packages/jobs/src/inngest/functions/integrations/reconcile-charge-lifecycle.test.ts b/packages/jobs/src/inngest/functions/integrations/reconcile-charge-lifecycle.test.tsindex b0c21f79dc..2fd0a88d4b 100644--- a/packages/jobs/src/inngest/functions/integrations/reconcile-charge-lifecycle.test.ts+++ b/packages/jobs/src/inngest/functions/integrations/reconcile-charge-lifecycle.test.ts@@ -2,207 +2,90 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { QboChargeSyncer, XeroChargeSyncer } from "@carbon/ee/accounting";-import { buildIntegrationTopology } from "@carbon/ee/sync";-import { beforeEach, describe, expect, it, vi } from "vitest";-import type { CardChargeSource } from "../../../../../ee/src/accounting/core/card-charge-source";-import type { SyncOperationRequest } from "./accounting-sync-operations";-import { reconcileEntities } from "./reconcile-executor";+// The reconcile half of a card void. The syncer half (delete remotely, mark+// the mapping voided only on confirmed deletion) is pinned by the Xero and+// QuickBooks charge tests in @carbon/ee.+import { resolvePostingSyncSettings } from "@carbon/ee/accounting";+import { asCarbonOwnedSettings } from "@carbon/ee/sync";+import { describe, expect, it } from "vitest";+import {+ computeReconcileDecision,+ type ReconcileEntityInput+} from "./reconcile";+import { providerSupportsNativeVoid } from "./reconcile-executor";-const { requests, mapping } = vi.hoisted(() => ({- requests: [] as SyncOperationRequest[],- mapping: {- entityId: "charge-1",- externalId: "remote-1",- lastSyncedAt: "2026-09-10T00:00:00Z",- metadata: {} as Record<string, unknown>- }-}));-vi.mock("./accounting-sync-operations", async (importOriginal) => ({- ...(await importOriginal<typeof import("./accounting-sync-operations")>()),- enqueueSyncOperations: async (- _client: unknown,- args: { requests: SyncOperationRequest[] }- ) => {- requests.push(...args.requests);- return args.requests.map(() => ({ outcome: "enqueued" }));- },- insertTerminalSyncOperations: async () => []-}));-vi.mock("../../../../../ee/src/accounting/core/external-mapping", () => ({- createMappingService: () => ({- getByEntity: async () => mapping,- getByEntities: async () => new Map([[mapping.entityId, mapping]]),- link: async (- _type: string,- _id: string,- _provider: string,- _externalId: string,- options: { metadata: Record<string, unknown> }- ) => {- mapping.metadata = options.metadata;- }- })-}));-vi.mock(- "../../../../../ee/src/accounting/core/utils",- async (importOriginal) => ({- ...(await importOriginal<- typeof import("../../../../../ee/src/accounting/core/utils")- >()),- withTriggersDisabled: async (- _db: unknown,- callback: (tx: unknown) => Promise<unknown>- ) => callback({})- })-);--beforeEach(() => {- requests.length = 0;- mapping.metadata = {};+describe("providerSupportsNativeVoid", () => {+ it.each([+ ["charge", "xero", true],+ ["charge", "quickbooks", true],+ ["charge", "rillet", true],+ // Invoices and bills fall back to the default set: Rillet only.+ ["invoice", "xero", false],+ ["invoice", "rillet", true]+ ] as const)("%s on %s: %s", (entityType, providerId, expected) => {+ expect(providerSupportsNativeVoid(entityType, providerId)).toBe(expected);+ });});-// Nothing is delegated in these fixtures, so the topology is carbon-owned.-const CARBON_TOPOLOGY = buildIntegrationTopology([], []);+describe("a voided card charge", () => {+ function voidedCharge(+ overrides: Partial<ReconcileEntityInput>+ ): ReconcileEntityInput {+ return {+ entityType: "charge",+ entityId: "charge-1",+ snapshot: { status: "Voided" },+ hasMappingWithExternalId: true,+ hasUnvoidedPushMapping: true,+ lastSyncedAt: "2026-09-10T00:00:00Z",+ hasLiveOperation: false,+ latestOperation: {+ id: "op-push",+ status: "Completed",+ errorCode: null,+ attemptCount: 1,+ createdAt: "2026-09-09T10:00:00Z"+ },+ context: {+ journalEntryPushEnabled: true,+ entityPushEnabled: true,+ providerSupportsPaymentPush: true,+ providerSupportsNativeVoid: true,+ settings: asCarbonOwnedSettings(+ resolvePostingSyncSettings({+ settings: { postingSync: { enabled: true } }+ })+ ),+ docSync: {+ invoiceEnabled: true,+ billEnabled: true,+ chargeEnabled: true,+ chargeCreditEnabled: false+ },+ inventoryAdjustmentEnabled: false,+ paymentFamily: null+ },+ ...overrides+ };+ }-describe.each(["xero", "quickbooks"])(- "%s reconciled card void",- (providerId) => {- it.each([true, false])(- "enqueues a mapped void, reaches the native adapter, and persists only confirmed deletion (confirmed=%s)",- async (confirmed) => {- const client = {- from(table: string) {- const query = {- select: () => query,- eq: () => query,- in: async () => ({- error: null,- data:- table === "charge"- ? [{ id: "charge-1", status: "Voided" }]- : []- })- };- return query;- }- };- const database = {- selectFrom: () => {- const query = {- select: () => query,- where: () => query,- execute: async () => [mapping]- };- return query;- }- };- const summary = await reconcileEntities({- topology: CARBON_TOPOLOGY,- client: client as never,- database: database as never,- companyId: "company-1",- providerId,- integrationMetadata: {},- createdBy: "system",- scope: "void",- refs: [{ entityType: "charge", entityId: "charge-1" }]- });- expect(summary.enqueued).toBe(1);- expect(requests[0]).toMatchObject({+ it("enqueues a void while its push mapping is not yet voided", () => {+ expect(computeReconcileDecision(voidedCharge({})).actions).toEqual([+ {+ kind: "enqueue",+ request: expect.objectContaining({entityType: "charge",entityId: "charge-1"- });-- const remoteCalls: string[] = [];- const provider = {- id: providerId,- deletePurchase: async () => {- remoteCalls.push("delete");- if (!confirmed) throw new Error("Provider refused deletion");- },- request: async (method: string) => {- remoteCalls.push(method);- if (!confirmed && method === "POST")- throw new Error("Provider refused deletion");- return {- error: false,- data: {- BankTransactions: [- {- BankTransactionID: "remote-1",- Type: "SPEND",- BankAccount: { Code: "card" },- LineItems: [],- Status: method === "GET" ? "AUTHORISED" : "DELETED"- }- ]- }- };- }- };- const Syncer =- providerId === "xero" ? XeroChargeSyncer : QboChargeSyncer;- const syncer = new Syncer({- database: {} as never,- companyId: "company-1",- provider: provider as never,- entityType: "charge",- config: {- enabled: true,- direction: "push-to-accounting",- owner: "carbon"- }- });- const localSource: CardChargeSource = {- id: "charge-1",- companyId: "company-1",- chargeId: "CARD-1",- type: "Charge",- status: "Voided",- supplierId: "supplier",- supplierExternalId: "remote-supplier",- merchantName: null,- memo: null,- updatedAt: null- };- vi.spyOn(- syncer as unknown as {- fetchLocalBatch(- ids: string[]- ): Promise<Map<string, CardChargeSource>>;- },- "fetchLocalBatch"- ).mockResolvedValue(new Map([[localSource.id, localSource]]));- const result = await syncer.pushBatchToAccounting(- requests.map((request) => request.entityId)- );- expect(result.results[0]).toMatchObject(- confirmed- ? {- status: "success",- action: "deleted"- }- : { status: "error" }- );- expect(remoteCalls.length).toBeGreaterThan(0);- expect(mapping.metadata.voided === true).toBe(confirmed);- expect(- (- await reconcileEntities({- topology: CARBON_TOPOLOGY,- client: client as never,- database: database as never,- companyId: "company-1",- providerId,- integrationMetadata: {},- createdBy: "system",- scope: "void-repeat",- refs: [{ entityType: "charge", entityId: "charge-1" }]- })- ).enqueued- ).toBe(confirmed ? 0 : 1);+ })}- );- }-);+ ]);+ });++ it("does nothing once the mapping records the confirmed deletion", () => {+ expect(+ computeReconcileDecision(+ voidedCharge({ hasUnvoidedPushMapping: false })+ ).actions.map((action) => action.kind)+ ).toEqual(["nothing"]);+ });+});diff --git a/packages/jobs/src/inngest/functions/integrations/reconcile-executor.ts b/packages/jobs/src/inngest/functions/integrations/reconcile-executor.tsindex 72e83ce208..f04c72df8c 100644--- a/packages/jobs/src/inngest/functions/integrations/reconcile-executor.ts+++ b/packages/jobs/src/inngest/functions/integrations/reconcile-executor.ts@@ -104,6 +104,17 @@ const NATIVE_VOID_PROVIDERS_BY_ENTITY: Partial</** Invoices and bills: Rillet is the only native document void today. */const DEFAULT_NATIVE_VOID_PROVIDERS: ReadonlySet<string> = new Set(["rillet"]);+/** Whether the provider can void this document type natively. */+export function providerSupportsNativeVoid(+ entityType: ReconcileEntityType,+ providerId: string+): boolean {+ return (+ NATIVE_VOID_PROVIDERS_BY_ENTITY[entityType]?.has(providerId) ??+ DEFAULT_NATIVE_VOID_PROVIDERS.has(providerId)+ );+}+/** Entity types whose decision consults the push mapping. */const MAPPED_TYPES: ReadonlySet<ReconcileEntityType> = new Set(["bill",@@ -209,19 +220,7 @@ export async function reconcileEntities(args: {// family modes and the backing entities — the pair that is only correct// together. With nothing delegated this is byte-identical to the previous// two lines.- const { settings, syncConfig: metadataSyncConfig } =- applyEffectivePostingState(- args.integrationMetadata,- args.topology,- args.providerId- );- const syncConfig = resolveEffectiveSyncConfig({- providerId: args.providerId,- provider: args.provider,- metadataSyncConfig,- settings,- topology: args.topology- });+ const { settings, syncConfig } = reconcileSyncConfig(args);// 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.@@ -510,9 +509,10 @@ export async function reconcileEntities(args: {// document live with nothing failing. Memos are the opposite case: only// Rillet can void one, and `MEMO_NATIVE_VOID_PROVIDERS` is where that// hole is declared rather than hidden in a comparison here.- providerSupportsNativeVoid:- NATIVE_VOID_PROVIDERS_BY_ENTITY[entityType]?.has(args.providerId) ??- DEFAULT_NATIVE_VOID_PROVIDERS.has(args.providerId),+ providerSupportsNativeVoid: providerSupportsNativeVoid(+ entityType,+ args.providerId+ ),journalEntryPushEnabled,entityPushEnabled,providerSupportsPaymentPush: PAYMENT_PUSH_PROVIDERS.has(@@ -595,6 +595,29 @@ export async function reconcileEntities(args: {return summary;}+/** The posting settings and sync config a reconcile occasion decides against. */+export function reconcileSyncConfig(args: {+ integrationMetadata: unknown;+ topology: IntegrationTopology;+ providerId: string;+ provider?: Pick<SyncProvider, "getSyncConfig">;+}) {+ const { settings, syncConfig: metadataSyncConfig } =+ applyEffectivePostingState(+ args.integrationMetadata,+ args.topology,+ args.providerId+ );+ const syncConfig = resolveEffectiveSyncConfig({+ providerId: args.providerId,+ provider: args.provider,+ metadataSyncConfig,+ settings,+ topology: args.topology+ });+ return { settings, syncConfig };+}+const SPEND_PROVIDER_IDS: ReadonlySet<string> = new Set(Object.values(SpendProviderID));diff --git a/packages/jobs/src/inngest/functions/integrations/reconcile-spend-config.test.ts b/packages/jobs/src/inngest/functions/integrations/reconcile-spend-config.test.tsindex cae227140e..5005ecd5ad 100644--- a/packages/jobs/src/inngest/functions/integrations/reconcile-spend-config.test.ts+++ b/packages/jobs/src/inngest/functions/integrations/reconcile-spend-config.test.ts@@ -3,65 +3,8 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { buildIntegrationTopology } from "@carbon/ee/sync";-import { beforeEach, describe, expect, it, vi } from "vitest";-import type { SyncOperationRequest } from "./accounting-sync-operations";-import { reconcileEntities } from "./reconcile-executor";--const { requests } = vi.hoisted(() => ({- requests: [] as SyncOperationRequest[]-}));--vi.mock("./accounting-sync-operations", async (importOriginal) => ({- ...(await importOriginal<typeof import("./accounting-sync-operations")>()),- enqueueSyncOperations: async (- _client: unknown,- args: { requests: SyncOperationRequest[] }- ) => {- requests.push(...args.requests);- return args.requests.map(() => ({ outcome: "enqueued" }));- },- insertTerminalSyncOperations: async () => []-}));--beforeEach(() => {- requests.length = 0;-});--/** Nothing delegated: a plain Ramp install holding the accounting seat. */-const CARBON_TOPOLOGY = buildIntegrationTopology([], []);--/** A posted, unmapped purchase invoice — the shape the sweep and events hand in. */-function fixtures() {- const client = {- from() {- const query = {- select: () => query,- eq: () => query,- not: () => query,- in: async () => ({- error: null,- data: [- { id: "pi-1", status: "Open", updatedAt: "2026-09-28T00:00:00Z" }- ]- })- };- return query;- }- };- const database = {- selectFrom: () => {- const query = {- select: () => query,- distinct: () => query,- innerJoin: () => query,- where: () => query,- execute: async () => []- };- return query;- }- };- return { client, database };-}+import { describe, expect, it } from "vitest";+import { reconcileSyncConfig } from "./reconcile-executor";const entityConfig = (enabled: boolean) => ({enabled,@@ -69,75 +12,45 @@ const entityConfig = (enabled: boolean) => ({owner: "carbon" as const});-async function reconcileBill(+/** Whether reconciliation would push a bill, for a plain install holding the accounting seat. */+function billEnabled(providerId: string,- provider?: { getSyncConfig: (entity: string) => unknown }+ provider?: { getSyncConfig: () => ReturnType<typeof entityConfig> }) {- const { client, database } = fixtures();- return await reconcileEntities({- topology: CARBON_TOPOLOGY,- client: client as never,- database: database as never,- companyId: "company-1",+ return reconcileSyncConfig({+ topology: buildIntegrationTopology([], []),providerId,- // A spend platform stores its toggles under `sync`, NEVER under- // `syncConfig` — which is the only key `resolveSyncConfig` reads.+ // A spend platform stores its toggles under `sync`, never under+ // `syncConfig`, the only key the metadata resolver reads.integrationMetadata: {syncMode: "provider",sync: { pushPurchaseOrders: false, pushInvoices: false }},- ...(provider ? { provider: provider as never } : {}),- createdBy: "system",- scope: "spend-config",- refs: [{ entityType: "bill", entityId: "pi-1" }]- });+ ...(provider ? { provider: provider as never } : {})+ }).syncConfig.entities.bill.enabled;}-describe("reconcileEntities with a spend provider", () => {- it("does not enqueue a bill the platform's config has disabled", async () => {- // The bug: `resolveSyncConfig` reads `metadata.syncConfig`, which a spend- // platform never writes, so it returned DEFAULT_SYNC_CONFIG — where `bill`- // is enabled. Reconciliation enqueued a push the drain then skipped on- // `config.enabled`, filling the ledger with "Sync disabled in config" rows.- const summary = await reconcileBill("ramp", {- getSyncConfig: () => entityConfig(false)- });-- expect(requests).toEqual([]);- expect(summary.enqueued).toBe(0);- expect(summary.nothing).toBe(1);- });-- it("still enqueues when the platform's config has it enabled", async () => {- const summary = await reconcileBill("ramp", {- getSyncConfig: () => entityConfig(true)- });-- expect(requests).toEqual([- {- entityType: "bill",- entityId: "pi-1",- direction: "push-to-accounting"- }- ]);- expect(summary.enqueued).toBe(1);- });-- it("leaves an accounting provider on its metadata-resolved config", async () => {- // Scoped to spend on purpose: `getProviderIntegration` FORCES entities for- // an accounting provider (Rillet's `payment`, say) that the generic default- // has off, so substituting its config here would change behaviour well- // outside this gap. A provider passed for `rillet` must be ignored.- const summary = await reconcileBill("rillet", {- getSyncConfig: () => entityConfig(false)- });-- expect(summary.enqueued).toBe(1);+describe("reconcileSyncConfig", () => {+ // Otherwise reconciliation enqueues a push the drain then skips, and the+ // ledger fills with "Sync disabled in config" rows.+ it.each([false, true])(+ "follows a spend provider's own config for a bill (enabled=%s)",+ (enabled) => {+ expect(+ billEnabled("ramp", { getSyncConfig: () => entityConfig(enabled) })+ ).toBe(enabled);+ }+ );++ it("keeps an accounting provider on its metadata-resolved config", () => {+ // getProviderIntegration forces entities for accounting providers that+ // the generic default has off; substituting here would change them.+ expect(+ billEnabled("rillet", { getSyncConfig: () => entityConfig(false) })+ ).toBe(true);});- it("is unchanged when no provider is supplied", async () => {- const summary = await reconcileBill("ramp");-- expect(summary.enqueued).toBe(1);+ it("uses the metadata-resolved config when no provider is supplied", () => {+ expect(billEnabled("ramp")).toBe(true);});});diff --git a/packages/jobs/src/inngest/functions/scheduled/mrp-companies.test.ts b/packages/jobs/src/inngest/functions/scheduled/mrp-companies.test.tsindex b374831c58..f4efe03a45 100644--- a/packages/jobs/src/inngest/functions/scheduled/mrp-companies.test.ts+++ b/packages/jobs/src/inngest/functions/scheduled/mrp-companies.test.ts@@ -5,7 +5,6 @@import type { KyselyDatabase } from "@carbon/database/client";import { parseAbsolute } from "@internationalized/date";import {- type CompiledQuery,type DatabaseConnection,DummyDriver,Kysely,@@ -96,21 +95,18 @@ describe("selectCompaniesForMrp with a planning-work lookup", () => {});});-// The Postgres wire is the boundary: the lookup's one statement is recorded-// as compiled SQL, and answered with the rows Postgres would return.-class RecordingDriver extends DummyDriver {- readonly sent: CompiledQuery[] = [];+// The Postgres wire is the boundary: the lookup's statement is answered with+// the rows Postgres would return. Which companies the SQL selects needs a+// database test.+class RowsDriver extends DummyDriver {constructor(private readonly rows: { companyId: string | null }[]) {super();}override async acquireConnection(): Promise<DatabaseConnection> {return {- executeQuery: async <R>(- query: CompiledQuery- ): Promise<QueryResult<R>> => {- this.sent.push(query);- return { rows: this.rows as R[] };- },+ executeQuery: async <R>(): Promise<QueryResult<R>> => ({+ rows: this.rows as R[]+ }),// biome-ignore lint/correctness/useYield: never streamedstreamQuery: async function* () {throw new Error("not streamed");@@ -119,55 +115,23 @@ class RecordingDriver extends DummyDriver {}}-async function lookup(rows: { companyId: string | null }[] = []) {- const driver = new RecordingDriver(rows);- const db = new Kysely<KyselyDatabase>({- dialect: {- createAdapter: () => new PostgresAdapter(),- createDriver: () => driver,- createIntrospector: (k) => new PostgresIntrospector(k),- createQueryCompiler: () => new PostgresQueryCompiler()- }- });- const companies = await companiesWithPlanningWork(db);- expect(driver.sent).toHaveLength(1);- return { companies, query: driver.sent[0]! };-}-describe("companiesWithPlanningWork", () => {it("returns each company once and drops a null", async () => {- const { companies } = await lookup([+ const driver = new RowsDriver([{ companyId: "c1" },{ companyId: null },- { companyId: "c2" }+ { companyId: "c2" },+ { companyId: "c1" }]);- expect([...companies]).toEqual(["c1", "c2"]);- });-- // A reorder policy orders from on-hand alone: no document, no forecast,- // nothing an earlier run wrote. Such a company was skipped, and its- // safety-stock and reorder-point Orders never appeared.- it("includes a company whose only need is a reorder floor", async () => {- const { query } = await lookup();- expect(query.sql).toContain('from "itemPlanning"');- expect(query.sql).toMatch(/"minimumReserveQuantity" > \$\d+/);- expect(query.sql).toMatch(/"demandAccumulationSafetyStock" > \$\d+/);- expect(query.sql).toMatch(/"reorderPoint" > \$\d+/);- expect(query.parameters).toEqual(- expect.arrayContaining([- "Demand-Based Reorder",- "Fixed Reorder Quantity",- "Maximum Quantity"- ])- );- // "not Manual Reorder" alone would be every company: it is the default- expect(query.parameters).not.toContain("Manual Reorder");- });-- it("includes a company with stock below zero", async () => {- const { query } = await lookup();- expect(query.sql).toContain('from "itemStockQuantities"');- expect(query.sql).toMatch(/"quantityOnHand" < \$\d+/);+ const db = new Kysely<KyselyDatabase>({+ dialect: {+ createAdapter: () => new PostgresAdapter(),+ createDriver: () => driver,+ createIntrospector: (k) => new PostgresIntrospector(k),+ createQueryCompiler: () => new PostgresQueryCompiler()+ }+ });+ expect([...(await companiesWithPlanningWork(db))]).toEqual(["c1", "c2"]);});});diff --git a/packages/jobs/src/inngest/functions/scheduled/notification-digest.test.ts b/packages/jobs/src/inngest/functions/scheduled/notification-digest.test.tsindex dfa1f30e94..5cde968144 100644--- a/packages/jobs/src/inngest/functions/scheduled/notification-digest.test.ts+++ b/packages/jobs/src/inngest/functions/scheduled/notification-digest.test.ts@@ -4,13 +4,10 @@import { describe, expect, it, vi } from "vitest";+// @carbon/auth builds its Supabase client at import time.vi.mock("@carbon/auth/client.server", () => ({getCarbonServiceRole: vi.fn()}));-vi.mock("../../../db", () => ({ getJobDatabaseClient: vi.fn() }));-vi.mock("../../client", () => ({- inngest: { createFunction: vi.fn(() => ({})) }-}));import { NotificationTopic } from "@carbon/notifications";import { staleDigests } from "./notification-digest";diff --git a/packages/jobs/src/inngest/functions/scheduled/notification-digest.ts b/packages/jobs/src/inngest/functions/scheduled/notification-digest.tsindex 0545c9af2c..151c84a192 100644--- a/packages/jobs/src/inngest/functions/scheduled/notification-digest.ts+++ b/packages/jobs/src/inngest/functions/scheduled/notification-digest.ts@@ -23,7 +23,7 @@ import { inngest } from "../../client";// The threshold and the age below are repeated in// `util.notification_digest_has_work` (the migration that defines it). Change// both: a stricter rule there leaves these digests unmade.-// `scheduled-sql-thresholds.test.ts` fails when the two disagree.+// the `scheduled-sql-constants` check (@carbon/checks) fails when they disagree.export const DIGEST_THRESHOLD = 5;// Minutes. Set to 0 for instant testing; production target is ~60 so users// get a chance to see live notifications before they roll up.diff --git a/packages/jobs/src/inngest/functions/scheduled/purge-company.integration.test.ts b/packages/jobs/src/inngest/functions/scheduled/purge-company.integration.test.tsindex 69961494ed..b789ed56a3 100644--- a/packages/jobs/src/inngest/functions/scheduled/purge-company.integration.test.ts+++ b/packages/jobs/src/inngest/functions/scheduled/purge-company.integration.test.ts@@ -16,7 +16,16 @@ import {purgeCompany} from "./purge-company";-const runDatabaseTests = process.env.RUN_PURGE_DB_TESTS === "true";+const LOCAL_HOSTS = ["localhost", "127.0.0.1", "[::1]"];+const hasLocalDatabase = (() => {+ try {+ return LOCAL_HOSTS.includes(+ new URL(process.env.SUPABASE_DB_URL ?? "").hostname+ );+ } catch {+ return false;+ }+})();class Rollback extends Error {}@@ -59,7 +68,7 @@ async function danglingForeignKeys(return counts;}-describe.skipIf(!runDatabaseTests)("purgeCompany (Postgres)", () => {+describe.skipIf(!hasLocalDatabase)("purgeCompany (Postgres)", () => {it("deletes a company, posted journals included, leaving no dangling rows", async () => {const db = getJobDatabaseClient();const replica = await canSetReplicationRole(db);diff --git a/packages/jobs/src/inngest/functions/scheduled/purge-inactive-companies.test.ts b/packages/jobs/src/inngest/functions/scheduled/purge-inactive-companies.test.tsindex fd68570b78..66fbf36ceb 100644--- a/packages/jobs/src/inngest/functions/scheduled/purge-inactive-companies.test.ts+++ b/packages/jobs/src/inngest/functions/scheduled/purge-inactive-companies.test.ts@@ -4,10 +4,10 @@import { describe, expect, it, vi } from "vitest";-vi.mock("../../client", () => ({- inngest: { createFunction: () => ({}) }+// @carbon/auth builds its Supabase client at import time.+vi.mock("@carbon/auth/client.server", () => ({+ getCarbonServiceRole: vi.fn()}));-vi.mock("./company-cleanup", () => ({}));const { purgeRefusal, resolvePurgeOptions } = await import("./purge-inactive-companies"diff --git a/packages/jobs/src/inngest/functions/scheduled/scheduled-sql-thresholds.test.ts b/packages/jobs/src/inngest/functions/scheduled/scheduled-sql-thresholds.test.tsdeleted file mode 100644index 3a863b8971..0000000000--- a/packages/jobs/src/inngest/functions/scheduled/scheduled-sql-thresholds.test.ts+++ /dev/null@@ -1,64 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { readdirSync, readFileSync } from "node:fs";-import { describe, expect, it, vi } from "vitest";--vi.mock("@carbon/auth/client.server", () => ({- getCarbonServiceRole: vi.fn()-}));-vi.mock("../../../db", () => ({ getJobDatabaseClient: vi.fn() }));-vi.mock("../../client", () => ({- inngest: { createFunction: vi.fn(() => ({})) }-}));--import { DIGEST_MIN_AGE_MIN, DIGEST_THRESHOLD } from "./notification-digest";-import {- COMPACT_DETAIL_DAYS,- FULL_DETAIL_DAYS,- RUN_HEADER_DAYS,- STALE_RUN_HOURS,- TERMINAL-} from "./workflow-run-retention";--// pg_cron wakes these functions only when `util.*_has_work()` says a run would-// do something, and that SQL repeats the constants above. A constant changed-// on one side only either wakes the function for nothing or leaves work-// undone, so read the newest definition of each and compare.-const MIGRATIONS = new URL(- "../../../../../database/supabase/migrations/",- import.meta.url-);--function newestDefinition(fn: string): string {- const marker = `CREATE OR REPLACE FUNCTION ${fn}(`;- for (const name of readdirSync(MIGRATIONS).sort().reverse()) {- const sql = readFileSync(new URL(name, MIGRATIONS), "utf8");- const start = sql.lastIndexOf(marker);- if (start === -1) continue;- const end = sql.indexOf("$$;", start);- if (end === -1) throw new Error(`${fn} in ${name} has no closing $$;`);- return sql.slice(start, end);- }- throw new Error(`No migration defines ${fn}`);-}--describe("SQL work checks repeat the functions' constants", () => {- it("util.notification_digest_has_work", () => {- const sql = newestDefinition("util.notification_digest_has_work");- expect(sql).toContain(`c.total >= ${DIGEST_THRESHOLD}`);- expect(sql).toContain(`interval '${DIGEST_MIN_AGE_MIN} minutes'`);- });-- it("util.workflow_run_retention_has_work", () => {- const sql = newestDefinition("util.workflow_run_retention_has_work");- expect(sql).toContain(`interval '${STALE_RUN_HOURS} hours'`);- expect(sql).toContain(`interval '${FULL_DETAIL_DAYS} days'`);- expect(sql).toContain(`interval '${COMPACT_DETAIL_DAYS} days'`);- expect(sql).toContain(`interval '${RUN_HEADER_DAYS} days'`);- expect(sql).toContain(- `IN (${TERMINAL.map((status) => `'${status}'`).join(", ")})`- );- });-});diff --git a/packages/jobs/src/inngest/functions/scheduled/workflow-run-retention.test.ts b/packages/jobs/src/inngest/functions/scheduled/workflow-run-retention.test.tsdeleted file mode 100644index 58170d3b69..0000000000--- a/packages/jobs/src/inngest/functions/scheduled/workflow-run-retention.test.ts+++ /dev/null@@ -1,56 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import {- DummyDriver,- Kysely,- PostgresAdapter,- PostgresIntrospector,- PostgresQueryCompiler-} from "kysely";-import { describe, expect, it } from "vitest";-import type { JobDatabase } from "../../../db";-import { terminalRunsQuery } from "./workflow-run-retention";--/** Compiles SQL without a connection — the passes below are pure query shape. */-const db = new Kysely<never>({- dialect: {- createAdapter: () => new PostgresAdapter(),- createDriver: () => new DummyDriver(),- createIntrospector: (i) => new PostgresIntrospector(i),- createQueryCompiler: () => new PostgresQueryCompiler()- }-}) as unknown as JobDatabase;--const sqlFor = (stage?: "uncompacted" | "hasSteps") =>- terminalRunsQuery(db, "2026-08-01T00:00:00.000Z", 500, stage).compile().sql;--describe("terminalRunsQuery", () => {- it("orders oldest first so a backlog drains", () => {- // Without this every pass re-reads the same unordered page each night.- expect(sqlFor()).toContain(- `order by COALESCE("completedAt", "createdAt") asc`- );- });-- it("narrows the compaction pass to runs not yet compacted", () => {- expect(sqlFor("uncompacted")).toContain(`"compactedAt" is null`);- });-- it("narrows the drop pass to compacted runs that still have steps", () => {- const sql = sqlFor("hasSteps");- // Both predicates are what make this pass advance: a run drops out of the- // candidate set as soon as its step rows are gone.- expect(sql).toContain(`"compactedAt" is not null`);- expect(sql).toContain(`exists`);- expect(sql).toContain(`from "workflowStepRun" as "step"`);- expect(sql).toContain(`"step"."runId" = "workflowRun"."id"`);- expect(sql).toContain(`"step"."companyId" = "workflowRun"."companyId"`);- });-- it("does not gate the header purge on compaction", () => {- // Headers age out at 90 days whether or not their steps were ever compacted.- expect(sqlFor()).not.toContain(`"compactedAt"`);- });-});diff --git a/packages/jobs/src/inngest/functions/scheduled/workflow-run-retention.ts b/packages/jobs/src/inngest/functions/scheduled/workflow-run-retention.tsindex ee6f9c9e3e..5f95f97dad 100644--- a/packages/jobs/src/inngest/functions/scheduled/workflow-run-retention.ts+++ b/packages/jobs/src/inngest/functions/scheduled/workflow-run-retention.ts@@ -15,7 +15,7 @@ import { inngest } from "../../client";// Compact runs BEFORE deleting their steps so compactedAt is always set first.// These ages are repeated in `util.workflow_run_retention_has_work` (the// migration that defines it). Change both;-// `scheduled-sql-thresholds.test.ts` fails when the two disagree.+// the `scheduled-sql-constants` check (@carbon/checks) fails when they disagree.export const STALE_RUN_HOURS = 24;export const FULL_DETAIL_DAYS = 7;export const COMPACT_DETAIL_DAYS = 30;@@ -51,7 +51,7 @@ function groupByCompany(* night. `stage` narrows to the runs a pass can still make progress on: without* it a pass that deletes nothing re-picks the same rows forever.*/-export function terminalRunsQuery(+function terminalRunsQuery(db: JobDatabase,cutoff: string,limit: number,diff --git a/packages/jobs/src/inngest/functions/tasks/changelog-dispatch.email.test.ts b/packages/jobs/src/inngest/functions/tasks/changelog-dispatch.email.test.tsdeleted file mode 100644index 61048c3390..0000000000--- a/packages/jobs/src/inngest/functions/tasks/changelog-dispatch.email.test.ts+++ /dev/null@@ -1,34 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { render } from "react-email";-import { describe, expect, it, vi } from "vitest";--// @carbon/env validates required vars at import; the template reaches it via Logo.-vi.mock("@carbon/env", () => ({- getAppUrl: () => "https://app.carbon.ms",- NODE_ENV: "test",- VERCEL_ENV: undefined-}));--import { ChangelogEntryEmail } from "@carbon/documents/email";--// Here rather than in @carbon/documents, whose test setup has no env.-describe("ChangelogEntryEmail", () => {- it("renders the notification card with escaped title and the unsubscribe link", async () => {- const html = await render(- ChangelogEntryEmail({- title: "Ship <faster> & better",- description: "A & B",- date: "04 Sep 2026",- readUrl: "https://docs.carbon.ms/changelog/x",- manageUrl: "https://app.carbon.ms/x/account/notifications"- })- );- expect(html).toContain("Ship <faster> & better");- expect(html).toContain("https://app.carbon.ms/x/account/notifications");- expect(html).toContain("nf-card");- expect(html).toContain("Changelog · 04 Sep 2026");- });-});diff --git a/packages/jobs/src/invoicing/automate-invoice.test.ts b/packages/jobs/src/invoicing/automate-invoice.test.tsindex e1c631d7a4..17efd5af03 100644--- a/packages/jobs/src/invoicing/automate-invoice.test.ts+++ b/packages/jobs/src/invoicing/automate-invoice.test.ts@@ -33,7 +33,7 @@ vi.mock("@carbon/ee/rules.server", () => ({// The Stripe API call only: the connected-account and customer-link reads run// for real against the fake client. The Stripe SDK module is replaced so// loading the real reads does not construct a Stripe or Supabase client.-vi.mock("../../../stripe/src/connect.server", () => ({+vi.mock("@carbon/stripe/connect.server", () => ({createAndSendConnectInvoice: () => {throw new Error("The Stripe API is not reachable in tests");}diff --git a/packages/jobs/src/workflows/actions/dispatcher.test.ts b/packages/jobs/src/workflows/actions/dispatcher.test.tsdeleted file mode 100644index 77a3a1ede4..0000000000--- a/packages/jobs/src/workflows/actions/dispatcher.test.ts+++ /dev/null@@ -1,22 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { describe, expect, it } from "vitest";-import {- getWorkflowDispatch,- setWorkflowDispatch,- type WorkflowDispatch-} from "./dispatcher";--describe("the workflow dispatch seam", () => {- it("has nothing until the app registers one", () => {- expect(getWorkflowDispatch()).toBeUndefined();- });-- it("hands back exactly what was registered", async () => {- const fake: WorkflowDispatch = async () => ({ success: true, data: null });- setWorkflowDispatch(fake);- expect(getWorkflowDispatch()).toBe(fake);- });-});diff --git a/packages/jobs/src/workflows/actions/operations.test.ts b/packages/jobs/src/workflows/actions/operations.test.tsindex 29dfd83328..2f5dd25f91 100644--- a/packages/jobs/src/workflows/actions/operations.test.ts+++ b/packages/jobs/src/workflows/actions/operations.test.ts@@ -14,11 +14,7 @@ import { runOperation } from "./operations";interface Call {table: string;- columns?: string;- head: boolean;eq: Record<string, unknown>;- in: Record<string, unknown>;- order?: { column: string; ascending?: boolean };}interface StubResult {@@ -30,12 +26,12 @@ interface StubResult {error?: unknown;}-/** A chainable stand-in for the owner's client that records how it was queried. */+/** A chainable stand-in for the owner's client; it records the `eq` filters for the scoping check. */function stubClient(result: StubResult = {}) {const calls: Call[] = [];const from = (table: string) => {- const call: Call = { table, head: false, eq: {}, in: {} };+ const call: Call = { table, eq: {} };calls.push(call);const settle = () => ({@@ -45,29 +41,15 @@ function stubClient(result: StubResult = {}) {});const builder = {- select(columns: string, options?: { head?: boolean }) {- call.columns = columns;- call.head = options?.head === true;- return builder;- },+ select: () => builder,eq(column: string, value: unknown) {call.eq[column] = value;return builder;},- in(column: string, value: unknown) {- call.in[column] = value;- return builder;- },- not() {- return builder;- },- order(column: string, options?: { ascending?: boolean }) {- call.order = { column, ascending: options?.ascending };- return builder;- },- limit() {- return builder;- },+ in: () => builder,+ not: () => builder,+ order: () => builder,+ limit: () => builder,maybeSingle: async () => ({data: result.row ?? null,error: result.error ?? null@@ -87,12 +69,6 @@ function stubClient(result: StubResult = {}) {};}-function firstCall(calls: Call[]): Call {- const call = calls[0];- if (call === undefined) throw new Error("the operation read nothing");- return call;-}-const COMPANY = "co1";async function run(@@ -114,36 +90,20 @@ async function run(return { outcome, calls };}-describe("stored totals", () => {- it("reads a purchase order total off the view", async () => {- const { outcome, calls } = await run(- "purchaseOrder.total",- "purchaseOrder",- "po1",- { row: { orderTotal: 1250.5 } }- );-- expect(outcome).toEqual({- ok: true,- value: { kind: "primitive", of: "number", value: 1250.5 }- });- expect(firstCall(calls).table).toBe("purchaseOrders");- expect(firstCall(calls).eq).toEqual({ id: "po1", companyId: COMPANY });- });-- it("reads a sales order total off the view", async () => {- const { outcome, calls } = await run(- "salesOrder.total",- "salesOrder",- "so1",- { row: { orderTotal: 42 } }- );+const number = (value: number) => ({+ ok: true,+ value: { kind: "primitive", of: "number", value }+});- expect(outcome).toEqual({- ok: true,- value: { kind: "primitive", of: "number", value: 42 }+describe("stored totals", () => {+ it.each([+ ["purchaseOrder.total", "purchaseOrder"],+ ["salesOrder.total", "salesOrder"]+ ])("reads %s off the order view", async (operationId, entity) => {+ const { outcome } = await run(operationId, entity, "o1", {+ row: { orderTotal: 1250.5 }});- expect(firstCall(calls).table).toBe("salesOrders");+ expect(outcome).toEqual(number(1250.5));});it("refuses rather than inventing a total for a record it cannot find", async () => {@@ -159,238 +119,109 @@ describe("stored totals", () => {});});- it("refuses a quote total, which no single read can answer", async () => {+ it("refuses a quote total without reading anything", async () => {+ // A quote prices several quantity breaks; no single read can answer it.const { outcome, calls } = await run("quote.total", "quote", "q1");expect(outcome.ok).toBe(false);- expect(calls).toHaveLength(0);+ expect(calls).toEqual([]);});});-describe("line counts", () => {- const cases = [- {- id: "purchaseOrder.lineCount",- entity: "purchaseOrder",- table: "purchaseOrderLine",- parent: "purchaseOrderId"- },- {- id: "salesOrder.lineCount",- entity: "salesOrder",- table: "salesOrderLine",- parent: "salesOrderId"- },- {- id: "receipt.lineCount",- entity: "receipt",- table: "receiptLine",- parent: "receiptId"- },- {- id: "shipment.lineCount",- entity: "shipment",- table: "shipmentLine",- parent: "shipmentId"- }- ];-- for (const { id, entity, table, parent } of cases) {- it(`counts ${table} rows for its parent`, async () => {- const { outcome, calls } = await run(id, entity, "p1", { count: 7 });-- expect(outcome).toEqual({- ok: true,- value: { kind: "primitive", of: "number", value: 7 }- });- expect(firstCall(calls).table).toBe(table);- expect(firstCall(calls).head).toBe(true);- expect(firstCall(calls).eq).toEqual({- [parent]: "p1",- companyId: COMPANY- });- });- }+describe("counts", () => {+ it.each([+ ["purchaseOrder.lineCount", "purchaseOrder"],+ ["salesOrder.lineCount", "salesOrder"],+ ["receipt.lineCount", "receipt"],+ ["shipment.lineCount", "shipment"],+ ["job.operationCount", "job"],+ ["job.openOperationCount", "job"],+ ["nonConformance.openTaskCount", "nonConformance"]+ ])("returns the row count for %s", async (operationId, entity) => {+ const { outcome } = await run(operationId, entity, "p1", { count: 7 });+ expect(outcome).toEqual(number(7));+ });- it("reads no rows back when the count is missing", async () => {+ it("reads a missing count as zero", async () => {const { outcome } = await run("receipt.lineCount", "receipt", "r1", {count: null});- expect(outcome).toEqual({- ok: true,- value: { kind: "primitive", of: "number", value: 0 }- });- });-});--describe("job operations", () => {- it("sums scrap across the job's operations", async () => {- const { outcome, calls } = await run(- "job.totalScrapQuantity",- "job",- "j1",- {- rows: [- { quantityScrapped: 3 },- { quantityScrapped: null },- { quantityScrapped: 2 }- ]- }- );-- expect(outcome).toEqual({- ok: true,- value: { kind: "primitive", of: "number", value: 5 }- });- expect(firstCall(calls).table).toBe("jobOperation");- expect(firstCall(calls).eq).toEqual({ jobId: "j1", companyId: COMPANY });- });-- it("turns that scrap into a percentage of the job quantity", async () => {- const { outcome, calls } = await run("job.scrapPercentage", "job", "j1", {- rows: [{ quantityScrapped: 5 }],- row: { quantity: 20 }- });-- expect(outcome).toEqual({- ok: true,- value: { kind: "primitive", of: "number", value: 25 }- });- expect(calls.map((call) => call.table)).toEqual(["jobOperation", "job"]);+ expect(outcome).toEqual(number(0));});- it("returns zero rather than dividing by a zero job quantity", async () => {- const { outcome } = await run("job.scrapPercentage", "job", "j1", {- rows: [{ quantityScrapped: 5 }],- row: { quantity: 0 }- });-- expect(outcome).toEqual({- ok: true,- value: { kind: "primitive", of: "number", value: 0 }- });- });-- it("counts every operation on the job", async () => {- const { outcome, calls } = await run("job.operationCount", "job", "j1", {- count: 4- });-- expect(outcome).toEqual({- ok: true,- value: { kind: "primitive", of: "number", value: 4 }+ it("fails when the count read errors", async () => {+ const { outcome } = await run("receipt.lineCount", "receipt", "r1", {+ error: { message: "denied" }});- expect(firstCall(calls).in).toEqual({});- });-- it("counts only the operations that are not finished", async () => {- const { outcome, calls } = await run(- "job.openOperationCount",- "job",- "j1",- {- count: 2- }- );-expect(outcome).toEqual({- ok: true,- value: { kind: "primitive", of: "number", value: 2 }+ ok: false,+ error: "We could not read the records this calculation needs."});- const statuses = firstCall(calls).in.status as string[];- expect(statuses).toContain("Todo");- expect(statuses).toContain("In Progress");- expect(statuses).not.toContain("Done");- expect(statuses).not.toContain("Canceled");});+});- it("reads the earliest scheduled start as a date", async () => {- const { outcome, calls } = await run(- "job.earliestOperationStart",- "job",- "j1",- { row: { startDate: "2026-03-04" } }- );+describe("job scrap", () => {+ const scrapped = [+ { quantityScrapped: 3 },+ { quantityScrapped: null },+ { quantityScrapped: 2 }+ ];- expect(outcome).toEqual({- ok: true,- value: {- kind: "primitive",- of: "date",- value: new Date("2026-03-04").toISOString()- }- });- expect(firstCall(calls).order).toEqual({- column: "startDate",- ascending: true+ it("sums scrap across the job's operations, reading null as zero", async () => {+ const { outcome } = await run("job.totalScrapQuantity", "job", "j1", {+ rows: scrapped});+ expect(outcome).toEqual(number(5));});- it("reads the latest scheduled end as a date", async () => {- const { outcome, calls } = await run(- "job.latestOperationEnd",- "job",- "j1",- { row: { dueDate: "2026-05-06" } }- );+ it.each([+ [20, 25],+ // A job that makes nothing cannot have scrapped a proportion of it.+ [0, 0]+ ])(+ "gives 5 scrapped on a job of %i as %i percent",+ async (quantity, percent) => {+ const { outcome } = await run("job.scrapPercentage", "job", "j1", {+ rows: scrapped,+ row: { quantity }+ });+ expect(outcome).toEqual(number(percent));+ }+ );+});+describe("job schedule dates", () => {+ it.each([+ ["job.earliestOperationStart", { startDate: "2026-03-04" }],+ ["job.latestOperationEnd", { dueDate: "2026-03-04" }]+ ])("reads %s as a date", async (operationId, row) => {+ const { outcome } = await run(operationId, "job", "j1", { row });expect(outcome).toEqual({ok: true,value: {kind: "primitive",of: "date",- value: new Date("2026-05-06").toISOString()+ value: "2026-03-04T00:00:00.000Z"}});- expect(firstCall(calls).order).toEqual({- column: "dueDate",- ascending: false- });});- it("says nothing rather than a made-up date when no operation is scheduled", async () => {- const { outcome } = await run("job.earliestOperationStart", "job", "j1", {- row: null- });- expect(outcome).toEqual({- ok: true,- value: { kind: "primitive", of: "null", value: null }- });- });+ it.each(["job.earliestOperationStart", "job.latestOperationEnd"])(+ "returns null rather than a made-up date when %s finds no scheduled operation",+ async (operationId) => {+ const { outcome } = await run(operationId, "job", "j1", { row: null });+ expect(outcome).toEqual({+ ok: true,+ value: { kind: "primitive", of: "null", value: null }+ });+ }+ );});-describe("the remaining reads", () => {- it("counts an issue's unfinished tasks", async () => {- const { outcome, calls } = await run(- "nonConformance.openTaskCount",- "nonConformance",- "nc1",- { count: 3 }- );-- expect(outcome).toEqual({- ok: true,- value: { kind: "primitive", of: "number", value: 3 }- });- expect(firstCall(calls).table).toBe("nonConformanceActionTask");- expect(firstCall(calls).eq).toEqual({- nonConformanceId: "nc1",- companyId: COMPANY- });- expect(firstCall(calls).in.status).toEqual(["Pending", "In Progress"]);- });-- it("sums an item's quantity on hand across locations", async () => {- const { outcome, calls } = await run("item.quantityOnHand", "item", "i1", {- rows: [{ quantityOnHand: 10 }, { quantityOnHand: 2.5 }]- });-- expect(outcome).toEqual({- ok: true,- value: { kind: "primitive", of: "number", value: 12.5 }- });- expect(firstCall(calls).table).toBe("itemStockQuantities");- expect(firstCall(calls).eq).toEqual({ itemId: "i1", companyId: COMPANY });+it("sums an item's quantity on hand across locations", async () => {+ const { outcome } = await run("item.quantityOnHand", "item", "i1", {+ rows: [{ quantityOnHand: 10 }, { quantityOnHand: 2.5 }]});+ expect(outcome).toEqual(number(12.5));});describe("the dispatcher", () => {diff --git a/packages/jobs/src/workflows/actions/services.test.ts b/packages/jobs/src/workflows/actions/services.test.tsindex b2fb898123..ec8c7bbc4a 100644--- a/packages/jobs/src/workflows/actions/services.test.ts+++ b/packages/jobs/src/workflows/actions/services.test.ts@@ -3,45 +3,15 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import type { Database } from "@carbon/database";-import { createWorkflowCatalog, entityValue } from "@carbon/ee/workflows";+import { createWorkflowCatalog } from "@carbon/ee/workflows";import type { SupabaseClient } from "@supabase/supabase-js";-import { beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it } from "vitest";import { createWorkflowServices } from "./services";-vi.mock("./create", () => ({- runCreateAction: vi.fn(async () => ({ ok: true, outputs: {} }))-}));-vi.mock("./notify", () => ({- runNotifyAction: vi.fn(async () => ({ ok: true, outputs: {} }))-}));-vi.mock("./update", () => ({- runUpdateAction: vi.fn(async () => ({ ok: true, outputs: {} }))-}));-vi.mock("./webhook", () => ({- runWebhookAction: vi.fn(async () => ({ ok: true, outputs: {} }))-}));-vi.mock("./operations", () => ({- runOperation: vi.fn(async () => ({ ok: true, value: null }))-}));-vi.mock("./search", () => ({- runSearch: vi.fn(async () => ({ ok: true, value: null }))-}));-vi.mock("./dispatcher", () => ({ getWorkflowDispatch: vi.fn() }));--const { runCreateAction } = await import("./create");-const { runNotifyAction } = await import("./notify");-const { runUpdateAction } = await import("./update");-const { runWebhookAction } = await import("./webhook");-const { runOperation } = await import("./operations");-const { runSearch } = await import("./search");-const { getWorkflowDispatch } = await import("./dispatcher");--const client = {} as SupabaseClient<Database>;-const dispatch = vi.fn();-function services() {return createWorkflowServices({- client,+ // Never reached: both refusals return before any executor runs.+ client: {} as SupabaseClient<Database>,catalog: createWorkflowCatalog(),companyId: "co1",companyGroupId: "cg1",@@ -52,110 +22,20 @@ function services() {});}-beforeEach(() => {- vi.clearAllMocks();- vi.mocked(getWorkflowDispatch).mockReturnValue(dispatch);-});--describe("runAction routing", () => {- it("sends notify to the notify action", async () => {- await services().runAction("notify", {});- expect(runNotifyAction).toHaveBeenCalledWith(- expect.objectContaining({- companyId: "co1",- runId: "run1"- })- );- expect(runUpdateAction).not.toHaveBeenCalled();- });-- it("sends webhook to the webhook action", async () => {- await services().runAction("webhook", {});- expect(runWebhookAction).toHaveBeenCalledWith(- expect.objectContaining({ companyId: "co1", workflowId: "wf1" })- );- });-- it("sends an update id to the update action, with its entity", async () => {- const inputs = { job: entityValue("job", "j1") };- await services().runAction("job.update", inputs);- expect(runUpdateAction).toHaveBeenCalledWith(- expect.objectContaining({- entity: "job",- companyId: "co1",- ownerId: "u1",- inputs- })- );- expect(runCreateAction).not.toHaveBeenCalled();- });-- it("sends a create id to the create action, with the tool it calls", async () => {- await services().runAction("job.create", {});- expect(runCreateAction).toHaveBeenCalledWith(- expect.objectContaining({- call: "production_insertJob",- entity: "job",- dispatch,- context: {- client,- companyId: "co1",- companyGroupId: "cg1",- userId: "u1",- permissions: {}- }- })- );- });-- it("refuses a create when no dispatcher was installed", async () => {- vi.mocked(getWorkflowDispatch).mockReturnValue(undefined);- expect(await services().runAction("job.create", {})).toEqual({- ok: false,- error: "This step is not available in this environment."- });- expect(runCreateAction).not.toHaveBeenCalled();- });-- // The regression this file exists for: routing off the id's shape would send- // this to the update executor, where it would write to a table nobody declared.+describe("runAction", () => {+ // Routing off the id's shape would send this to the update executor, which+ // would write to a table no action declared.it("refuses an unknown id that merely looks like an update", async () => {expect(await services().runAction("madeUp.update", {})).toEqual({ok: false,error: "This step is no longer available."});- expect(runUpdateAction).not.toHaveBeenCalled();- expect(runCreateAction).not.toHaveBeenCalled();});- it("refuses an id the catalog has never heard of", async () => {- expect(await services().runAction("nonsense", {})).toEqual({+ it("refuses a create when the app has installed no dispatcher", async () => {+ expect(await services().runAction("job.create", {})).toEqual({ok: false,- error: "This step is no longer available."- });- });-});--describe("the other two services", () => {- it("passes an operation through with the company", async () => {- const inputs = { job: entityValue("job", "j1") };- await services().runOperation("job.operationCount", inputs);- expect(runOperation).toHaveBeenCalledWith({- client,- companyId: "co1",- operationId: "job.operationCount",- inputs- });- });-- it("passes a search through with the company", async () => {- await services().search({ entity: "job", returns: "one", criteria: [] });- expect(runSearch).toHaveBeenCalledWith({- client,- companyId: "co1",- entity: "job",- returns: "one",- criteria: []+ error: "This step is not available in this environment."});});});diff --git a/packages/jobs/src/workflows/engine/batch.test.ts b/packages/jobs/src/workflows/engine/batch.test.tsindex c754408b1c..4f03de8d6f 100644--- a/packages/jobs/src/workflows/engine/batch.test.ts+++ b/packages/jobs/src/workflows/engine/batch.test.ts@@ -41,15 +41,6 @@ vi.mock("./owner", () => ({hasPermission: () => true}));vi.mock("../actions", () => ({ createWorkflowServices: vi.fn() }));-// The real module pulls in the email templates and @carbon/env; the engine only wants a URL.-vi.mock("../../inngest/functions/notifications/content", () => ({- buildNotificationLink: (- event: string,- documentId: string,- companyId: string- ) =>- `https://erp.test/api/link?event=${event}&documentId=${documentId}&companyId=${companyId}`-}));const { executeWorkflowRun } = await import("./execute");const { loadRunContext } = await import("./log");diff --git a/packages/jobs/src/workflows/engine/end-to-end.test.ts b/packages/jobs/src/workflows/engine/end-to-end.test.tsindex 99aa58f01a..b11eeee8c5 100644--- a/packages/jobs/src/workflows/engine/end-to-end.test.ts+++ b/packages/jobs/src/workflows/engine/end-to-end.test.ts@@ -44,15 +44,6 @@ vi.mock("./owner", () => ({hasPermission: () => true}));vi.mock("../actions", () => ({ createWorkflowServices: vi.fn() }));-// The real module pulls in the email templates and @carbon/env; the engine only wants a URL.-vi.mock("../../inngest/functions/notifications/content", () => ({- buildNotificationLink: (- event: string,- documentId: string,- companyId: string- ) =>- `https://erp.test/api/link?event=${event}&documentId=${documentId}&companyId=${companyId}`-}));const { executeWorkflowRun } = await import("./execute");const { loadRunContext } = await import("./log");@@ -169,106 +160,122 @@ beforeEach(() => {});});-describe("a workflow end to end", () => {- it("notifies a role with a sentence built from the record", async () => {- seed("purchaseOrder.status.changed", {- formatVersion: 2,- nodes: [- {- id: "t1",- type: "trigger",- position: { x: 0, y: 0 },- data: { events: ["purchaseOrder.status.changed"], origin: "Both" }- },- {- id: "total",- type: "compute",- position: { x: 0, y: 1 },- data: {- operation: "purchaseOrder.total",- inputs: {- purchaseOrder: { kind: "ref", nodeId: "t1", output: "record" }- }- }- },- {- id: "over",- type: "condition",- position: { x: 0, y: 2 },- data: {- paths: [- {- id: "p1",- kind: "if",- combinator: "and",- clauses: [- {- left: { kind: "ref", nodeId: "total", output: "result" },- operator: "gt",- right: {- kind: "literal",- type: { kind: "primitive", of: "number" },- value: 10000- }- }- ]- }- ]- }- },+type Ref = { kind: "ref"; nodeId: string; output: string; path?: string[] };+const ref = (nodeId: string, output: string, path?: string[]): Ref =>+ path+ ? { kind: "ref", nodeId, output, path }+ : { kind: "ref", nodeId, output };+const literal = (type: unknown, value: unknown) => ({+ kind: "literal",+ type,+ value+});+const template = (...parts: (string | Ref)[]) => ({+ kind: "template",+ parts: parts.map((part) =>+ typeof part === "string" ? { kind: "text", text: part } : part+ )+});++/** Nodes laid out top to bottom; each edge is [source, sourceHandle, target]. */+function definition(+ nodes: [id: string, type: string, data: unknown][],+ edges: [source: string, handle: string, target: string][]+): SeedDefinition {+ return {+ formatVersion: 2,+ nodes: nodes.map(([id, type, data], y) => ({+ id,+ type,+ position: { x: 0, y },+ data+ })),+ edges: edges.map(([source, sourceHandle, target], i) => ({+ id: `e${i + 1}`,+ source,+ sourceHandle,+ target,+ targetHandle: "in"+ }))+ };+}++/** trigger → compute → "result > threshold" → action. */+function computeThenAct(params: {+ event: string;+ operation: string;+ operationInputs: Record<string, Ref>;+ threshold: number;+ actionId: string;+ action: string;+ actionInputs: Record<string, unknown>;+}): SeedDefinition {+ return definition(+ [+ ["t1", "trigger", { events: [params.event], origin: "Both" }],+ [+ "compute",+ "compute",+ { operation: params.operation, inputs: params.operationInputs }+ ],+ [+ "over",+ "condition",{- id: "tell",- type: "action",- position: { x: 0, y: 3 },- data: {- action: "notify",- inputs: {- role: {- kind: "literal",- type: { kind: "entity", of: "group" },- value: "g-buyers"- },- subject: {- kind: "template",- parts: [- { kind: "text", text: "Purchase order " },- {- kind: "ref",- nodeId: "t1",- output: "record",- path: ["purchaseOrderId"]- },- { kind: "text", text: " is over $10,000" }- ]- }+ paths: [+ {+ id: "p1",+ kind: "if",+ combinator: "and",+ clauses: [+ {+ left: ref("compute", "result"),+ operator: "gt",+ right: literal(+ { kind: "primitive", of: "number" },+ params.threshold+ )+ }+ ]}- }+ ]}],- edges: [- {- id: "e1",- source: "t1",- sourceHandle: DEFAULT_HANDLE,- target: "total",- targetHandle: "in"- },- {- id: "e2",- source: "total",- sourceHandle: DEFAULT_HANDLE,- target: "over",- targetHandle: "in"- },- {- id: "e3",- source: "over",- sourceHandle: "p1",- target: "tell",- targetHandle: "in"- }+ [+ params.actionId,+ "action",+ { action: params.action, inputs: params.actionInputs }]- });+ ],+ [+ ["t1", DEFAULT_HANDLE, "compute"],+ ["compute", DEFAULT_HANDLE, "over"],+ ["over", "p1", params.actionId]+ ]+ );+}++describe("a workflow end to end", () => {+ it("notifies a role with a sentence built from the record", async () => {+ seed(+ "purchaseOrder.status.changed",+ computeThenAct({+ event: "purchaseOrder.status.changed",+ operation: "purchaseOrder.total",+ operationInputs: { purchaseOrder: ref("t1", "record") },+ threshold: 10000,+ actionId: "tell",+ action: "notify",+ actionInputs: {+ role: literal({ kind: "entity", of: "group" }, "g-buyers"),+ subject: template(+ "Purchase order ",+ ref("t1", "record", ["purchaseOrderId"]),+ " is over $10,000"+ )+ }+ })+ );const { step } = harness();const { runAction } = withServices({@@ -341,87 +348,55 @@ describe("a workflow end to end", () => {});it("hands a created record on to the next step", async () => {- seed("sales.quoteAccepted", {- formatVersion: 2,- nodes: [- {- id: "t1",- type: "trigger",- position: { x: 0, y: 0 },- data: { events: ["sales.quoteAccepted"], origin: "Both" }- },- {- id: "create",- type: "action",- position: { x: 0, y: 1 },- data: {- action: "salesOrder.create",- inputs: {- customerId: {- kind: "literal",- type: { kind: "entity", of: "customer" },- value: "c-acme"+ seed(+ "sales.quoteAccepted",+ definition(+ [+ [+ "t1",+ "trigger",+ { events: ["sales.quoteAccepted"], origin: "Both" }+ ],+ [+ "create",+ "action",+ {+ action: "salesOrder.create",+ inputs: {+ customerId: literal(+ { kind: "entity", of: "customer" },+ "c-acme"+ )}}- }- },- {- id: "tell",- type: "action",- position: { x: 0, y: 2 },- data: {- action: "notify",- inputs: {- user: {- kind: "literal",- type: { kind: "entity", of: "user" },- value: "u-sales"- },- subject: {- kind: "template",- parts: [- { kind: "text", text: "Sales order " },- {- kind: "ref",- nodeId: "create",- output: "record",- path: ["salesOrderId"]- },- { kind: "text", text: " is ready" }- ]- },- aboutId: {- kind: "ref",- nodeId: "create",- output: "record",- path: ["id"]- },- aboutType: {- kind: "literal",- type: { kind: "primitive", of: "string" },- value: "salesOrder"+ ],+ [+ "tell",+ "action",+ {+ action: "notify",+ inputs: {+ user: literal({ kind: "entity", of: "user" }, "u-sales"),+ subject: template(+ "Sales order ",+ ref("create", "record", ["salesOrderId"]),+ " is ready"+ ),+ aboutId: ref("create", "record", ["id"]),+ aboutType: literal(+ { kind: "primitive", of: "string" },+ "salesOrder"+ )}}- }- }- ],- edges: [- {- id: "e1",- source: "t1",- sourceHandle: DEFAULT_HANDLE,- target: "create",- targetHandle: "in"- },- {- id: "e2",- source: "create",- sourceHandle: SUCCESS_HANDLE,- target: "tell",- targetHandle: "in"- }- ]- });+ ]+ ],+ [+ ["t1", DEFAULT_HANDLE, "create"],+ ["create", SUCCESS_HANDLE, "tell"]+ ]+ )+ );const { step } = harness();const { runAction } = withServices({@@ -461,241 +436,21 @@ describe("a workflow end to end", () => {);});- it("claims one step per job when a batched update follows a lookup", async () => {- seed("job.status.changed", {- formatVersion: 2,- nodes: [- {- id: "t1",- type: "trigger",- position: { x: 0, y: 0 },- data: { events: ["job.status.changed"], origin: "Both" }- },- {- id: "look",- type: "lookup",- position: { x: 0, y: 1 },- data: {- entity: "job",- returns: "list",- match: [- {- field: "status",- operator: "eq",- value: {- kind: "literal",- type: { kind: "primitive", of: "string" },- value: "Ready"- }- }- ]- }- },- {- id: "keep",- type: "filter",- position: { x: 0, y: 2 },- data: {- source: { kind: "ref", nodeId: "look", output: "result" },- combinator: "and",- clauses: [- {- left: { kind: "item", path: ["priority"] },- operator: "gt",- right: {- kind: "literal",- type: { kind: "primitive", of: "number" },- value: 0- }- }- ]- }- },- {- id: "bump",- type: "action",- position: { x: 0, y: 3 },- data: {- action: "job.update",- inputs: {- job: { kind: "ref", nodeId: "keep", output: "result" },- priority: {- kind: "literal",- type: { kind: "primitive", of: "number" },- value: 5- }- }- }- }- ],- edges: [- {- id: "e1",- source: "t1",- sourceHandle: DEFAULT_HANDLE,- target: "look",- targetHandle: "in"- },- {- id: "e2",- source: "look",- sourceHandle: SUCCESS_HANDLE,- target: "keep",- targetHandle: "in"- },- {- id: "e3",- source: "keep",- sourceHandle: DEFAULT_HANDLE,- target: "bump",- targetHandle: "in"- }- ]- });-- const { step } = harness();- const { runAction } = withServices({- // The last job is filtered out, so only two reach the batch.- search: () => {- const items = [- entityValue("job", "j1", { id: "j1", status: "Ready", priority: 3 }),- entityValue("job", "j2", { id: "j2", status: "Ready", priority: 1 }),- entityValue("job", "j3", { id: "j3", status: "Ready", priority: 0 })- ];- return {- ok: true,- value: { kind: "list", of: { kind: "entity", of: "job" }, items },- matched: items.length,- dropped: 0- };- },- runAction: (_actionId, inputs) => {- const job = inputs.job;- return job === undefined- ? { ok: false, error: "This turn had no item." }- : { ok: true, outputs: { record: job } };- }- });-- const result = await executeWorkflowRun({- payload: payloadFor("job.status.changed", {- kind: "record",- table: "job",- recordId: "j0",- operation: "UPDATE",- record: { id: "j0", status: "Ready" },- before: { id: "j0", status: "Draft" },- after: { id: "j0", status: "Ready" }- }),- step,- logger- });-- expect(result.status).toBe("Succeeded");- const keys = vi- .mocked(claimStep)- .mock.calls.filter(- ([, params]) => params.nodeId === "bump" && params.itemKey !== ""- )- .map(([, params]) => params.itemKey);- expect(keys).toEqual(["j1", "j2"]);- expect(runAction.mock.calls.map(([, inputs]) => inputs.job)).toEqual([- entityValue("job", "j1", { id: "j1", status: "Ready", priority: 3 }),- entityValue("job", "j2", { id: "j2", status: "Ready", priority: 1 })- ]);- });-it("opens one issue when a computed total clears the condition", async () => {- seed("job.scrapQuantity.changed", {- formatVersion: 2,- nodes: [- {- id: "t1",- type: "trigger",- position: { x: 0, y: 0 },- data: { events: ["job.scrapQuantity.changed"], origin: "Both" }- },- {- id: "scrap",- type: "compute",- position: { x: 0, y: 1 },- data: {- operation: "job.totalScrapQuantity",- inputs: { job: { kind: "ref", nodeId: "t1", output: "record" } }- }- },- {- id: "over",- type: "condition",- position: { x: 0, y: 2 },- data: {- paths: [- {- id: "p1",- kind: "if",- combinator: "and",- clauses: [- {- left: { kind: "ref", nodeId: "scrap", output: "result" },- operator: "gt",- right: {- kind: "literal",- type: { kind: "primitive", of: "number" },- value: 5- }- }- ]- }- ]- }- },- {- id: "open",- type: "action",- position: { x: 0, y: 3 },- data: {- action: "nonConformance.create",- inputs: {- name: {- kind: "template",- parts: [- { kind: "text", text: "Excess scrap on " },- {- kind: "ref",- nodeId: "t1",- output: "record",- path: ["jobId"]- }- ]- }- }- }- }- ],- edges: [- {- id: "e1",- source: "t1",- sourceHandle: DEFAULT_HANDLE,- target: "scrap",- targetHandle: "in"- },- {- id: "e2",- source: "scrap",- sourceHandle: DEFAULT_HANDLE,- target: "over",- targetHandle: "in"- },- {- id: "e3",- source: "over",- sourceHandle: "p1",- target: "open",- targetHandle: "in"+ seed(+ "job.scrapQuantity.changed",+ computeThenAct({+ event: "job.scrapQuantity.changed",+ operation: "job.totalScrapQuantity",+ operationInputs: { job: ref("t1", "record") },+ threshold: 5,+ actionId: "open",+ action: "nonConformance.create",+ actionInputs: {+ name: template("Excess scrap on ", ref("t1", "record", ["jobId"]))}- ]- });+ })+ );const { step } = harness();const { runAction } = withServices({diff --git a/packages/jobs/src/workflows/engine/execute.test.ts b/packages/jobs/src/workflows/engine/execute.test.tsindex bcd177bb98..711a06f4f4 100644--- a/packages/jobs/src/workflows/engine/execute.test.ts+++ b/packages/jobs/src/workflows/engine/execute.test.ts@@ -24,7 +24,12 @@ vi.mock("./ledger", () => ({settleStep: vi.fn(async () => {}),failInterruptedSteps: vi.fn(async () => 0)}));-vi.mock("./owner", () => ({+// @carbon/auth builds its Supabase client at import time; ./owner imports it.+vi.mock("@carbon/auth", () => ({}));+vi.mock("@carbon/auth/client.server", () => ({}));+// The owner's reads are faked; the permission rule itself is real.+vi.mock("./owner", async (importOriginal) => ({+ ...(await importOriginal<typeof import("./owner")>()),// The engine reads the company custom fields through this client; a bare {} has no// `.from`, so the stub answers that one query with an empty list.getOwnerClient: vi.fn(async () => ({@@ -34,24 +39,28 @@ vi.mock("./owner", () => ({})})})),- readOwnerPermissions: vi.fn(async () => ({})),- hasPermission: vi.fn(() => true)+ readOwnerPermissions: vi.fn()}));vi.mock("../actions", () => ({ createWorkflowServices: vi.fn() }));-// The real module pulls in the email templates and @carbon/env; the engine only wants a URL.-vi.mock("../../inngest/functions/notifications/content", () => ({- buildNotificationLink: (- event: string,- documentId: string,- companyId: string- ) =>- `https://erp.test/api/link?event=${event}&documentId=${documentId}&companyId=${companyId}`-}));const { executeWorkflowRun } = await import("./execute");const { loadRunContext, claimRun, finishRun } = await import("./log");const { claimStep, settleStep } = await import("./ledger");-const { hasPermission } = await import("./owner");+const { readOwnerPermissions } = await import("./owner");++/** The owner's Purchasing grants in co1. */+function purchasing(...actions: ("view" | "create" | "update" | "delete")[]) {+ const grant = (action: string) =>+ actions.includes(action as never) ? ["co1"] : [];+ return {+ purchasing: {+ view: grant("view"),+ create: grant("create"),+ update: grant("update"),+ delete: grant("delete")+ }+ };+}const { createWorkflowServices } = await import("../actions");const definition = {@@ -128,7 +137,9 @@ const runAction = vi.fn(beforeEach(() => {vi.clearAllMocks();vi.mocked(claimRun).mockResolvedValue(true);- vi.mocked(hasPermission).mockReturnValue(true);+ vi.mocked(readOwnerPermissions).mockResolvedValue(+ purchasing("view", "update")+ );vi.mocked(claimStep).mockResolvedValue({ claimed: true, stepRunId: "s1" });vi.mocked(createWorkflowServices).mockReturnValue({runAction,@@ -155,9 +166,7 @@ describe("the owner's permissions", () => {it("fails the action step by name when the owner has lost the module", async () => {const { step } = harness();// The trigger's own view check still passes; only the action's update is gone.- vi.mocked(hasPermission).mockImplementation(- (_permissions, _module, action) => action !== "update"- );+ vi.mocked(readOwnerPermissions).mockResolvedValue(purchasing("view"));const result = await executeWorkflowRun({ payload, step, logger });@@ -171,7 +180,7 @@ describe("the owner's permissions", () => {it("refuses the whole run when the trigger's own module is gone", async () => {const { ids, step } = harness();- vi.mocked(hasPermission).mockReturnValue(false);+ vi.mocked(readOwnerPermissions).mockResolvedValue(purchasing());await executeWorkflowRun({ payload, step, logger });diff --git a/packages/jobs/src/workflows/engine/manual.test.ts b/packages/jobs/src/workflows/engine/manual.test.tsindex 08f39004b2..6a064460ef 100644--- a/packages/jobs/src/workflows/engine/manual.test.ts+++ b/packages/jobs/src/workflows/engine/manual.test.ts@@ -80,15 +80,6 @@ vi.mock("./owner", () => ({hasPermission: vi.fn(() => true)}));vi.mock("../actions", () => ({ createWorkflowServices: vi.fn() }));-// The real module pulls in the email templates and @carbon/env; the engine only wants a URL.-vi.mock("../../inngest/functions/notifications/content", () => ({- buildNotificationLink: (- event: string,- documentId: string,- companyId: string- ) =>- `https://erp.test/api/link?event=${event}&documentId=${documentId}&companyId=${companyId}`-}));const { executeManualWorkflowRun } = await import("./manual");const { createWorkflowServices } = await import("../actions");diff --git a/packages/jobs/src/workflows/scheduler.test.ts b/packages/jobs/src/workflows/scheduler.test.tsindex d070a7c690..979874c693 100644--- a/packages/jobs/src/workflows/scheduler.test.ts+++ b/packages/jobs/src/workflows/scheduler.test.ts@@ -3,22 +3,14 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { describe, expect, it } from "vitest";-import type { PlannedRun } from "./matcher";import {type DueWorkflow,- MAX_DUE_PER_WAKE,OVERFLOW_WAKE_MS,- PREVIOUS_RUN_ACTIVE,planClaims,planWakeAt,- SCHEDULE_EVENT_ID,- STALE_AFTER_MS,- TOO_LATE,WAKE_CEILING_MS} from "./scheduler";-// ---- planWakeAt -----describe("planWakeAt", () => {const now = new Date("2026-08-01T10:00:00Z");@@ -51,74 +43,12 @@ describe("planWakeAt", () => {it("floors earliestFuture to at least now + 1s", () => {const past = new Date(now.getTime() - 1000);- const result = planWakeAt({ now, earliestFuture: past, overflow: false });- expect(result).toBeGreaterThanOrEqual(now.getTime() + 1000);- });-});--// ---- PlannedRun shape ------describe("PlannedRun", () => {- it("has the expected flat shape fields", () => {- const plan: PlannedRun = {- workflowId: "wf_1",- workflowVersionId: "wfv_1",- eventId: SCHEDULE_EVENT_ID,- ownerId: "usr_1",- status: "Queued",- statusReason: null,- rootRunId: null,- causedByRunId: null,- depth: 0,- path: []- };- expect(plan.eventId).toBe("schedule");- expect(plan.depth).toBe(0);- expect(plan.path).toEqual([]);- });-- it("accepts Skipped status (not available in matcher's MatchPlan)", () => {- const plan: PlannedRun = {- workflowId: "wf_1",- workflowVersionId: "wfv_1",- eventId: SCHEDULE_EVENT_ID,- ownerId: "usr_1",- status: "Skipped",- statusReason: PREVIOUS_RUN_ACTIVE,- rootRunId: null,- causedByRunId: null,- depth: 0,- path: []- };- expect(plan.status).toBe("Skipped");- expect(plan.statusReason).toBe(PREVIOUS_RUN_ACTIVE);- });-});--// ---- constant values ------describe("scheduler constants", () => {- it("STALE_AFTER_MS is one hour", () => {- expect(STALE_AFTER_MS).toBe(60 * 60 * 1000);- });-- it("MAX_DUE_PER_WAKE is 200", () => {- expect(MAX_DUE_PER_WAKE).toBe(200);- });-- it("TOO_LATE message is defined", () => {- expect(typeof TOO_LATE).toBe("string");- expect(TOO_LATE.length).toBeGreaterThan(0);- });-- it("PREVIOUS_RUN_ACTIVE message is defined", () => {- expect(typeof PREVIOUS_RUN_ACTIVE).toBe("string");- expect(PREVIOUS_RUN_ACTIVE.length).toBeGreaterThan(0);+ expect(planWakeAt({ now, earliestFuture: past, overflow: false })).toBe(+ now.getTime() + 1000+ );});});-// ---- planClaims -----describe("planClaims", () => {const now = new Date("2026-08-01T10:00:00Z");@@ -160,11 +90,11 @@ describe("planClaims", () => {now);expect(unscheduled).toEqual([]);+ // Due 08-01 09:00 and now 10:00: tomorrow's slot, not today's missed one,+ // so a long outage cannot queue a cascade of catch-ups. The minutes are+ // the workflow's spread offset.expect(claims).toHaveLength(1);- // Computed from `now`, so a long outage cannot queue a cascade of catch-ups.- expect(new Date(claims[0]!.recomputed).getTime()).toBeGreaterThan(- now.getTime()- );+ expect(claims[0]?.recomputed).toMatch(/^2026-08-02T09:/);});it("clears a workflow whose promoted version is no longer scheduled", () => {diff --git a/packages/jobs/tsconfig.json b/packages/jobs/tsconfig.jsonindex beead8d694..57ddf10f4b 100644--- a/packages/jobs/tsconfig.json+++ b/packages/jobs/tsconfig.json@@ -1,7 +1,5 @@{"compilerOptions": {- "outDir": "./dist",- "sourceMap": false,"allowImportingTsExtensions": true,"noEmit": true,"strictNullChecks": truediff --git a/packages/kv/package.json b/packages/kv/package.jsonindex 71e39e5a80..27593a65aa 100644--- a/packages/kv/package.json+++ b/packages/kv/package.json@@ -3,17 +3,17 @@"dependencies": {"@carbon/env": "workspace:*","@carbon/logger": "workspace:*",- "cookie": "catalog:",- "dompurify": "catalog:",- "ioredis": "5.10.1",- "nanoid": "catalog:"+ "ioredis": "5.10.1"},"devDependencies": {"@carbon/config": "workspace:*","@types/ioredis-mock": "8.2.8","@types/node": "20.19.39",+ "cookie": "catalog:",+ "dompurify": "catalog:","dotenv": "16.3.1","ioredis-mock": "8.13.1",+ "nanoid": "catalog:","rimraf": "catalog:","sst": "catalog:","tsup": "catalog:",@@ -32,7 +32,7 @@"test": "vitest run","test:watch": "vitest","test:coverage": "vitest run --coverage",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"sideEffects": false,"version": "0.0.0"diff --git a/packages/kv/src/ratelimit/cache.test.ts b/packages/kv/src/ratelimit/cache.test.tsindex 9438370553..88f25e9636 100644--- a/packages/kv/src/ratelimit/cache.test.ts+++ b/packages/kv/src/ratelimit/cache.test.ts@@ -5,146 +5,38 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { Cache } from "./cache";-describe("Cache", () => {+describe("Cache.isBlocked", () => {beforeEach(() => {vi.useFakeTimers();+ vi.setSystemTime(1_000_000);});afterEach(() => {vi.useRealTimers();});- describe("constructor", () => {- it("should create cache with empty map by default", () => {- const cache = new Cache();- expect(cache.get("key")).toBeUndefined();- });-- it("should create cache with provided map", () => {- const existingMap = new Map<string, number>();- existingMap.set("existing", 123);- const cache = new Cache(existingMap);- expect(cache.get("existing")).toBe(123);- });- });-- describe("isBlocked()", () => {- it("should return not blocked for unknown key", () => {- const cache = new Cache();- const result = cache.isBlocked("unknown");- expect(result.blocked).toBe(false);- expect(result.reset).toBe(0);- });-- it("should return blocked when reset time is in the future", () => {- const cache = new Cache();- const futureTime = Date.now() + 10000; // 10 seconds in future- cache.blockUntil("user:123", futureTime);-- const result = cache.isBlocked("user:123");- expect(result.blocked).toBe(true);- expect(result.reset).toBe(futureTime);- });-- it("should return not blocked when reset time has passed", () => {- const cache = new Cache();- const pastTime = Date.now() + 5000;- cache.blockUntil("user:123", pastTime);-- // Advance time past the reset- vi.advanceTimersByTime(6000);-- const result = cache.isBlocked("user:123");- expect(result.blocked).toBe(false);- expect(result.reset).toBe(0);- });-- it("should clean up expired entries on check", () => {- const cache = new Cache();- const resetTime = Date.now() + 5000;- cache.blockUntil("user:123", resetTime);-- // Advance time past the reset- vi.advanceTimersByTime(6000);-- // First check should clean up- cache.isBlocked("user:123");-- // Key should now be gone- expect(cache.get("user:123")).toBeUndefined();- });- });-- describe("blockUntil()", () => {- it("should block a key until specified time", () => {- const cache = new Cache();- const resetTime = Date.now() + 10000;- cache.blockUntil("user:123", resetTime);-- expect(cache.get("user:123")).toBe(resetTime);- });-- it("should overwrite existing block time", () => {- const cache = new Cache();- const firstReset = Date.now() + 5000;- const secondReset = Date.now() + 10000;-- cache.blockUntil("user:123", firstReset);- cache.blockUntil("user:123", secondReset);-- expect(cache.get("user:123")).toBe(secondReset);+ it("does not block a key that was never blocked", () => {+ expect(new Cache().isBlocked("user:1")).toEqual({+ blocked: false,+ reset: 0});});- describe("set() and get()", () => {- it("should set and get values", () => {- const cache = new Cache();- cache.set("key1", 100);- cache.set("key2", 200);-- expect(cache.get("key1")).toBe(100);- expect(cache.get("key2")).toBe(200);- });-- it("should return undefined for non-existent keys", () => {- const cache = new Cache();- expect(cache.get("nonexistent")).toBeUndefined();- });-- it("should overwrite existing values", () => {- const cache = new Cache();- cache.set("key", 100);- cache.set("key", 200);- expect(cache.get("key")).toBe(200);+ it("blocks a key until its reset time", () => {+ const cache = new Cache();+ cache.blockUntil("user:1", 1_010_000);+ vi.advanceTimersByTime(9_999);+ expect(cache.isBlocked("user:1")).toEqual({+ blocked: true,+ reset: 1_010_000});});- describe("incr()", () => {- it("should increment from 0 for new keys", () => {- const cache = new Cache();- const result = cache.incr("counter");- expect(result).toBe(1);- expect(cache.get("counter")).toBe(1);- });-- it("should increment existing values", () => {- const cache = new Cache();- cache.set("counter", 5);-- expect(cache.incr("counter")).toBe(6);- expect(cache.incr("counter")).toBe(7);- expect(cache.incr("counter")).toBe(8);- });-- it("should handle multiple counters independently", () => {- const cache = new Cache();-- cache.incr("counter1");- cache.incr("counter1");- cache.incr("counter2");-- expect(cache.get("counter1")).toBe(2);- expect(cache.get("counter2")).toBe(1);- });+ it("unblocks and forgets a key once its reset time is reached", () => {+ const cache = new Cache();+ cache.blockUntil("user:1", 1_010_000);+ vi.advanceTimersByTime(10_000);+ expect(cache.isBlocked("user:1")).toEqual({ blocked: false, reset: 0 });+ expect(cache.get("user:1")).toBeUndefined();});});diff --git a/packages/kv/src/ratelimit/duration.test.ts b/packages/kv/src/ratelimit/duration.test.tsindex f12bec4224..3d84d0be0f 100644--- a/packages/kv/src/ratelimit/duration.test.ts+++ b/packages/kv/src/ratelimit/duration.test.ts@@ -4,73 +4,22 @@import { describe, expect, it } from "vitest";import { ms } from "./duration";+import type { Duration } from "./types";++describe("ms", () => {+ it.each<[Duration, number]>([+ ["100ms", 100],+ ["1 ms", 1],+ ["10s", 10_000],+ ["0 s", 0],+ ["5m", 300_000],+ ["24 h", 86_400_000],+ ["7d", 604_800_000]+ ])("converts %s to %i milliseconds", (input, expected) => {+ expect(ms(input)).toBe(expected);+ });-describe("duration parser", () => {- describe("ms()", () => {- it("should parse milliseconds", () => {- expect(ms("100ms")).toBe(100);- expect(ms("1ms")).toBe(1);- expect(ms("1000ms")).toBe(1000);- });-- it("should parse milliseconds with space", () => {- expect(ms("100 ms")).toBe(100);- expect(ms("1 ms")).toBe(1);- });-- it("should parse seconds", () => {- expect(ms("1s")).toBe(1000);- expect(ms("10s")).toBe(10000);- expect(ms("60s")).toBe(60000);- });-- it("should parse seconds with space", () => {- expect(ms("1 s")).toBe(1000);- expect(ms("10 s")).toBe(10000);- });-- it("should parse minutes", () => {- expect(ms("1m")).toBe(60000);- expect(ms("5m")).toBe(300000);- expect(ms("60m")).toBe(3600000);- });-- it("should parse minutes with space", () => {- expect(ms("1 m")).toBe(60000);- expect(ms("5 m")).toBe(300000);- });-- it("should parse hours", () => {- expect(ms("1h")).toBe(3600000);- expect(ms("24h")).toBe(86400000);- });-- it("should parse hours with space", () => {- expect(ms("1 h")).toBe(3600000);- expect(ms("24 h")).toBe(86400000);- });-- it("should parse days", () => {- expect(ms("1d")).toBe(86400000);- expect(ms("7d")).toBe(604800000);- });-- it("should parse days with space", () => {- expect(ms("1 d")).toBe(86400000);- expect(ms("7 d")).toBe(604800000);- });-- it("should throw on invalid format", () => {- expect(() => ms("invalid" as any)).toThrow("Unable to parse window size");- expect(() => ms("10" as any)).toThrow("Unable to parse window size");- expect(() => ms("10x" as any)).toThrow("Unable to parse window size");- expect(() => ms("" as any)).toThrow("Unable to parse window size");- });-- it("should handle edge cases", () => {- expect(ms("0s")).toBe(0);- expect(ms("0 s")).toBe(0);- expect(ms("0m")).toBe(0);- });+ it.each(["invalid", "10", "10x", "", "1 s"])("refuses %j", (input) => {+ expect(() => ms(input as Duration)).toThrow("Unable to parse window size");});});diff --git a/packages/kv/src/ratelimit/ratelimit.test.ts b/packages/kv/src/ratelimit/ratelimit.test.tsindex 659f5c0745..e4812a8f33 100644--- a/packages/kv/src/ratelimit/ratelimit.test.ts+++ b/packages/kv/src/ratelimit/ratelimit.test.ts@@ -6,607 +6,249 @@ import type { Redis } from "ioredis";import RedisMock from "ioredis-mock";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { Ratelimit } from "./ratelimit";+import type { RatelimitConfig } from "./types";-// Create a mock Redis client-const createMockRedis = () => {- const storage = new Map<string, any>();- const hashStorage = new Map<string, Map<string, any>>();+// These run the REAL Lua scripts (ioredis-mock executes them), so they pin what+// Redis does with the counters, not what a stubbed `eval` returns. The token+// bucket is not here: ioredis-mock returns a missing HMGET field as userdata,+// not Redis's `false`, so its script cannot run on the mock.++const MIDNIGHT = 1_704_067_200_000; // 2024-01-01T00:00:00Z+const minutes = (n: number) => MIDNIGHT + n * 60_000;++let redis: Redis;++function base(overrides: Partial<RatelimitConfig> = {}) {+ return new Ratelimit({+ redis,+ limiter: Ratelimit.slidingWindow(2, "1 h"),+ timeout: 0,+ ...overrides+ });+}++async function outcomes(ratelimit: Ratelimit, calls: number, id = "user") {+ const results = [];+ for (let i = 0; i < calls; i++) {+ const { success, remaining } = await ratelimit.limit(id);+ results.push({ success, remaining });+ }+ return results;+}++beforeEach(async () => {+ // Only the clock is faked, mid-window, so no test straddles a boundary.+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(minutes(30));+ // ioredis-mock instances share one keyspace; start every test empty.+ redis = new RedisMock() as unknown as Redis;+ await redis.flushall();+});- return {- eval: vi.fn(),- del: vi.fn().mockImplementation((...keys: string[]) => {- keys.forEach((key) => {- storage.delete(key);- hashStorage.delete(key);- });- return Promise.resolve(keys.length);- }),- get: vi.fn().mockImplementation((key: string) => {- return Promise.resolve(storage.get(key) ?? null);- }),- set: vi.fn().mockImplementation((key: string, value: any) => {- storage.set(key, value);- return Promise.resolve("OK");- }),- // Helper to access internal storage for testing- _storage: storage,- _hashStorage: hashStorage- } as unknown as Redis & {- _storage: Map<string, any>;- _hashStorage: Map<string, Map<string, any>>;- };-};+afterEach(() => {+ vi.useRealTimers();+});-describe("Ratelimit", () => {- let mockRedis: ReturnType<typeof createMockRedis>;+describe("fixed window", () => {+ const fixed = () => base({ limiter: Ratelimit.fixedWindow(3, "1 m") });- beforeEach(() => {- mockRedis = createMockRedis();- vi.useFakeTimers();- vi.setSystemTime(new Date("2024-01-01T00:00:00.000Z"));+ it("allows the budget, then blocks", async () => {+ expect(await outcomes(fixed(), 4)).toEqual([+ { success: true, remaining: 2 },+ { success: true, remaining: 1 },+ { success: true, remaining: 0 },+ { success: false, remaining: 0 }+ ]);});- afterEach(() => {- vi.useRealTimers();- vi.clearAllMocks();+ it("allows again once the window has expired", async () => {+ const ratelimit = fixed();+ await outcomes(ratelimit, 3);+ vi.setSystemTime(minutes(31) + 1);+ expect((await ratelimit.limit("user")).success).toBe(true);});- describe("constructor", () => {- it("should create a ratelimiter with default options", () => {- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.slidingWindow(10, "1 h")- });-- expect(ratelimit).toBeInstanceOf(Ratelimit);- });-- it("should create a ratelimiter with custom prefix", () => {- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.slidingWindow(10, "1 h"),- prefix: "custom-prefix"- });-- expect(ratelimit).toBeInstanceOf(Ratelimit);- });-- it("should create a ratelimiter with ephemeral cache enabled", () => {- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.slidingWindow(10, "1 h"),- ephemeralCache: true- });-- expect(ratelimit).toBeInstanceOf(Ratelimit);- });-- it("should create a ratelimiter with custom cache map", () => {- const customCache = new Map<string, number>();- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.slidingWindow(10, "1 h"),- ephemeralCache: customCache- });-- expect(ratelimit).toBeInstanceOf(Ratelimit);+ it("takes a per-call rate over the configured one", async () => {+ const ratelimit = fixed();+ expect(await ratelimit.limit("user", { rate: 1 })).toMatchObject({+ success: true,+ limit: 1,+ remaining: 0});+ expect((await ratelimit.limit("user", { rate: 1 })).success).toBe(false);});+});- describe("fixedWindow algorithm", () => {- it("should allow requests within limit", async () => {- // Mock Redis eval to return [1, 10] (1 request used, limit of 10)- mockRedis.eval = vi.fn().mockResolvedValue([1, 10]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.fixedWindow(10, "1 m")- });-- const result = await ratelimit.limit("user:123");-- expect(result.success).toBe(true);- expect(result.limit).toBe(10);- expect(result.remaining).toBe(9);- expect(result.reset).toBeGreaterThan(Date.now());- });-- it("should block requests when limit exceeded", async () => {- // Mock Redis eval to return [11, 10] (11 requests used, limit of 10)- mockRedis.eval = vi.fn().mockResolvedValue([11, 10]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.fixedWindow(10, "1 m")- });-- const result = await ratelimit.limit("user:123");-- expect(result.success).toBe(false);- expect(result.limit).toBe(10);- expect(result.remaining).toBe(0);- });-- it("should call Redis eval with correct parameters", async () => {- mockRedis.eval = vi.fn().mockResolvedValue([1, 10]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.fixedWindow(10, "1 m"),- prefix: "test"- });-- await ratelimit.limit("user:123");-- expect(mockRedis.eval).toHaveBeenCalledWith(- expect.any(String), // Lua script- 1, // Number of keys- "test:user:123", // Key- 10, // Limit- 60000, // Window in ms- 1 // Increment by- );- });+describe("sliding window", () => {+ it("allows the budget, then blocks until the window ends", async () => {+ const ratelimit = base();+ expect(await outcomes(ratelimit, 3)).toEqual([+ { success: true, remaining: 1 },+ { success: true, remaining: 0 },+ { success: false, remaining: 0 }+ ]);+ expect((await ratelimit.limit("user")).reset).toBe(minutes(60));+ });++ it("counts the previous window by how much of it still overlaps", async () => {+ // Two calls at 23:45 the day before; at 00:30 half the previous hour still+ // overlaps, so floor(0.5 × 2) = 1 of them counts and one call is left.+ const ratelimit = base();+ vi.setSystemTime(minutes(-15));+ await outcomes(ratelimit, 2);+ vi.setSystemTime(minutes(30));+ expect(await outcomes(ratelimit, 2)).toEqual([+ { success: true, remaining: 0 },+ { success: false, remaining: 0 }+ ]);});- describe("slidingWindow algorithm", () => {- it("should allow requests within limit", async () => {- // Mock Redis eval to return [9, 10] (9 remaining, limit of 10)- mockRedis.eval = vi.fn().mockResolvedValue([9, 10]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.slidingWindow(10, "1 h")- });-- const result = await ratelimit.limit("user:123");-- expect(result.success).toBe(true);- expect(result.limit).toBe(10);- expect(result.remaining).toBe(9);- });-- it("should block requests when limit exceeded", async () => {- // Mock Redis eval to return [-1, 10] (blocked, limit of 10)- mockRedis.eval = vi.fn().mockResolvedValue([-1, 10]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.slidingWindow(10, "1 h")- });-- const result = await ratelimit.limit("user:123");-- expect(result.success).toBe(false);- expect(result.limit).toBe(10);- expect(result.remaining).toBe(0);- });-- it("should call Redis eval with two keys (current and previous window)", async () => {- mockRedis.eval = vi.fn().mockResolvedValue([9, 10]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.slidingWindow(10, "1 h"),- prefix: "test"- });-- await ratelimit.limit("user:123");-- expect(mockRedis.eval).toHaveBeenCalledWith(- expect.any(String), // Lua script- 2, // Number of keys (current + previous window)- expect.stringMatching(/^test:user:123:\d+$/), // Current window key- expect.stringMatching(/^test:user:123:\d+$/), // Previous window key- 10, // Limit- expect.any(Number), // Current timestamp- 3600000, // Window in ms (1 hour)- 1 // Increment by- );- });+ it("a concurrent burst consumes at most the budget", async () => {+ const ratelimit = base();+ const results = await Promise.all(+ Array.from({ length: 10 }, () => ratelimit.limit("user"))+ );+ expect(results.filter((r) => r.success)).toHaveLength(2);});+});- describe("tokenBucket algorithm", () => {- it("should allow requests when tokens available", async () => {- // Mock Redis eval to return [9, next_refill_time, 10]- const nextRefill = Date.now() + 1000;- mockRedis.eval = vi.fn().mockResolvedValue([9, nextRefill, 10]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.tokenBucket(1, "1 s", 10)- });-- const result = await ratelimit.limit("user:123");-- expect(result.success).toBe(true);- expect(result.limit).toBe(10);- expect(result.remaining).toBe(9);- expect(result.reset).toBe(nextRefill);- });-- it("should block requests when bucket is empty", async () => {- const nextRefill = Date.now() + 1000;- mockRedis.eval = vi.fn().mockResolvedValue([-1, nextRefill, 10]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.tokenBucket(1, "1 s", 10)- });-- const result = await ratelimit.limit("user:123");-- expect(result.success).toBe(false);- expect(result.limit).toBe(10);- expect(result.remaining).toBe(0);- expect(result.reset).toBe(nextRefill);- });-- it("should use refillRate as maxTokens when not specified", async () => {- mockRedis.eval = vi.fn().mockResolvedValue([4, Date.now() + 1000, 5]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.tokenBucket(5, "10 s"), // No maxTokens specified- prefix: "test"- });-- await ratelimit.limit("user:123");-- // Check that maxTokens (5) was passed to the script- expect(mockRedis.eval).toHaveBeenCalledWith(- expect.any(String),- 1,- "test:user:123",- 5, // maxTokens defaults to refillRate- 10000, // 10 seconds in ms- 5, // refillRate- expect.any(Number),- 1- );- });+describe.each([+ ["fixed window", Ratelimit.fixedWindow(2, "1 m")],+ ["sliding window", Ratelimit.slidingWindow(2, "1 h")]+])("%s", (_name, limiter) => {+ it("reports what is left without using it", async () => {+ const ratelimit = base({ limiter });+ await ratelimit.limit("user");+ expect((await ratelimit.getRemaining("user")).remaining).toBe(1);+ expect((await ratelimit.getRemaining("user")).remaining).toBe(1);+ });++ it("starts over after resetUsedTokens", async () => {+ const ratelimit = base({ limiter });+ await outcomes(ratelimit, 2);+ await ratelimit.resetUsedTokens("user");+ expect((await ratelimit.limit("user")).success).toBe(true);+ });++ it("keeps each identifier's budget, and each prefix's, apart", async () => {+ const ratelimit = base({ limiter });+ await outcomes(ratelimit, 2, "a");+ expect((await ratelimit.limit("b")).success).toBe(true);+ expect((await base({ limiter, prefix: "other" }).limit("a")).success).toBe(+ true+ );+ expect((await base({ limiter }).limit("a")).success).toBe(false);});+});- describe("ephemeral cache", () => {- it("should use cache to block subsequent requests", async () => {- // First call: blocked (returns [-1, 10] meaning blocked with limit 10)- mockRedis.eval = vi.fn().mockResolvedValue([-1, 10]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.slidingWindow(10, "1 h"),- ephemeralCache: true- });-- // First request - blocked by Redis- const firstResult = await ratelimit.limit("user:123");- expect(firstResult.success).toBe(false);-- // Clear the mock call history but keep returning blocked result- vi.clearAllMocks();-- // Second request - should be blocked by cache, not Redis- // The cache blocks based on the key prefix + identifier- const result = await ratelimit.limit("user:123");-- expect(result.success).toBe(false);- // Cache uses the full key including prefix- expect(mockRedis.eval).not.toHaveBeenCalled(); // Cache should prevent Redis call- });-- it("should allow requests after cache expires", async () => {- mockRedis.eval = vi.fn().mockResolvedValue([-1, 10]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.slidingWindow(10, "1 h"),- ephemeralCache: true- });-- // First request - blocked- await ratelimit.limit("user:123");-- // Advance time past the window- vi.advanceTimersByTime(3600001);-- // Mock successful response for next call- mockRedis.eval = vi.fn().mockResolvedValue([9, 10]);-- // Second request - should go to Redis again- const result = await ratelimit.limit("user:123");-- expect(mockRedis.eval).toHaveBeenCalled();- expect(result.success).toBe(true);- });+describe("refund", () => {+ it("returns a consumed token so the next call passes", async () => {+ const ratelimit = base();+ await outcomes(ratelimit, 3);+ await ratelimit.refund("user");+ expect(await outcomes(ratelimit, 2)).toEqual([+ { success: true, remaining: 0 },+ { success: false, remaining: 0 }+ ]);});- describe("timeout handling", () => {- it("should return success on timeout", async () => {- // Create a promise that never resolves- mockRedis.eval = vi.fn().mockImplementation(- () =>- new Promise(() => {- /* intentionally never resolves */- })- );-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.slidingWindow(10, "1 h"),- timeout: 1000- });-- const resultPromise = ratelimit.limit("user:123");-- // Advance time past timeout- vi.advanceTimersByTime(1001);-- const result = await resultPromise;-- expect(result.success).toBe(true);- expect(result.limit).toBe(0);- expect(result.remaining).toBe(0);- expect(result.reset).toBe(0);- });+ it("never banks credit below zero", async () => {+ const ratelimit = base();+ await ratelimit.refund("user");+ await ratelimit.refund("user");+ expect((await outcomes(ratelimit, 3)).map((r) => r.success)).toEqual([+ true,+ true,+ false+ ]);});- describe("getRemaining()", () => {- it("should return remaining tokens for fixedWindow", async () => {- mockRedis.eval = vi.fn().mockResolvedValue([7, 10]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.fixedWindow(10, "1 m")- });-- const result = await ratelimit.getRemaining("user:123");-- expect(result.remaining).toBe(7);- expect(result.limit).toBe(10);- expect(result.reset).toBeGreaterThan(Date.now());- });-- it("should return remaining tokens for slidingWindow", async () => {- mockRedis.eval = vi.fn().mockResolvedValue([5, 10]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.slidingWindow(10, "1 h")- });-- const result = await ratelimit.getRemaining("user:123");-- expect(result.remaining).toBe(5);- expect(result.limit).toBe(10);- });-- it("should return remaining tokens for tokenBucket", async () => {- mockRedis.eval = vi.fn().mockResolvedValue([8, Date.now() + 1000, 10]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.tokenBucket(1, "1 s", 10)- });-- const result = await ratelimit.getRemaining("user:123");-- expect(result.remaining).toBe(8);- expect(result.limit).toBe(10);- });+ it("only returns the identifier's own token", async () => {+ const ratelimit = base();+ await outcomes(ratelimit, 2, "a");+ await ratelimit.limit("b");+ await ratelimit.refund("b");+ expect((await ratelimit.limit("a")).success).toBe(false);});+});- describe("resetUsedTokens()", () => {- it("should delete the key for fixedWindow", async () => {- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.fixedWindow(10, "1 m"),- prefix: "test"- });-- await ratelimit.resetUsedTokens("user:123");-- expect(mockRedis.del).toHaveBeenCalledWith("test:user:123");- });-- it("should delete both window keys for slidingWindow", async () => {- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.slidingWindow(10, "1 h"),- prefix: "test"- });-- await ratelimit.resetUsedTokens("user:123");-- expect(mockRedis.del).toHaveBeenCalledWith(- expect.stringMatching(/^test:user:123:\d+$/),- expect.stringMatching(/^test:user:123:\d+$/)- );+describe("ephemeral cache", () => {+ it("keeps a blocked identifier blocked in memory until its reset", async () => {+ const ratelimit = base({ ephemeralCache: true });+ await outcomes(ratelimit, 3);+ // Clearing Redis proves the next answer comes from memory.+ await ratelimit.resetUsedTokens("user");+ expect(await ratelimit.limit("user")).toMatchObject({+ success: false,+ reset: minutes(60)});- it("should delete the key for tokenBucket", async () => {- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.tokenBucket(1, "1 s", 10),- prefix: "test"- });-- await ratelimit.resetUsedTokens("user:123");-- expect(mockRedis.del).toHaveBeenCalledWith("test:user:123");- });+ vi.setSystemTime(minutes(60));+ expect((await ratelimit.limit("user")).success).toBe(true);});+});- describe("blockUntilReady()", () => {- it("should return immediately if not rate limited", async () => {- mockRedis.eval = vi.fn().mockResolvedValue([9, 10]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.slidingWindow(10, "1 h")- });-- const result = await ratelimit.blockUntilReady("user:123", 5000);-- expect(result.success).toBe(true);- });-- it("should throw error for non-positive timeout", async () => {- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.slidingWindow(10, "1 h")- });-- await expect(ratelimit.blockUntilReady("user:123", 0)).rejects.toThrow(- "timeout must be positive"- );-- await expect(ratelimit.blockUntilReady("user:123", -1)).rejects.toThrow(- "timeout must be positive"- );- });-- it("should wait and retry when rate limited", async () => {- // Use real timers for this test since fake timers + async is tricky- vi.useRealTimers();-- // First call: blocked, second call: allowed- mockRedis.eval = vi- .fn()- .mockResolvedValueOnce([-1, 10]) // First: blocked- .mockResolvedValueOnce([9, 10]); // Second: allowed-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.slidingWindow(10, "100 ms") // Short window for fast test- });-- const result = await ratelimit.blockUntilReady("user:123", 500);-- expect(result.success).toBe(true);- expect(mockRedis.eval).toHaveBeenCalledTimes(2);+describe("when Redis fails", () => {+ const failOpen = { success: true, limit: 0, remaining: 0, reset: 0 };- // Restore fake timers for other tests- vi.useFakeTimers();+ it("fails open on an error", async () => {+ const down = {+ eval: async () => {+ throw new Error("ECONNREFUSED");+ }+ } as unknown as Redis;+ expect(await base({ redis: down }).limit("user")).toMatchObject(failOpen);+ expect(await base({ redis: down }).getRemaining("user")).toEqual({+ remaining: 0,+ reset: 0,+ limit: 0});});- describe("analytics option (compatibility)", () => {- it("should accept analytics option without error", () => {- // analytics is a no-op for compatibility- expect(() => {- new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.slidingWindow(10, "1 h"),- analytics: true- });- }).not.toThrow();- });- });-- describe("prefix handling", () => {- it("should use default prefix when not specified", async () => {- mockRedis.eval = vi.fn().mockResolvedValue([9, 10]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.fixedWindow(10, "1 m")- });-- await ratelimit.limit("user:123");-- expect(mockRedis.eval).toHaveBeenCalledWith(- expect.any(String),- 1,- "@carbon/ratelimit:user:123", // Default prefix- expect.anything(),- expect.anything(),- expect.anything()- );- });-- it("should use custom prefix when specified", async () => {- mockRedis.eval = vi.fn().mockResolvedValue([9, 10]);-- const ratelimit = new Ratelimit({- redis: mockRedis,- limiter: Ratelimit.fixedWindow(10, "1 m"),- prefix: "myapp:ratelimit"- });-- await ratelimit.limit("user:123");-- expect(mockRedis.eval).toHaveBeenCalledWith(- expect.any(String),- 1,- "myapp:ratelimit:user:123",- expect.anything(),- expect.anything(),- expect.anything()- );- });+ it("fails open when Redis does not answer within the timeout", async () => {+ vi.useFakeTimers();+ const silent = {+ eval: () => new Promise(() => undefined)+ } as unknown as Redis;+ const pending = base({ redis: silent, timeout: 1000 }).limit("user");+ await vi.advanceTimersByTimeAsync(1001);+ expect(await pending).toMatchObject(failOpen);});});-// These run the REAL Lua scripts (ioredis-mock executes them), so they pin what-// Redis does with the counters rather than what a stubbed `eval` returns.-describe("refund() against the real window scripts", () => {- beforeEach(async () => {- // Only the clock is faked — mid-window, so no test straddles a boundary.- vi.useFakeTimers({ toFake: ["Date"] });- vi.setSystemTime(new Date("2024-01-01T00:30:00.000Z"));- // ioredis-mock instances share one keyspace; start every test empty.- await new RedisMock().flushall();- });-- afterEach(() => {- vi.useRealTimers();+describe("blockUntilReady", () => {+ beforeEach(() => {+ vi.useFakeTimers({ toFake: ["Date", "setTimeout"] });+ vi.setSystemTime(minutes(30) + 500);});- const create = () =>- new Ratelimit({- redis: new RedisMock() as unknown as Redis,- limiter: Ratelimit.slidingWindow(2, "1 h"),- timeout: 0+ it("waits until a call is allowed", async () => {+ // A 1 s sliding window: at :01 the call at :00.5 still counts in full, so+ // the first free moment is :02.+ const ratelimit = base({ limiter: Ratelimit.slidingWindow(1, "1 s") });+ await ratelimit.limit("user");+ let result: { success: boolean } | undefined;+ const pending = ratelimit.blockUntilReady("user", 5000).then((r) => {+ result = r;});-- it("a concurrent burst consumes at most the budget", async () => {- const ratelimit = create();- const results = await Promise.all(- Array.from({ length: 10 }, () => ratelimit.limit("terminal"))- );- expect(results.filter((r) => r.success)).toHaveLength(2);- });-- it("returns a consumed token so the next call passes", async () => {- const ratelimit = create();- expect((await ratelimit.limit("terminal")).success).toBe(true);- expect((await ratelimit.limit("terminal")).success).toBe(true);- expect((await ratelimit.limit("terminal")).success).toBe(false);-- await ratelimit.refund("terminal");-- expect((await ratelimit.limit("terminal")).success).toBe(true);- expect((await ratelimit.limit("terminal")).success).toBe(false);+ await vi.advanceTimersByTimeAsync(1000);+ expect(result).toBeUndefined();+ await vi.advanceTimersByTimeAsync(500);+ await pending;+ expect(result?.success).toBe(true);});- it("never banks credit below zero", async () => {- const ratelimit = create();- await ratelimit.refund("terminal");- await ratelimit.refund("terminal");-- expect((await ratelimit.limit("terminal")).success).toBe(true);- expect((await ratelimit.limit("terminal")).success).toBe(true);- expect((await ratelimit.limit("terminal")).success).toBe(false);+ it("gives up blocked at the deadline", async () => {+ const ratelimit = base({ limiter: Ratelimit.slidingWindow(1, "1 h") });+ await ratelimit.limit("user");+ const pending = ratelimit.blockUntilReady("user", 300);+ await vi.advanceTimersByTimeAsync(300);+ expect((await pending).success).toBe(false);});- it("only returns the identifier's own token", async () => {- const ratelimit = create();- await ratelimit.limit("a");- await ratelimit.limit("a");- await ratelimit.limit("b");-- await ratelimit.refund("b");-- expect((await ratelimit.limit("a")).success).toBe(false);+ it.each([0, -1])("refuses a timeout of %s", async (timeout) => {+ await expect(base().blockUntilReady("user", timeout)).rejects.toThrow(+ "timeout must be positive"+ );});});diff --git a/packages/lib/AGENTS.md b/packages/lib/AGENTS.mdindex 5ca4870af9..7ee11b5642 100644--- a/packages/lib/AGENTS.md+++ b/packages/lib/AGENTS.md@@ -24,7 +24,7 @@ Shared server utilities — event system, Inngest client, trigger dispatch, SMTP## Validation Commands```bash-pnpm --filter @carbon/lib typecheck # tsgo --noEmit+pnpm --filter @carbon/lib typecheck # tsc --noEmitpnpm --filter @carbon/lib test # vitest run```diff --git a/packages/lib/package.json b/packages/lib/package.jsonindex f9cf09c010..1aaa490992 100644--- a/packages/lib/package.json+++ b/packages/lib/package.json@@ -1,32 +1,32 @@{"name": "@carbon/lib","dependencies": {- "@carbon/database": "workspace:*","@carbon/documents": "workspace:*","@carbon/env": "workspace:*","@carbon/files": "workspace:*","@carbon/kv": "workspace:*","@carbon/logger": "workspace:*",- "@carbon/notifications": "workspace:*","@carbon/utils": "workspace:*",- "@carbon/workflows-core": "workspace:*","@react-pdf/renderer": "catalog:","@slack/web-api": "catalog:",- "@supabase/supabase-js": "catalog:","inngest": "3.54.2","nanoid": "catalog:","nodemailer": "10.0.6","resend": "3.5.0",- "sst": "catalog:",- "supabase": "catalog:","zod": "catalog:"},"devDependencies": {"@carbon/config": "workspace:*",+ "@carbon/database": "workspace:*",+ "@carbon/notifications": "workspace:*",+ "@carbon/workflows-core": "workspace:*",+ "@supabase/supabase-js": "catalog:","@types/node": "20.19.39","@types/nodemailer": "6.4.23","dotenv": "16.3.1","rimraf": "catalog:",+ "sst": "catalog:",+ "supabase": "catalog:","tsup": "catalog:","tsx": "catalog:","typescript": "catalog:",@@ -55,7 +55,7 @@"clean": "rimraf .turbo node_modules dist","dev": "tsup --watch","lint": "biome lint --write ",- "typecheck": "tsgo --noEmit",+ "typecheck": "tsc --noEmit","test": "vitest run"},"sideEffects": [diff --git a/packages/lib/src/party-contact.test.ts b/packages/lib/src/party-contact.test.tsindex 6fc96538a6..8a70398009 100644--- a/packages/lib/src/party-contact.test.ts+++ b/packages/lib/src/party-contact.test.ts@@ -3,37 +3,30 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { describe, expect, it } from "vitest";-import * as partyContact from "./party-contact";import {hasEmailableContact,hasUsableLocation,isEmailableContact,isUsableLocationAddress,missingPartyFacts,- PARTY_CONTACT_SETTING,- partyContactRequiredMessage,- STATE_REQUIRED_COUNTRIES+ type PartyContactRow,+ type PartyLocationRow,+ partyContactRequiredMessage} from "./party-contact";-/**- * Every bar below is what a spend-vendor create actually enforces, verified- * field-by-field against the Ramp sandbox on 2026-09-28. A gate that is LOOSER- * than the platform lets the document post and fail downstream, which is worse- * than no gate; a gate that is STRICTER blocks work for no reason.- */+// Every bar below is what a Ramp vendor create enforces (sandbox, 2026-09-28):+// looser lets a document post and fail downstream, stricter blocks for nothing.describe("isEmailableContact", () => {it("accepts a contact with an email", () => {expect(isEmailableContact({ email: "[email protected]" })).toBe(true);});- it("rejects a blank-but-present email", () => {- // `{"business_vendor_contacts": {"email": ["Missing data for required- // field."]}}` — a phone-only contact satisfies nothing, and an empty string- // in the column is common enough that it would otherwise pass.- for (const email of ["", " ", null, undefined]) {+ it.each(["", " ", null, undefined])(+ "rejects a contact whose email is %j",+ (email) => {expect(isEmailableContact({ email })).toBe(false);}- });+ );});describe("hasEmailableContact", () => {@@ -54,60 +47,37 @@ describe("hasEmailableContact", () => {});describe("isUsableLocationAddress", () => {- /**- * `{"country": ["Missing data for required field."]}` with no country, and- * `400 DEVELOPER_7080 "State is required for US"` for a US address with no- * state. A GB address with no state was accepted (200), so the state rule is- * genuinely per-country rather than general address hygiene.- */- it("accepts a non-US address with just a country", () => {- expect(isUsableLocationAddress({ country: "GB" })).toBe(true);- expect(- isUsableLocationAddress({ country: "DE", stateProvince: null })- ).toBe(true);- });-- it("refuses an address with no country", () => {- for (const country of ["", " ", null, undefined]) {- expect(isUsableLocationAddress({ country })).toBe(false);- }- });-- it("refuses a US address with no state, and accepts one with a state", () => {- expect(isUsableLocationAddress({ country: "US" })).toBe(false);- expect(- isUsableLocationAddress({ country: "US", stateProvince: " " })- ).toBe(false);- expect(- isUsableLocationAddress({ country: "US", stateProvince: "VA" })- ).toBe(true);- });-- it("applies the US state rule whatever the casing or alpha-3 form", () => {- // Carbon stores `address.countryCode` as free text; "us" and "USA" are the- // same country to Ramp and must not slip past the state rule.- expect(isUsableLocationAddress({ country: "us" })).toBe(false);- expect(isUsableLocationAddress({ country: "USA" })).toBe(false);- expect(STATE_REQUIRED_COUNTRIES.has("US")).toBe(true);+ // Ramp accepts a GB vendor with no state and refuses a US one.+ it.each([+ [{ country: "GB" }, true],+ [{ country: "DE", stateProvince: null }, true],+ [{ country: "US", stateProvince: "VA" }, true],+ [{ country: "" }, false],+ [{ country: " " }, false],+ [{ country: null }, false],+ [{}, false],+ [{ country: "US" }, false],+ [{ country: "US", stateProvince: " " }, false],+ // countryCode is free text: "us" and "USA" are the US too.+ [{ country: "us" }, false],+ [{ country: "USA" }, false]+ ])("%j is usable: %s", (address, expected) => {+ expect(isUsableLocationAddress(address)).toBe(expected);});});describe("hasUsableLocation", () => {it("is satisfied by one usable location among several", () => {- // A party often has a billing address with no country and a real ship-from- // with one. Any single usable location is enough — the push picks it.expect(hasUsableLocation([{ country: null },- { country: "US" }, // US with no state — not usable+ { country: "US" },{ country: "US", stateProvince: "CA" }])).toBe(true);});- it("refuses no locations at all, which is the common failure", () => {- // McMaster-Carr had zero contacts AND zero locations; both halves of the- // push error were real.+ it("refuses no locations, or only unusable ones", () => {expect(hasUsableLocation([])).toBe(false);expect(hasUsableLocation([{ country: null }, { country: "US" }])).toBe(false@@ -115,128 +85,86 @@ describe("hasUsableLocation", () => {});});-describe("PARTY_CONTACT_SETTING", () => {- it("maps each party kind to its own company setting", () => {- // These are column names in a live query — a typo is a runtime failure the- // type system cannot see. The two are independent on purpose: the- // purchasing side has a platform requirement behind it, the sales side- // ships off and has none yet.- expect(PARTY_CONTACT_SETTING.supplier).toBe(- "requireSupplierContactAndLocation"- );- expect(PARTY_CONTACT_SETTING.customer).toBe(- "requireCustomerContactAndLocation"- );- });-});-describe("partyContactRequiredMessage", () => {- it("names only the fact that is actually missing", () => {- const contactOnly = partyContactRequiredMessage(- "supplier",- "Deep Space RF",- {- contact: true,- location: false- }- );- expect(contactOnly).toContain("Deep Space RF");- expect(contactOnly).toContain("email");- expect(contactOnly).not.toContain("country");- expect(contactOnly).toContain("Contacts");-- const locationOnly = partyContactRequiredMessage("supplier", "Acme", {- contact: false,- location: true- });- expect(locationOnly).toContain("country");- expect(locationOnly).not.toContain("email");- expect(locationOnly).toContain("Locations");- });-- it("names both when both are missing, which is the common case", () => {- // A supplier somebody created from just a name has neither.- const message = partyContactRequiredMessage("supplier", "McMaster-Carr", {- contact: true,- location: true- });-- expect(message).toContain("email");- expect(message).toContain("country");- expect(message).toContain("Contacts and Locations");- });-- it("mentions the US state rule, since that is the non-obvious half", () => {+ it("names the party, both missing facts and where to add them", () => {expect(- partyContactRequiredMessage("supplier", "Acme", {- contact: false,- location: true- })- ).toContain("state");- });-- it("stays readable when the party has no name", () => {- expect(- partyContactRequiredMessage("customer", null, {- contact: true,- location: false- })- ).toContain("This customer");- expect(- partyContactRequiredMessage("supplier", " ", {- contact: true,- location: false- })- ).toContain("This supplier");- });-- it("says the requirement came from settings, not from nowhere", () => {- // Without this the message reads as a hard product rule, and the person- // hitting it has no idea it is a company setting somebody turned on.- expect(- partyContactRequiredMessage("supplier", "Acme", {+ partyContactRequiredMessage("supplier", "McMaster-Carr", {contact: true,location: true})- ).toContain("settings");+ ).toBe(+ "McMaster-Carr needs a contact with an email address and a location with a country (and a state, for US addresses). Add them on the supplier record before posting. (Suppliers → Contacts and Locations. This is required by your company's settings.)"+ );});++ it.each([+ [+ "supplier",+ "Acme",+ { contact: true, location: false },+ /^Acme needs a contact with an email address\. Add it .*Suppliers → Contacts\./+ ],+ [+ "customer",+ "Acme",+ { contact: false, location: true },+ /^Acme needs a location with a country .*Customers → Locations\./+ ],+ [+ "customer",+ null,+ { contact: true, location: false },+ /^This customer needs /+ ],+ [+ "supplier",+ " ",+ { contact: true, location: false },+ /^This supplier needs /+ ]+ ] as const)(+ "phrases a %s named %j missing %j",+ (kind, name, missing, expected) => {+ expect(partyContactRequiredMessage(kind, name, missing)).toMatch(+ expected+ );+ }+ );});describe("missingPartyFacts", () => {- /**- * The decision `checkPartyContactRequirement` makes, without its three- * queries. Both halves below have been wrong in this file's history.- */- const reachable = [{ contact: { email: "[email protected]" } }];- const placeable = [{ address: { countryCode: "GB" } }];+ function base(overrides: {+ contacts?: { rows: PartyContactRow[] | null; failed: boolean };+ locations?: { rows: PartyLocationRow[] | null; failed: boolean };+ }) {+ return missingPartyFacts({+ contacts: {+ rows: [{ contact: { email: "[email protected]" } }],+ failed: false+ },+ locations: { rows: [{ address: { countryCode: "GB" } }], failed: false },+ ...overrides+ });+ }it("finds nothing missing for a complete party", () => {- expect(- missingPartyFacts({- contacts: { rows: reachable, failed: false },- locations: { rows: placeable, failed: false }- })- ).toEqual({ contact: false, location: false });+ expect(base({})).toEqual({ contact: false, location: false });});- it("maps address.countryCode onto the address rule's `country`", () => {- // The column is `countryCode`; the rule takes `country`. Miss the rename and- // every complete address reads as "no country", blocking a fine record.+ it("reads the stored countryCode as the address rule's country", () => {expect(- missingPartyFacts({- contacts: { rows: reachable, failed: false },+ base({locations: {rows: [{ address: { countryCode: "US", stateProvince: "VA" } }],failed: false}- }).location- ).toBe(false);+ })+ ).toEqual({ contact: false, location: false });});- it("carries the US state rule through the stored columns", () => {+ it("applies the US state rule to the stored columns", () => {expect(- missingPartyFacts({- contacts: { rows: reachable, failed: false },+ base({locations: {rows: [{ address: { countryCode: "US", stateProvince: null } }],failed: false@@ -245,10 +173,9 @@ describe("missingPartyFacts", () => {).toEqual({ contact: false, location: true });});- it("treats an unjoined embed as absent, not as a crash", () => {- // PostgREST returns the join row with a null embed when the FK is dangling.+ it("treats an unjoined embed as absent", () => {expect(- missingPartyFacts({+ base({contacts: { rows: [{ contact: null }, {}], failed: false },locations: { rows: [{ address: null }, {}], failed: false }})@@ -257,53 +184,37 @@ describe("missingPartyFacts", () => {it("reports both missing for a party created from just a name", () => {expect(- missingPartyFacts({+ base({contacts: { rows: [], failed: false },locations: { rows: [], failed: false }})).toEqual({ contact: true, location: true });});- it("fails open per read, without suppressing the other half", () => {- // A locations query that errored must not be reported as "no location" —- // and must not hide a genuinely unreachable supplier either. Skipping BOTH- // halves on EITHER error is what this pins against.- expect(- missingPartyFacts({+ // A failed read must not report its fact missing, nor hide the other read's finding.+ it.each([+ [+ {contacts: { rows: [], failed: false },locations: { rows: null, failed: true }- })- ).toEqual({ contact: true, location: false });-- expect(- missingPartyFacts({+ },+ { contact: true, location: false }+ ],+ [+ {contacts: { rows: null, failed: true },locations: { rows: [], failed: false }- })- ).toEqual({ contact: false, location: true });- });-- it("finds nothing missing when both reads failed", () => {- // Which makes `checkPartyContactRequirement` return null — a database hiccup- // is not a reason to block a post. The route logs the degradation.- expect(- missingPartyFacts({+ },+ { contact: false, location: true }+ ],+ [+ {contacts: { rows: null, failed: true },locations: { rows: null, failed: true }- })- ).toEqual({ contact: false, location: false });- });-});--describe("the party check is the only enforcement point", () => {- it("exposes no document field-level requirement (D-2)", () => {- // `requiredContactField` was applied by six `make*Validator` factories, which- // only the six browser forms and the six `*.details.tsx` actions used — every- // CREATE action, the API and MCP kept the permissive validator, so the rule- // was cosmetic there. It also refused to save an EXISTING draft whose- // optional location was null, blocking edits to unrelated fields. Deleting- // the helper is what stops a seventh copy being built on it; the bar now- // lives in `checkPartyContactRequirement` alone.- expect(Object.keys(partyContact)).not.toContain("requiredContactField");+ },+ { contact: false, location: false }+ ]+ ])("fails open per read: %j", (reads, expected) => {+ expect(base(reads)).toEqual(expected);});});diff --git a/packages/locale/package.json b/packages/locale/package.jsonindex 89725ed8fc..baf071ddd7 100644--- a/packages/locale/package.json+++ b/packages/locale/package.json@@ -26,7 +26,7 @@"clean": "rimraf .turbo node_modules","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"sideEffects": false,"version": "0.0.0"diff --git a/packages/logger/package.json b/packages/logger/package.jsonindex 4a8c3efd50..db24e0fbd2 100644--- a/packages/logger/package.json+++ b/packages/logger/package.json@@ -44,7 +44,7 @@"lint": "biome lint --write ","test": "vitest run","test:watch": "vitest",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"sideEffects": false,"version": "0.0.0"diff --git a/packages/logger/src/http-formatter.test.ts b/packages/logger/src/http-formatter.test.tsindex 4db8ae0ad8..2c8980ef51 100644--- a/packages/logger/src/http-formatter.test.ts+++ b/packages/logger/src/http-formatter.test.ts@@ -5,114 +5,52 @@import { describe, expect, it } from "vitest";import { httpDevFormatter } from "./http-formatter";-function record(properties: Record<string, unknown>) {- return {+// Colours are cosmetic; assert the text a developer reads.+function format(properties: Record<string, unknown>) {+ const line = httpDevFormatter({category: ["carbon", "http"],level: "debug",message: ["access log"],rawMessage: "access log",timestamp: Date.now(),properties- } as never;+ } as never);+ // biome-ignore lint/suspicious/noControlCharactersInRegex: strips ANSI escapes+ return line.replace(/\x1b\[\d+m/g, "").trimEnd();}-describe("httpDevFormatter", () => {- it("renders a pino-style time-only / level / pid / module prefix", () => {- const line = httpDevFormatter(- record({ method: "GET", pathname: "/dashboard", status: 200 })- );- // [HH:MM:SS.mmm] — time only, no date.- expect(line).toMatch(/\[\d{2}:\d{2}:\d{2}\.\d{3}\]/);- // Uppercase level, pid, and the `carbon`-stripped module.- expect(line).toContain("DEBUG");- expect(line).toContain(`(${process.pid})`);- expect(line).toContain("[http]");- // No full date in the line.- expect(line).not.toMatch(/\d{4}-\d{2}-\d{2}/);- });-- it("includes the query string, redacting sensitive params", () => {- const line = httpDevFormatter(- record({- method: "GET",- pathname: "/callback",- search: "?ref=home&token=%5BREDACTED%5D",- status: 200- })- );- expect(line).toContain("/callback?ref=home&token=%5BREDACTED%5D");- });+const access = { method: "GET", pathname: "/dashboard", status: 200 };- it("renders the message portion as a morgan dev-style access line — bold colored method, dimmed duration", () => {- const line = httpDevFormatter(- record({- method: "GET",- pathname: "/dashboard",- status: 200,- responseTime: 12.34- })- );- expect(line).toContain(- "\x1b[1m\x1b[32mGET\x1b[0m \x1b[32m200\x1b[0m /dashboard \x1b[2m12.3 ms\x1b[0m"- );- });-- it("colors the method: GET green, POST yellow, DELETE red", () => {- expect(- httpDevFormatter(record({ method: "GET", pathname: "/x", status: 200 }))- ).toContain("\x1b[1m\x1b[32mGET\x1b[0m");- expect(- httpDevFormatter(record({ method: "POST", pathname: "/x", status: 200 }))- ).toContain("\x1b[1m\x1b[33mPOST\x1b[0m");- expect(- httpDevFormatter(- record({ method: "DELETE", pathname: "/x", status: 200 })+describe("httpDevFormatter", () => {+ it("prefixes a time-only clock, level, pid and the module without its carbon root", () => {+ const line = format(access);+ expect(line).toMatch(+ new RegExp(+ `^\\[\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\] DEBUG \\(${process.pid}\\): \\[http\\] `)- ).toContain("\x1b[1m\x1b[31mDELETE\x1b[0m");+ );});- it("colors 3xx cyan, 4xx yellow, 5xx red", () => {+ it("renders an access log as method, status, path with query, and duration", () => {expect(- httpDevFormatter(record({ method: "GET", pathname: "/x", status: 301 }))- ).toContain("\x1b[36m301\x1b[0m");- expect(- httpDevFormatter(record({ method: "GET", pathname: "/x", status: 404 }))- ).toContain("\x1b[33m404\x1b[0m");- expect(- httpDevFormatter(record({ method: "POST", pathname: "/x", status: 500 }))- ).toContain("\x1b[31m500\x1b[0m");+ format({ ...access, search: "?ref=home", responseTime: 12.34 })+ ).toContain("GET 200 /dashboard?ref=home 12.3 ms");});- it("truncates rather than rounds, and drops a padded trailing zero", () => {- // 12.36 rounds to 12.4 but truncates to 12.3 — must match truncation.- expect(- httpDevFormatter(- record({- method: "GET",- pathname: "/x",- status: 200,- responseTime: 12.36- })- )- ).toContain("\x1b[2m12.3 ms\x1b[0m");- // Exact integer ms — no forced ".0".- expect(- httpDevFormatter(- record({ method: "GET", pathname: "/x", status: 200, responseTime: 5 })- )- ).toContain("\x1b[2m5 ms\x1b[0m");+ it.each([+ [12.36, "12.3 ms"],+ [5, "5 ms"]+ ])("truncates a %f ms response time to %s", (responseTime, expected) => {+ expect(format({ ...access, responseTime })).toMatch(+ new RegExp(` ${expected.replace(".", "\\.")}$`)+ );});- it("omits response time when absent", () => {- const line = httpDevFormatter(- record({ method: "GET", pathname: "/x", status: 200 })- );- expect(line).toContain("\x1b[1m\x1b[32mGET\x1b[0m \x1b[32m200\x1b[0m /x");- expect(line).not.toContain("ms");+ it("omits the duration when the response time is absent", () => {+ expect(format(access)).toMatch(/GET 200 \/dashboard$/);});- it("falls back to the default rendered message for non-access-log records", () => {- const line = httpDevFormatter(record({ note: "not an access log" }));- expect(line).toContain("access log");+ it("falls back to the rendered message for a record that is not an access log", () => {+ expect(format({ note: "not an access log" })).toMatch(/ access log$/);});});diff --git a/packages/notifications/AGENTS.md b/packages/notifications/AGENTS.mdindex 1c91c0999d..b478ae90ad 100644--- a/packages/notifications/AGENTS.md+++ b/packages/notifications/AGENTS.md@@ -22,7 +22,7 @@ Notification event taxonomy — enums and topic mapping shared across app routes## Validation Commands```bash-pnpm --filter @carbon/notifications typecheck # tsgo --noEmit+pnpm --filter @carbon/notifications typecheck # tsc --noEmit```## Key Patternsdiff --git a/packages/notifications/package.json b/packages/notifications/package.jsonindex 0c38a4edfc..587bacf5e6 100644--- a/packages/notifications/package.json+++ b/packages/notifications/package.json@@ -16,7 +16,7 @@"dev": "tsup --watch","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"sideEffects": false,"type": "module",diff --git a/packages/onboarding/AGENTS.md b/packages/onboarding/AGENTS.mdindex 907048b20e..7c297435fe 100644--- a/packages/onboarding/AGENTS.md+++ b/packages/onboarding/AGENTS.md@@ -24,7 +24,7 @@ Implementation Hub — onboarding blueprint, pure logic, server DB helpers, and```bashpnpm --filter @carbon/onboarding test # vitest-pnpm --filter @carbon/onboarding typecheck # tsgo --noEmit+pnpm --filter @carbon/onboarding typecheck # tsc --noEmit```## Key Patternsdiff --git a/packages/onboarding/package.json b/packages/onboarding/package.jsonindex f34f80ded0..f17f3ff3b2 100644--- a/packages/onboarding/package.json+++ b/packages/onboarding/package.json@@ -10,14 +10,10 @@"./ui": "./src/ui/index.ts"},"dependencies": {- "@carbon/database": "workspace:*",- "@carbon/form": "workspace:*","@carbon/react": "workspace:*",- "@carbon/utils": "workspace:*","@internationalized/date": "catalog:","@lingui/core": "catalog:","@lingui/react": "catalog:",- "@supabase/supabase-js": "catalog:","react": "catalog:","react-icons": "catalog:","zod": "catalog:",@@ -25,6 +21,10 @@},"devDependencies": {"@carbon/config": "workspace:*",+ "@carbon/database": "workspace:*",+ "@carbon/form": "workspace:*",+ "@carbon/utils": "workspace:*",+ "@supabase/supabase-js": "catalog:","@types/react": "catalog:","rimraf": "catalog:","tsup": "catalog:",@@ -36,6 +36,6 @@"dev": "tsup --watch","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"}}diff --git a/packages/planning/package.json b/packages/planning/package.jsonindex 9feec0493e..5bef68bc6b 100644--- a/packages/planning/package.json+++ b/packages/planning/package.json@@ -11,19 +11,19 @@"clean": "rimraf .turbo node_modules","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"dependencies": {"@carbon/database": "workspace:*","@carbon/logger": "workspace:*","@carbon/utils": "workspace:*","@internationalized/date": "catalog:",- "@supabase/supabase-js": "catalog:","kysely": "catalog:","zod": "catalog:"},"devDependencies": {"@carbon/config": "workspace:*",+ "@supabase/supabase-js": "catalog:","typescript": "catalog:","vitest": "catalog:"}diff --git a/packages/planning/src/mrp/planning-actions.ts b/packages/planning/src/mrp/planning-actions.tsindex 42ee907491..b0c6a2b4a7 100644--- a/packages/planning/src/mrp/planning-actions.ts+++ b/packages/planning/src/mrp/planning-actions.ts@@ -1027,6 +1027,44 @@ const PATCH_COLUMN_TYPES: Record<string, string> = {assignee: "text"};+/**+ * The diff's updates grouped by the columns they change, one group per+ * statement, each row as its `VALUES` tuple (`id`, then the group's columns).+ * Throws on a column with no known type before anything is written.+ */+export function groupPatchUpdates(+ updates: PlanningActionDiff["updates"]+): { columns: string[]; rows: unknown[][] }[] {+ const groups = new Map<string, PlanningActionDiff["updates"]>();+ for (const update of updates) {+ const shape = Object.keys(update.patch).sort().join(",");+ const group = groups.get(shape);+ if (group) group.push(update);+ else groups.set(shape, [update]);+ }++ return [...groups].map(([shape, group]) => {+ const columns = shape.split(",");+ for (const column of columns) {+ if (!PATCH_COLUMN_TYPES[column]) {+ throw new Error(`No column type for planning action patch "${column}"`);+ }+ }+ return {+ columns,+ rows: group.map((row) => [+ row.id,+ ...columns.map((column) => {+ const value = row.patch[column] ?? null;+ return column === "triggerValues" && value !== null+ ? JSON.stringify(value)+ : value;+ })+ ])+ };+ });+}+/*** Writes one run's diff inside the caller's transaction.*@@ -1063,21 +1101,7 @@ export async function writePlanningActionDiff(.execute();}- const groups = new Map<string, PlanningActionDiff["updates"]>();- for (const update of diff.updates) {- const shape = Object.keys(update.patch).sort().join(",");- const group = groups.get(shape);- if (group) group.push(update);- else groups.set(shape, [update]);- }-- for (const [shape, rows] of groups) {- const columns = shape.split(",");- for (const column of columns) {- if (!PATCH_COLUMN_TYPES[column]) {- throw new Error(`No column type for planning action patch "${column}"`);- }- }+ for (const { columns, rows } of groupPatchUpdates(diff.updates)) {// The diff skipped an overridden assignee when it READ the row, but a// planner can assign between that read and this write (Assign does not// take the run's lock), so the statement re-checks the flag on the row.@@ -1094,18 +1118,7 @@ export async function writePlanningActionDiff(for (let i = 0; i < rows.length; i += BATCH_SIZE) {const values = sql.join(- rows.slice(i, i + BATCH_SIZE).map(- (row) =>- sql`(${sql.join([- row.id,- ...columns.map((column) => {- const value = row.patch[column] ?? null;- return column === "triggerValues" && value !== null- ? JSON.stringify(value)- : value;- })- ])})`- )+ rows.slice(i, i + BATCH_SIZE).map((row) => sql`(${sql.join(row)})`));await sql`UPDATE "planningAction" AS tdiff --git a/packages/planning/src/mrp/planning-actions.write.test.ts b/packages/planning/src/mrp/planning-actions.write.test.tsindex b5912a60ed..0dc606a6ff 100644--- a/packages/planning/src/mrp/planning-actions.write.test.ts+++ b/packages/planning/src/mrp/planning-actions.write.test.ts@@ -2,155 +2,66 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import type { DB } from "@carbon/database/client";-import {- type CompiledQuery,- type DatabaseConnection,- DummyDriver,- Kysely,- PostgresAdapter,- PostgresIntrospector,- PostgresQueryCompiler,- type QueryResult-} from "kysely";import { describe, expect, it } from "vitest";-import {- type PlanningActionDiff,- writePlanningActionDiff-} from "./planning-actions";+import { groupPatchUpdates } from "./planning-actions";-// The Postgres wire is the boundary: every statement the writer sends is-// recorded as compiled SQL with its parameters.-class RecordingDriver extends DummyDriver {- readonly sent: CompiledQuery[] = [];- override async acquireConnection(): Promise<DatabaseConnection> {- return {- executeQuery: async <R>(- query: CompiledQuery- ): Promise<QueryResult<R>> => {- this.sent.push(query);- return { rows: [] };+describe("groupPatchUpdates", () => {+ // One UPDATE per row was thousands of round trips on the weekly roll.+ it("puts rows that change the same columns in one group, whatever the key order", () => {+ expect(+ groupPatchUpdates([+ { id: "a1", patch: { periodId: "p2" } },+ { id: "a2", patch: { suggestedQuantity: 12, status: "Open" } },+ { id: "a3", patch: { periodId: "p3" } },+ { id: "a4", patch: { status: "Dismissed", suggestedQuantity: 4 } }+ ])+ ).toEqual([+ {+ columns: ["periodId"],+ rows: [+ ["a1", "p2"],+ ["a3", "p3"]+ ]},- // biome-ignore lint/correctness/useYield: never streamed- streamQuery: async function* () {- throw new Error("not streamed");+ {+ columns: ["status", "suggestedQuantity"],+ rows: [+ ["a2", "Open", 12],+ ["a4", "Dismissed", 4]+ ]}- };- }-}--function database() {- const driver = new RecordingDriver();- const db = new Kysely<DB>({- dialect: {- createAdapter: () => new PostgresAdapter(),- createDriver: () => driver,- createIntrospector: (k) => new PostgresIntrospector(k),- createQueryCompiler: () => new PostgresQueryCompiler()- }+ ]);});- return { db, driver };-}-const emptyDiff: PlanningActionDiff = {- inserts: [],- updates: [],- deleteIds: []-};--async function write(diff: Partial<PlanningActionDiff>) {- const { db, driver } = database();- await writePlanningActionDiff(db, {- companyId: "c1",- userId: "u1",- diff: { ...emptyDiff, ...diff },- updatedAt: "2026-10-06T00:00:00.000Z"- });- return driver.sent;-}--describe("writePlanningActionDiff", () => {- // The run reads the actions, then writes its diff. A row applied in between- // was deleted, or reopened by a `status: "Open"` patch.- it("never deletes an applied action", async () => {- const [statement] = await write({ deleteIds: ["a1", "a2"] });- expect(statement?.sql).toMatch(/^delete from "planningAction"/);- expect(statement?.sql).toContain('"status" != $');- expect(statement?.parameters).toContain("Actioned");- expect(statement?.parameters).toContain("c1");- });-- it("never updates an applied action", async () => {- const [statement] = await write({- updates: [{ id: "a1", patch: { status: "Open" } }]- });- expect(statement?.sql).toContain(`t."status" <> 'Actioned'`);- expect(statement?.sql).toContain(`t."companyId" = $`);+ it("writes trigger values as JSON and a cleared value as null", () => {+ expect(+ groupPatchUpdates([+ {+ id: "a1",+ patch: { triggerValues: { reorderPoint: 5 }, reason: null }+ },+ {+ id: "a2",+ patch: { triggerValues: null, reason: "Below reorder point" }+ }+ ])+ ).toEqual([+ {+ columns: ["reason", "triggerValues"],+ rows: [+ ["a1", null, '{"reorderPoint":5}'],+ ["a2", "Below reorder point", null]+ ]+ }+ ]);});- // One UPDATE per row was thousands of round trips on the weekly roll.- it("sends one statement per set of changed columns, not per row", async () => {- const sent = await write({- updates: [+ it("refuses a patch column it has no type for", () => {+ expect(() =>+ groupPatchUpdates([{ id: "a1", patch: { periodId: "p2" } },- { id: "a2", patch: { periodId: "p3" } },- { id: "a3", patch: { periodId: "p4" } },- { id: "a4", patch: { suggestedQuantity: 12, status: "Open" } }- ]- });- expect(sent).toHaveLength(2);-- const periodOnly = sent.find((q) => !q.sql.includes("suggestedQuantity"));- expect(periodOnly?.sql).toContain(`"periodId" = v."periodId"::text`);- expect(periodOnly?.parameters).toEqual(- expect.arrayContaining(["a1", "p2", "a2", "p3", "a3", "p4"])- );-- const reopen = sent.find((q) => q.sql.includes("suggestedQuantity"));- expect(reopen?.sql).toContain(- `"status" = v."status"::"planningActionStatus"`- );- expect(reopen?.sql).toContain(- `"suggestedQuantity" = v."suggestedQuantity"::numeric`- );- // Only the patched columns: a period-only row keeps its stored quantity.- expect(periodOnly?.sql).not.toContain("suggestedQuantity");- });-- // The diff skips an overridden assignee when it READS the row; a planner- // who assigns between that read and the write (Assign takes no lock) must- // still win, so the statement re-checks the flag on the row itself.- it("keeps a planner's overridden assignee in the statement itself", async () => {- const [statement] = await write({- updates: [{ id: "a1", patch: { assignee: "u2", suggestedQuantity: 3 } }]- });- expect(statement?.sql).toContain(- `"assignee" = CASE WHEN t."assigneeOverridden" THEN t."assignee" ELSE v."assignee"::text END`- );- // The other columns of the same statement still update unconditionally.- expect(statement?.sql).toContain(- `"suggestedQuantity" = v."suggestedQuantity"::numeric`- );- });-- it("writes trigger values as JSON", async () => {- const [statement] = await write({- updates: [{ id: "a1", patch: { triggerValues: { reorderPoint: 5 } } }]- });- expect(statement?.sql).toContain(`"triggerValues"::jsonb`);- expect(statement?.parameters).toContain('{"reorderPoint":5}');- });-- it("refuses a patch column it has no type for, before writing", async () => {- const { db, driver } = database();- await expect(- writePlanningActionDiff(db, {- companyId: "c1",- userId: "u1",- diff: { ...emptyDiff, updates: [{ id: "a1", patch: { bogus: 1 } }] },- updatedAt: "2026-10-06T00:00:00.000Z"- })- ).rejects.toThrow(/bogus/);- expect(driver.sent).toHaveLength(0);+ { id: "a2", patch: { bogus: 1 } }+ ])+ ).toThrow(/bogus/);});});diff --git a/packages/planning/src/scheduling/conflict-messages.test.ts b/packages/planning/src/scheduling/conflict-messages.test.tsindex 2cfa059a4a..b81dec27be 100644--- a/packages/planning/src/scheduling/conflict-messages.test.ts+++ b/packages/planning/src/scheduling/conflict-messages.test.ts@@ -2,400 +2,295 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { it } from "vitest";+import { describe, expect, it } from "vitest";import {+ type BehindTargetOperation,classifyLatePlacement,composeBehindTarget,composeLateConflict,composePlacementNote,- formatWaitDuration+ formatWaitDuration,+ type LatePlacementCause,+ type WaitAttribution} from "./conflict-messages.ts";-import { assertEquals } from "./test-helpers.ts";const HOUR = 3_600_000;+const BLOCKERS = "queued behind J000009 (3 ops), J000010 (1 op)";-it("waited behind other jobs' operators → operator-queue naming the blockers", () => {- const cause = classifyLatePlacement({- waitedMs: 30 * HOUR,- wait: {- resource: "operator",- blockers: "queued behind J000009 (3 ops), J000010 (1 op)",- ownJobAhead: false- },- dominantDep: null- });- assertEquals(cause, {- kind: "operator-queue",- blockers: "queued behind J000009 (3 ops), J000010 (1 op)"- });- assertEquals(- composeLateConflict("2026-07-20", "2026-07-17", cause),- "Finishes 2026-07-20 but the job is due 2026-07-17 — waited for a qualified operator, queued behind J000009 (3 ops), J000010 (1 op)"- );-});+function wait(overrides: Partial<WaitAttribution>): WaitAttribution {+ return {+ resource: "operator",+ blockers: null,+ ownJobAhead: false,+ ...overrides+ };+}-it("waited behind other jobs on the machine → machine-queue naming the blockers", () => {- const cause = classifyLatePlacement({- waitedMs: 30 * HOUR,- wait: {- resource: "machine",- blockers: "queued behind J000009 (1 op)",- ownJobAhead: false- },- dominantDep: null+describe("classifyLatePlacement", () => {+ it.each<+ [string, Parameters<typeof classifyLatePlacement>[0], LatePlacementCause]+ >([+ [+ "another job held the operator",+ { waitedMs: HOUR, wait: wait({ blockers: BLOCKERS }), dominantDep: null },+ { kind: "operator-queue", blockers: BLOCKERS }+ ],+ [+ "another job held the operator, over own-job queueing and a dominant dep",+ {+ waitedMs: HOUR,+ wait: wait({ blockers: BLOCKERS, ownJobAhead: true }),+ dominantDep: { description: "Assembly" }+ },+ { kind: "operator-queue", blockers: BLOCKERS }+ ],+ [+ "this job's own operations held the operator",+ { waitedMs: HOUR, wait: wait({ ownJobAhead: true }), dominantDep: null },+ { kind: "own-job-queue" }+ ],+ [+ "the operator wait has no attributable reservation",+ { waitedMs: HOUR, wait: wait({}), dominantDep: null },+ { kind: "operator-wait" }+ ],+ [+ "the wait was a shift gap with no attribution",+ { waitedMs: HOUR, wait: null, dominantDep: null },+ { kind: "operator-wait" }+ ],+ [+ "a staffed station waited for its people",+ { waitedMs: HOUR, wait: wait({}), dominantDep: null, staffed: true },+ { kind: "people-wait" }+ ],+ [+ "another job held the machine",+ {+ waitedMs: HOUR,+ wait: wait({ resource: "machine", blockers: BLOCKERS }),+ dominantDep: null+ },+ { kind: "machine-queue", blockers: BLOCKERS }+ ],+ [+ "this job's own operations held the machine",+ {+ waitedMs: HOUR,+ wait: wait({ resource: "machine", ownJobAhead: true }),+ dominantDep: null+ },+ { kind: "machine-own-job" }+ ],+ [+ "a staffed station waited for the machine",+ {+ waitedMs: HOUR,+ wait: wait({ resource: "machine" }),+ dominantDep: null,+ staffed: true+ },+ { kind: "machine-wait" }+ ],+ [+ "it did not wait but a predecessor bound its start",+ { waitedMs: 0, wait: null, dominantDep: { description: "Battery Test" } },+ { kind: "inherited-delay", predecessorDescription: "Battery Test" }+ ],+ [+ "nothing delayed it",+ { waitedMs: 0, wait: null, dominantDep: null },+ { kind: "no-runway" }+ ]+ ])("classifies the case where %s", (_, args, expected) => {+ expect(classifyLatePlacement(args)).toEqual(expected);});- assertEquals(cause, {- kind: "machine-queue",- blockers: "queued behind J000009 (1 op)"- });- assertEquals(- composeLateConflict("2026-07-20", "2026-07-17", cause),- "Finishes 2026-07-20 but the job is due 2026-07-17 — waited for the work center, queued behind J000009 (1 op)"- );});-it("machine busy with this job's own operations → machine-own-job", () => {- const cause = classifyLatePlacement({- waitedMs: 8 * HOUR,- wait: { resource: "machine", blockers: null, ownJobAhead: true },- dominantDep: null+describe("composeLateConflict", () => {+ // Stored on jobOperation.conflictReason and shown verbatim on the boards.+ it.each<[LatePlacementCause, string]>([+ [+ { kind: "operator-queue", blockers: BLOCKERS },+ `waited for a qualified operator, ${BLOCKERS}`+ ],+ [+ { kind: "own-job-queue" },+ "waited for a qualified operator, busy with earlier operations in this job"+ ],+ [+ { kind: "operator-wait" },+ "waited for a qualified operator to be available"+ ],+ [{ kind: "people-wait" }, "waited for the assigned people to be available"],+ [+ { kind: "machine-queue", blockers: BLOCKERS },+ `waited for the work center, ${BLOCKERS}`+ ],+ [+ { kind: "machine-own-job" },+ "waited for the work center, busy with earlier operations in this job"+ ],+ [{ kind: "machine-wait" }, "waited for the work center to be available"],+ [+ { kind: "inherited-delay", predecessorDescription: "Battery Test" },+ 'starts late because it waits for "Battery Test" earlier in this job; its own work center was free'+ ],+ [+ { kind: "inherited-delay", predecessorDescription: null },+ "starts late because it waits for an earlier operation earlier in this job; its own work center was free"+ ],+ [{ kind: "no-runway" }, "not enough time remains before the due date"],+ [+ { kind: "outside-processing" },+ "outside processing pushes it past the due date"+ ]+ ])("explains %j", (cause, reason) => {+ expect(composeLateConflict("2026-07-20", "2026-07-17", cause)).toBe(+ `Finishes 2026-07-20 but the job is due 2026-07-17 — ${reason}`+ );});- assertEquals(cause, { kind: "machine-own-job" });- assertEquals(- composeLateConflict("2026-07-20", "2026-07-17", cause),- "Finishes 2026-07-20 but the job is due 2026-07-17 — waited for the work center, busy with earlier operations in this job"- );});-it("machine-bound wait with no attributable reservations → machine-wait", () => {- const cause = classifyLatePlacement({- waitedMs: 2 * HOUR,- wait: { resource: "machine", blockers: null, ownJobAhead: false },- dominantDep: null+describe("composePlacementNote", () => {+ it.each<[LatePlacementCause, number, string | null]>([+ [+ { kind: "operator-queue", blockers: BLOCKERS },+ 14 * HOUR,+ `Waited 14h for a qualified operator — ${BLOCKERS}`+ ],+ [+ { kind: "own-job-queue" },+ 8 * HOUR,+ "Waited 8h for a qualified operator — busy with earlier operations in this job"+ ],+ [+ { kind: "operator-wait" },+ 90 * 60_000,+ "Waited 1h 30m for a qualified operator to be available"+ ],+ [{ kind: "people-wait" }, 2 * HOUR, "Waited 2h for the assigned people"],+ [+ { kind: "machine-queue", blockers: BLOCKERS },+ 14 * HOUR,+ `Waited 14h for the work center — ${BLOCKERS}`+ ],+ [+ { kind: "machine-own-job" },+ 8 * HOUR,+ "Waited 8h for the work center — busy with earlier operations in this job"+ ],+ [+ { kind: "machine-wait" },+ 2 * HOUR,+ "Waited 2h for the work center to be available"+ ],+ [+ { kind: "inherited-delay", predecessorDescription: "Flash Firmware" },+ 0,+ 'Starts after "Flash Firmware" finishes'+ ],+ [+ { kind: "inherited-delay", predecessorDescription: null },+ 0,+ "Starts after an earlier operation in this job finishes"+ ],+ // Started as early as it could: nothing to explain.+ [{ kind: "no-runway" }, 0, null],+ [{ kind: "outside-processing" }, 0, null]+ ])("notes %j", (cause, waitedMs, expected) => {+ expect(composePlacementNote(cause, waitedMs)).toBe(expected);});- assertEquals(cause, { kind: "machine-wait" });- assertEquals(- composeLateConflict("2026-07-20", "2026-07-17", cause),- "Finishes 2026-07-20 but the job is due 2026-07-17 — waited for the work center to be available"- );});-it("blockers win over own-job queueing and a dominant dep", () => {- const cause = classifyLatePlacement({- waitedMs: HOUR,- wait: {- resource: "operator",- blockers: "queued behind J000009 (1 op)",- ownJobAhead: true- },- dominantDep: { description: "Assembly" }+describe("formatWaitDuration", () => {+ it.each([+ [45 * 60_000, "45m"],+ [14 * HOUR, "14h"],+ [14 * HOUR + 30 * 60_000, "14h 30m"],+ [48 * HOUR, "2d"],+ [51 * HOUR, "2d 3h"]+ ])("formats %i ms as %s", (ms, expected) => {+ expect(formatWaitDuration(ms)).toBe(expected);});- assertEquals(cause.kind, "operator-queue");});-it("waited behind this job's own operations → own-job-queue", () => {- const cause = classifyLatePlacement({- waitedMs: 8 * HOUR,- wait: { resource: "operator", blockers: null, ownJobAhead: true },- dominantDep: null- });- assertEquals(cause, { kind: "own-job-queue" });- assertEquals(- composeLateConflict("2026-07-20", "2026-07-17", cause),- "Finishes 2026-07-20 but the job is due 2026-07-17 — waited for a qualified operator, busy with earlier operations in this job"- );-});+describe("composeBehindTarget", () => {+ function op(+ overrides: Partial<BehindTargetOperation>+ ): BehindTargetOperation {+ return {+ description: "Machining",+ needBy: "2026-07-16",+ projectedCompletionAt: "2026-07-18T14:00:00.000Z",+ ...overrides+ };+ }-it("waited with no blockers and no own ops → operator-wait", () => {- const cause = classifyLatePlacement({- waitedMs: 8 * HOUR,- wait: { resource: "operator", blockers: null, ownJobAhead: false },- dominantDep: null+ it("names the first operation in the given order whose projected day passes its need-by", () => {+ expect(+ composeBehindTarget(+ [+ op({+ description: "Cut Stock",+ needBy: "2026-07-15",+ projectedCompletionAt: "2026-07-15T20:00:00.000Z"+ }),+ op({}),+ op({+ description: "Assembly",+ needBy: "2026-07-17",+ projectedCompletionAt: "2026-07-20T14:00:00.000Z"+ })+ ],+ "UTC"+ )+ ).toBe(+ "First behind target: Machining (due 2026-07-16, projected 2026-07-18)"+ );});- assertEquals(cause, { kind: "operator-wait" });- assertEquals(- composeLateConflict("2026-07-20", "2026-07-17", cause),- "Finishes 2026-07-20 but the job is due 2026-07-17 — waited for a qualified operator to be available"- );-});-it("shift-gap wait (null attribution) still classifies as operator-wait", () => {- const cause = classifyLatePlacement({- waitedMs: 12 * HOUR,- wait: null,- dominantDep: null+ it("compares the factory's business day, not UTC's", () => {+ // 22:00 UTC on the 16th is 03:30 on the 17th in Kolkata.+ expect(+ composeBehindTarget(+ [op({ projectedCompletionAt: "2026-07-16T22:00:00.000Z" })],+ "Asia/Kolkata"+ )+ ).toBe(+ "First behind target: Machining (due 2026-07-16, projected 2026-07-17)"+ );});- assertEquals(cause, { kind: "operator-wait" });-});-it("no wait, dep-dominated → inherited delay naming the predecessor", () => {- const cause = classifyLatePlacement({- waitedMs: 0,- wait: null,- dominantDep: { description: "Battery Test" }- });- assertEquals(cause, {- kind: "inherited-delay",- predecessorDescription: "Battery Test"+ it("skips operations with no need-by or no placement", () => {+ expect(+ composeBehindTarget(+ [+ op({ description: "Cut Stock", needBy: null }),+ op({ description: "Deburr", projectedCompletionAt: null }),+ op({})+ ],+ "UTC"+ )+ ).toBe(+ "First behind target: Machining (due 2026-07-16, projected 2026-07-18)"+ );});- assertEquals(- composeLateConflict("2026-07-20", "2026-07-17", cause),- 'Finishes 2026-07-20 but the job is due 2026-07-17 — starts late because it waits for "Battery Test" earlier in this job; its own work center was free'- );-});--it("inherited delay without a predecessor description stays readable", () => {- assertEquals(- composeLateConflict("2026-07-20", "2026-07-17", {- kind: "inherited-delay",- predecessorDescription: null- }),- "Finishes 2026-07-20 but the job is due 2026-07-17 — starts late because it waits for an earlier operation earlier in this job; its own work center was free"- );-});-it("no wait, no dominant dep → no runway before the due date", () => {- const cause = classifyLatePlacement({- waitedMs: 0,- wait: null,- dominantDep: null+ it.each<[string, BehindTargetOperation[]]>([+ [+ "every operation meets its target",+ [op({ projectedCompletionAt: "2026-07-16T14:00:00.000Z" })]+ ],+ ["the job has no due date", [op({ needBy: null })]],+ ["there are no operations", []]+ ])("returns null when %s", (_, operations) => {+ expect(composeBehindTarget(operations, "UTC")).toBeNull();});- assertEquals(cause, { kind: "no-runway" });- assertEquals(- composeLateConflict("2026-07-20", "2026-07-17", cause),- "Finishes 2026-07-20 but the job is due 2026-07-17 — not enough time remains before the due date"- );-});--it("formatWaitDuration is coarse and human", () => {- assertEquals(formatWaitDuration(45 * 60_000), "45m");- assertEquals(formatWaitDuration(14 * HOUR), "14h");- assertEquals(formatWaitDuration(14 * HOUR + 30 * 60_000), "14h 30m");- assertEquals(formatWaitDuration(51 * HOUR), "2d 3h");- assertEquals(formatWaitDuration(48 * HOUR), "2d");-});--it("placement note: queued behind other jobs", () => {- assertEquals(- composePlacementNote(- { kind: "operator-queue", blockers: "queued behind J000010 (2 ops)" },- 14 * HOUR- ),- "Waited 14h for a qualified operator — queued behind J000010 (2 ops)"- );-});--it("placement note: queued at the work center", () => {- assertEquals(- composePlacementNote(- { kind: "machine-queue", blockers: "queued behind J000009 (1 op)" },- 14 * HOUR- ),- "Waited 14h for the work center — queued behind J000009 (1 op)"- );- assertEquals(- composePlacementNote({ kind: "machine-own-job" }, 8 * HOUR),- "Waited 8h for the work center — busy with earlier operations in this job"- );- assertEquals(- composePlacementNote({ kind: "machine-wait" }, 2 * HOUR),- "Waited 2h for the work center to be available"- );-});--it("placement note: own job ahead / operator wait", () => {- assertEquals(- composePlacementNote({ kind: "own-job-queue" }, 8 * HOUR),- "Waited 8h for a qualified operator — busy with earlier operations in this job"- );- assertEquals(- composePlacementNote({ kind: "operator-wait" }, 90 * 60_000),- "Waited 1h 30m for a qualified operator to be available"- );-});--it("placement note: chained after a predecessor", () => {- assertEquals(- composePlacementNote(- { kind: "inherited-delay", predecessorDescription: "Flash Firmware" },- 0- ),- 'Starts after "Flash Firmware" finishes'- );- assertEquals(- composePlacementNote(- { kind: "inherited-delay", predecessorDescription: null },- 0- ),- "Starts after an earlier operation in this job finishes"- );-});--it("placement note: null when the op started as early as it could", () => {- assertEquals(composePlacementNote({ kind: "no-runway" }, 0), null);- assertEquals(composePlacementNote({ kind: "outside-processing" }, 0), null);-});--it("outside processing message", () => {- assertEquals(- composeLateConflict("2026-07-20", "2026-07-17", {- kind: "outside-processing"- }),- "Finishes 2026-07-20 but the job is due 2026-07-17 — outside processing pushes it past the due date"- );-});--it("people-manned wait classifies and words as the assigned people", () => {- const cause = classifyLatePlacement({- waitedMs: 2 * HOUR,- wait: { resource: "operator", blockers: null, ownJobAhead: false },- dominantDep: null,- staffed: true- });- assertEquals(cause, { kind: "people-wait" });- assertEquals(- composePlacementNote(cause, 2 * HOUR),- "Waited 2h for the assigned people"- );- assertEquals(- composeLateConflict("2026-07-20", "2026-07-17", cause),- "Finishes 2026-07-20 but the job is due 2026-07-17 — waited for the assigned people to be available"- );-});--it("behind target: names the FIRST op past its need-by in the given order", () => {- assertEquals(- composeBehindTarget(- [- {- // On target — projected day equals its need-by.- description: "Cut Stock",- needBy: "2026-07-15",- projectedCompletionAt: "2026-07-15T20:00:00.000Z"- },- {- // First behind target — this one is named.- description: "Machining",- needBy: "2026-07-16",- projectedCompletionAt: "2026-07-18T14:00:00.000Z"- },- {- // Also behind, but later in topological order — never reached.- description: "Assembly",- needBy: "2026-07-17",- projectedCompletionAt: "2026-07-20T14:00:00.000Z"- }- ],- "UTC"- ),- "First behind target: Machining (due 2026-07-16, projected 2026-07-18)"- );-});--it("behind target: projected day is the FACTORY day, not UTC's", () => {- // 03:30 IST on the 17th is 22:00 UTC on the 16th — on target in UTC,- // behind target on the factory calendar.- assertEquals(- composeBehindTarget(- [- {- description: "Machining",- needBy: "2026-07-16",- projectedCompletionAt: "2026-07-16T22:00:00.000Z"- }- ],- "Asia/Kolkata"- ),- "First behind target: Machining (due 2026-07-16, projected 2026-07-17)"- );-});--it("behind target: null when every op meets its target", () => {- assertEquals(- composeBehindTarget(- [- {- description: "Cut Stock",- needBy: "2026-07-15",- projectedCompletionAt: "2026-07-14T20:00:00.000Z"- },- {- description: "Assembly",- needBy: "2026-07-17",- projectedCompletionAt: "2026-07-17T14:00:00.000Z"- }- ],- "UTC"- ),- null- );-});--it("behind target: ops with no need-by (or no placement) are skipped", () => {- // No due date on the job → every need-by is null → nothing to attribute.- assertEquals(- composeBehindTarget(- [- {- description: "Cut Stock",- needBy: null,- projectedCompletionAt: "2026-07-18T14:00:00.000Z"- }- ],- "UTC"- ),- null- );- // A null-needBy op is skipped, not treated as behind; an unplaced op- // (null projection) is skipped too — the next behind-target op is named.- assertEquals(- composeBehindTarget(- [- {- description: "Cut Stock",- needBy: null,- projectedCompletionAt: "2026-07-18T14:00:00.000Z"- },- {- description: "Deburr",- needBy: "2026-07-16",- projectedCompletionAt: null- },- {- description: "Machining",- needBy: "2026-07-16",- projectedCompletionAt: "2026-07-18T14:00:00.000Z"- }- ],- "UTC"- ),- "First behind target: Machining (due 2026-07-16, projected 2026-07-18)"- );- assertEquals(composeBehindTarget([], "UTC"), null);-});--it("behind target: a blank description stays readable", () => {- assertEquals(- composeBehindTarget(- [- {- description: null,- needBy: "2026-07-16",- projectedCompletionAt: "2026-07-18T14:00:00.000Z"- }- ],- "UTC"- ),- "First behind target: an operation (due 2026-07-16, projected 2026-07-18)"- );-});-it("staffed never reclassifies a machine-bound wait", () => {- const cause = classifyLatePlacement({- waitedMs: 2 * HOUR,- wait: { resource: "machine", blockers: null, ownJobAhead: false },- dominantDep: null,- staffed: true+ it("calls an operation with no description 'an operation'", () => {+ expect(composeBehindTarget([op({ description: null })], "UTC")).toBe(+ "First behind target: an operation (due 2026-07-16, projected 2026-07-18)"+ );});- assertEquals(cause, { kind: "machine-wait" });});diff --git a/packages/printing/package.json b/packages/printing/package.jsonindex 28049e3722..98e632c8b1 100644--- a/packages/printing/package.json+++ b/packages/printing/package.json@@ -31,7 +31,7 @@"clean": "rimraf .turbo node_modules dist","dev": "tsup --watch","lint": "biome lint --write ",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"sideEffects": false,"version": "0.0.0"diff --git a/packages/query/package.json b/packages/query/package.jsonindex dbead0c1a6..f8f144e522 100644--- a/packages/query/package.json+++ b/packages/query/package.json@@ -12,10 +12,9 @@"clean": "rimraf .turbo node_modules","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"dependencies": {- "@carbon/database": "workspace:*","@carbon/env": "workspace:*","@carbon/logger": "workspace:*","@carbon/react": "workspace:*",@@ -25,6 +24,7 @@},"devDependencies": {"@carbon/config": "workspace:*",+ "@carbon/database": "workspace:*","@types/react": "catalog:","react": "catalog:","react-router": "catalog:",diff --git a/packages/react/package.json b/packages/react/package.jsonindex 835957818b..8326ab5ca0 100644--- a/packages/react/package.json+++ b/packages/react/package.json@@ -1,18 +1,15 @@{"name": "@carbon/react","dependencies": {- "@carbon/database": "workspace:*",- "@carbon/env": "workspace:*",- "@carbon/files": "workspace:*",+ "@base-ui/react": "1.6.0","@carbon/content": "workspace:*",+ "@carbon/files": "workspace:*","@carbon/logger": "workspace:*","@carbon/tiptap": "workspace:*","@carbon/utils": "workspace:*",- "@base-ui/react": "1.6.0","@dicebear/core": "10.7.0","@dicebear/styles": "10.6.0","@radix-ui/react-accordion": "1.2.12",- "@radix-ui/react-avatar": "1.1.11","@radix-ui/react-checkbox": "1.3.3","@radix-ui/react-collapsible": "1.1.0","@radix-ui/react-context-menu": "2.2.16",@@ -38,15 +35,7 @@"@react-aria/i18n": "catalog:","@react-stately/calendar": "3.9.3","@react-stately/datepicker": "3.16.1",- "@react-types/button": "3.15.1",- "@react-types/calendar": "3.8.3",- "@react-types/datepicker": "3.13.5","@shikijs/langs": "catalog:",- "@shikijs/themes": "catalog:",- "@shikijs/types": "catalog:",- "@supabase/supabase-js": "catalog:",- "@tailwindcss/typography": "catalog:",- "@tanstack/react-table": "8.21.3","@tanstack/react-virtual": "3.13.23","@tiptap/core": "catalog:","@tiptap/extension-color": "catalog:",@@ -57,7 +46,6 @@"@tiptap/extension-table-row": "catalog:","@tiptap/extension-text-style": "catalog:","@tiptap/extension-underline": "catalog:",- "@tiptap/extension-youtube": "catalog:","@tiptap/pm": "catalog:","@tiptap/react": "catalog:","@tiptap/starter-kit": "catalog:",@@ -70,43 +58,54 @@"class-variance-authority": "catalog:","clsx": "2.1.1","cmdk": "0.2.0",- "cookie": "catalog:","dompurify": "catalog:","embla-carousel-react": "8.5.2","input-otp": "1.4.2",- "intl-parse-accept-language": "catalog:",- "is-hotkey": "0.2.0",- "nanoid": "catalog:",+ "match-sorter": "catalog:","nprogress": "0.2.0","react-aria-components": "1.0.1","react-colorful": "5.6.1","react-hotkeys-hook": "catalog:",- "react-resizable-panels": "catalog:","react-shiki": "0.9.2","recharts": "2.15.4","sonner": "2.0.7",- "tailwind-merge": "catalog:",- "tailwindcss-animate": "catalog:",- "zustand": "catalog:",- "match-sorter": "catalog:"+ "tailwind-merge": "catalog:"},"devDependencies": {"@carbon/config": "workspace:*",- "@carbon/utils": "workspace:*",+ "@carbon/database": "workspace:*",+ "@carbon/env": "workspace:*",+ "@radix-ui/react-avatar": "1.1.11",+ "@react-types/button": "3.15.1",+ "@react-types/calendar": "3.8.3",+ "@react-types/datepicker": "3.13.5",+ "@shikijs/themes": "catalog:",+ "@shikijs/types": "catalog:",+ "@supabase/supabase-js": "catalog:",+ "@tailwindcss/typography": "catalog:",+ "@tanstack/react-table": "8.21.3","@testing-library/dom": "8.20.1",+ "@tiptap/extension-youtube": "catalog:","@types/dompurify": "2.4.0","@types/forge-viewer": "7.99.3","@types/nprogress": "0.2.3","@types/react": "catalog:","@types/react-dom": "catalog:","@types/react-window": "1.8.8",+ "cookie": "catalog:",+ "intl-parse-accept-language": "catalog:",+ "is-hotkey": "0.2.0","jsdom": "26.1.0",+ "nanoid": "catalog:","react": "catalog:",+ "react-resizable-panels": "catalog:","sst": "catalog:","tailwindcss": "catalog:",+ "tailwindcss-animate": "catalog:","tsup": "catalog:","typescript": "catalog:",- "vitest": "catalog:"+ "vitest": "catalog:",+ "zustand": "catalog:"},"exports": {".": "./src/index.tsx",@@ -135,7 +134,7 @@"clean": "rimraf .turbo node_modules","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"sideEffects": false,"version": "0.0.0"diff --git a/packages/react/src/__tests__/Number.test.tsx b/packages/react/src/__tests__/Number.test.tsxindex f9321c3ae5..1fcdf40bbd 100644--- a/packages/react/src/__tests__/Number.test.tsx+++ b/packages/react/src/__tests__/Number.test.tsx@@ -3,109 +3,68 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source./**- * Tests for NumberInput — ensures the prop-spreading bug is fixed so that- * isReadOnly and isDisabled are not overridden by the rest-props spread.- *- * Uses react-dom/server renderToStaticMarkup (no DOM / jsdom required) to- * assert the rendered HTML attributes.- *- * Note: `disabled` also appears in Tailwind class names like `disabled:opacity-50`.- * We check for the HTML attribute form `disabled=""` to avoid false positives.+ * NumberInput used to spread its rest props after `isReadOnly={isDisabled ||+ * isReadOnly}`, so an explicit `isReadOnly={false}` unlocked a disabled field.+ * Rendered with react-dom/server (the vitest env has no DOM).*/+import type { ComponentProps } from "react";import { renderToStaticMarkup } from "react-dom/server";import { describe, expect, it, vi } from "vitest";import { areNumberFormatOptionsEqual, NumberInput } from "../Number";-/**- * The `onFocus` behavior ([4] focus-select) is an inline closure on the real- * NumberInput. The vitest env is `node` (no jsdom), so we exercise the actual- * component's render output via forwardRef's `.render` — no reimplementation —- * and invoke the handler it wires onto the underlying Input with a stub event.- */-type FocusableElement = { props: { onFocus?: (e: unknown) => void } };-function getRenderedOnFocus(props: Record<string, unknown>) {- // forwardRef components expose the render fn; call it to get the element tree.- const rendered = (- NumberInput as unknown as {- render: (p: Record<string, unknown>, ref: unknown) => FocusableElement;- }- ).render(props, null);- return rendered.props.onFocus;-}--/** Returns the first <input> element's attribute string from rendered HTML */-function getInputAttrs(html: string): string {- const match = html.match(/<input([^>]*)>/);- return match?.[1] ?? "";+// `disabled` also appears in Tailwind classes (`disabled:opacity-50`), so read+// the attribute form off the <input> only.+function inputLock(props: ComponentProps<typeof NumberInput>) {+ const attrs =+ renderToStaticMarkup(<NumberInput {...props} />).match(+ /<input([^>]*)>/+ )?.[1] ?? "";+ return {+ readonly: /\breadonly=""/i.test(attrs),+ disabled: /\bdisabled=""/i.test(attrs)+ };}describe("NumberInput", () => {- it("has no readonly attribute by default (allows typing for non-serial items)", () => {- const attrs = getInputAttrs(renderToStaticMarkup(<NumberInput />));- // HTML readonly attr is rendered as readonly="" by React- expect(attrs).not.toMatch(/\breadonly=""/i);- });-- it("has no readonly attribute when isReadOnly=false and isDisabled=false", () => {- // Key regression guard: before the fix, {…props} spread would re-introduce- // isReadOnly=false AFTER the explicit isReadOnly={isDisabled || isReadOnly},- // but this case (both false) was unaffected — confirms the happy path still works.- const attrs = getInputAttrs(- renderToStaticMarkup(- <NumberInput isReadOnly={false} isDisabled={false} />- )- );- expect(attrs).not.toMatch(/\breadonly=""/i);- expect(attrs).not.toMatch(/\bdisabled=""/i);+ it.each<+ [+ ComponentProps<typeof NumberInput>,+ { readonly: boolean; disabled: boolean }+ ]+ >([+ [{}, { readonly: false, disabled: false }],+ [+ { isReadOnly: false, isDisabled: false },+ { readonly: false, disabled: false }+ ],+ [{ isReadOnly: true }, { readonly: true, disabled: false }],+ [{ isDisabled: true }, { readonly: true, disabled: true }],+ [+ { isDisabled: true, isReadOnly: false },+ { readonly: true, disabled: true }+ ]+ ])("locks the input for %j as %j", (props, expected) => {+ expect(inputLock(props)).toEqual(expected);});- it("has readonly attribute when isReadOnly=true (serial-tracked lock preserved)", () => {- const attrs = getInputAttrs(- renderToStaticMarkup(<NumberInput isReadOnly />)- );- expect(attrs).toMatch(/\breadonly=""/i);- });-- it("has disabled attribute when isDisabled=true", () => {- const attrs = getInputAttrs(- renderToStaticMarkup(<NumberInput isDisabled />)- );- expect(attrs).toMatch(/\bdisabled=""/i);- });-- it("has disabled attribute when isDisabled=true even if isReadOnly=false (regression guard)", () => {- // Before the fix: {…props} spread would override isReadOnly={true || false}- // with isReadOnly=false — this test would have caught that bug.- const attrs = getInputAttrs(- renderToStaticMarkup(<NumberInput isDisabled={true} isReadOnly={false} />)- );- // A disabled input carries disabled="" — not editable regardless- expect(attrs).toMatch(/\bdisabled=""/i);- });-- describe("focus behavior ([4] field selects on focus for quick overwrite)", () => {- it("selects the input's contents on focus", () => {- const select = vi.fn();- getRenderedOnFocus({})?.({ target: { select } });- expect(select).toHaveBeenCalledTimes(1);- });-- it("forwards the focus event to a caller-supplied onFocus (tab/focus unbroken)", () => {- const onFocus = vi.fn();- const select = vi.fn();- const event = { target: { select } };- getRenderedOnFocus({ onFocus })?.(event);- expect(select).toHaveBeenCalledTimes(1);- expect(onFocus).toHaveBeenCalledTimes(1);- expect(onFocus).toHaveBeenCalledWith(event);- });-- it("does not throw when no onFocus is provided", () => {- expect(() =>- getRenderedOnFocus({})?.({ target: { select: vi.fn() } })- ).not.toThrow();- });+ it("selects the contents on focus and still calls the caller's onFocus", () => {+ // The vitest env has no DOM, so call the forwardRef render directly.+ const onFocus = vi.fn();+ const select = vi.fn();+ const event = { target: { select } };+ (+ NumberInput as unknown as {+ render: (+ p: Record<string, unknown>,+ ref: unknown+ ) => { props: { onFocus: (e: unknown) => void } };+ }+ )+ .render({ onFocus }, null)+ .props.onFocus(event);+ expect(select).toHaveBeenCalledTimes(1);+ expect(onFocus).toHaveBeenCalledWith(event);});});diff --git a/packages/react/src/__tests__/generatedAvatar.test.ts b/packages/react/src/__tests__/generatedAvatar.test.tsindex 8f70907976..e36c298bdb 100644--- a/packages/react/src/__tests__/generatedAvatar.test.ts+++ b/packages/react/src/__tests__/generatedAvatar.test.ts@@ -2,7 +2,6 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { readFileSync } from "node:fs";import { GENERATED_AVATAR_STYLES } from "@carbon/utils";import { describe, expect, it, vi } from "vitest";import {@@ -10,7 +9,6 @@ import {isDarkBackground,loadGeneratedAvatarStyle} from "../utils/generatedAvatar";-import { generatedAvatarClassName } from "../utils/generatedAvatarImage";const svgOf = (uri: string | undefined) =>decodeURIComponent((uri ?? "").replace(/^data:image\/svg\+xml;[^,]*,/, ""));@@ -81,59 +79,13 @@ describe("generatedAvatarDataUri", () => {expect(light).not.toContain("#ffffff");});- it("classifies backgrounds by contrast", () => {- expect(isDarkBackground("000000")).toBe(true);- expect(isDarkBackground("1e3a8a")).toBe(true);- expect(isDarkBackground("ffffff")).toBe(false);- expect(isDarkBackground("ffd5dc")).toBe(false);+ it.each([+ ["000000", true],+ ["1e3a8a", true],+ ["ffffff", false],+ ["ffd5dc", false]+ ])("classifies #%s as dark: %s", (hex, dark) => {+ expect(isDarkBackground(hex)).toBe(dark);});});-- describe("generatedAvatarClassName", () => {- it("puts line-art styles on white in both themes", () => {- for (const style of [- "croodles-neutral",- "notionists",- "notionists-neutral",- "lorelei",- "lorelei-neutral"- ] as const) {- expect(generatedAvatarClassName(style)).toBe(- "bg-white border-black/10"- );- }- });-- it("leaves color styles on the muted background, never inverted", () => {- for (const style of [- "loops",- "pixel-art",- "voxel-art",- "voxel-bot",- "planets"- ] as const) {- const className = generatedAvatarClassName(style);- expect(className).toBe("bg-muted border-transparent");- expect(className).not.toContain("invert");- }- });- });-- it("never passes import attributes to a style's import()", () => {- // `import(x, { with: { type: "json" } })` makes the server route work but- // the browser rejects it — Vite serves the JSON as JavaScript — and every- // picker preview stayed grey. The server bundles @dicebear/styles instead- // (`ssrNoExternal` in each app's vite.config.ts). See .ai/lessons.md.- const source = readFileSync(- new URL("../utils/generatedAvatar.ts", import.meta.url),- "utf8"- );- const styleImports = source.match(- /import\(\s*["']@dicebear\/styles\/[^)]*\)/g- );- expect(styleImports).toHaveLength(10);- for (const call of styleImports ?? []) {- expect(call).toMatch(/^import\(\s*["'][^"']+["']\s*\)$/);- }- });});diff --git a/packages/serve/package.json b/packages/serve/package.jsonindex 6d17be728c..2036bc19ab 100644--- a/packages/serve/package.json+++ b/packages/serve/package.json@@ -24,7 +24,7 @@"clean": "rimraf .turbo node_modules dist","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"sideEffects": false,"type": "module"diff --git a/packages/stripe/AGENTS.md b/packages/stripe/AGENTS.mdindex 629987ac05..db35924de8 100644--- a/packages/stripe/AGENTS.md+++ b/packages/stripe/AGENTS.md@@ -24,7 +24,7 @@ Stripe billing integration — checkout, subscriptions, webhooks, and customer s## Validation Commands```bash-pnpm --filter @carbon/stripe typecheck # tsgo --noEmit+pnpm --filter @carbon/stripe typecheck # tsc --noEmitpnpm --filter @carbon/stripe dev:stripe # local Stripe listener (dev)```diff --git a/packages/stripe/package.json b/packages/stripe/package.jsonindex c630a9602b..9dbb0df430 100644--- a/packages/stripe/package.json+++ b/packages/stripe/package.json@@ -10,20 +10,20 @@"@carbon/logger": "workspace:*","@carbon/utils": "workspace:*","@internationalized/date": "catalog:",- "@supabase/supabase-js": "catalog:",- "stripe": "22.4.0"+ "dotenv": "16.3.1",+ "stripe": "22.4.0",+ "zod": "catalog:"},"type": "module","devDependencies": {"@carbon/config": "workspace:*",+ "@supabase/supabase-js": "catalog:","@types/node": "20.19.39",- "dotenv": "16.3.1","rimraf": "catalog:","sst": "catalog:","tsup": "catalog:","tsx": "catalog:",- "typescript": "catalog:",- "zod": "catalog:"+ "typescript": "catalog:"},"exports": {"./stripe.server": "./src/stripe.server.ts",@@ -39,7 +39,7 @@"lint": "biome lint --write ","dev:stripe": "tsx ./stripe.dev.ts","register:stripe": "tsx ./stripe.register.ts",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"sideEffects": false,"version": "0.0.0"diff --git a/packages/tiptap/package.json b/packages/tiptap/package.jsonindex b27411811a..f286e5b4a9 100644--- a/packages/tiptap/package.json+++ b/packages/tiptap/package.json@@ -11,7 +11,6 @@"@tiptap/extension-horizontal-rule": "2.27.2","@tiptap/extension-image": "2.27.2","@tiptap/extension-link": "2.27.2",- "@tiptap/extension-mention": "2.27.2","@tiptap/extension-placeholder": "2.27.2","@tiptap/extension-task-item": "2.27.2","@tiptap/extension-task-list": "2.27.2",@@ -22,12 +21,7 @@"@tiptap/react": "catalog:","@tiptap/starter-kit": "catalog:","@tiptap/suggestion": "2.27.2",- "@types/node": "22.19.7","cmdk": "0.2.0",- "cookie": "catalog:",- "dompurify": "catalog:",- "linkifyjs": "4.3.2",- "nanoid": "catalog:","react-moveable": "0.56.0","tippy.js": "6.3.7","tiptap-extension-global-drag-handle": "0.1.18",@@ -39,11 +33,17 @@"@carbon/config": "workspace:*","@carbon/utils": "workspace:*","@testing-library/dom": "8.20.1",+ "@tiptap/extension-mention": "2.27.2","@types/dompurify": "2.4.0","@types/forge-viewer": "7.99.3",+ "@types/node": "22.19.7","@types/react": "catalog:","@types/react-dom": "catalog:","@types/react-window": "1.8.8",+ "cookie": "catalog:",+ "dompurify": "catalog:",+ "linkifyjs": "4.3.2",+ "nanoid": "catalog:","react": "catalog:","sst": "catalog:","tsup": "catalog:",@@ -63,7 +63,7 @@"clean": "rimraf .turbo node_modules","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"sideEffects": false,"version": "0.0.0"diff --git a/packages/utils/package.json b/packages/utils/package.jsonindex 31bbfaf75e..96f85f1946 100644--- a/packages/utils/package.json+++ b/packages/utils/package.json@@ -3,21 +3,21 @@"dependencies": {"@carbon/database": "workspace:*","@internationalized/date": "catalog:",- "@supabase/supabase-js": "catalog:",- "@tiptap/react": "catalog:","cookie": "catalog:",- "dompurify": "catalog:",+ "humanize-duration": "3.35.0","intl-parse-accept-language": "catalog:","lodash.template": "4.18.1",- "nanoid": "catalog:","zod": "catalog:"},"devDependencies": {"@carbon/config": "workspace:*",+ "@supabase/supabase-js": "catalog:",+ "@tiptap/react": "catalog:","@types/lodash.template": "4.5.3","@types/react": "catalog:","@types/react-dom": "catalog:",- "humanize-duration": "3.35.0",+ "dompurify": "catalog:",+ "nanoid": "catalog:","react": "catalog:","sst": "catalog:","tsup": "catalog:",@@ -35,7 +35,7 @@"dev": "tsup src/index.ts --format esm,cjs --watch --dts --external react","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"sideEffects": false,"version": "0.0.0"diff --git a/packages/utils/src/batch-time-split.test.ts b/packages/utils/src/batch-time-split.test.tsindex e7d66f8475..e14de896eb 100644--- a/packages/utils/src/batch-time-split.test.ts+++ b/packages/utils/src/batch-time-split.test.ts@@ -58,33 +58,44 @@ describe("splitSecondsByWeight", () => {});describe("sliceEventByWeight", () => {- it("produces contiguous windows that tile the recorded span", () => {- const windows = sliceEventByWeight(+ it("tiles the recorded span with contiguous windows in proportion to weight", () => {+ expect(+ sliceEventByWeight(+ {+ startTime: "2026-07-14T00:00:00.000Z",+ endTime: "2026-07-14T01:10:00.000Z"+ },+ [+ { id: "a", weight: 5 },+ { id: "b", weight: 20 },+ { id: "c", weight: 10 }+ ]+ )+ ).toEqual([{+ id: "a",startTime: "2026-07-14T00:00:00.000Z",- endTime: "2026-07-14T01:10:00.000Z"+ endTime: "2026-07-14T00:10:00.000Z",+ durationSeconds: 600},- [- { id: "a", weight: 5 },- { id: "b", weight: 20 },- { id: "c", weight: 10 }- ]- );- const [a, b, c] = windows;- // Durations follow the proportional split.- expect(windows.map((w) => w.durationSeconds)).toEqual([600, 2400, 1200]);- // Windows are contiguous: each starts where the previous ended.- expect(a!.startTime).toBe("2026-07-14T00:00:00.000Z");- expect(a!.endTime).toBe(b!.startTime);- expect(b!.endTime).toBe(c!.startTime);- // Last window closes out the parent span exactly.- expect(c!.endTime).toBe("2026-07-14T01:10:00.000Z");+ {+ id: "b",+ startTime: "2026-07-14T00:10:00.000Z",+ endTime: "2026-07-14T00:50:00.000Z",+ durationSeconds: 2400+ },+ {+ id: "c",+ startTime: "2026-07-14T00:50:00.000Z",+ endTime: "2026-07-14T01:10:00.000Z",+ durationSeconds: 1200+ }+ ]);});});describe("buildBatchCompletionPlan", () => {- // The AC[6] scenario: members with qty 5/20/10, one 70-minute machine event,- // scrap entered only on the middle member.+ // Members with qty 5/20/10, one 70-minute machine event, scrap only on the middle one.const members = [{ jobOperationId: "op-a", operationQuantity: 5, quantity: 5 },{@@ -99,58 +110,59 @@ describe("buildBatchCompletionPlan", () => {id: "evt-1",type: "Machine",startTime: "2026-07-14T00:00:00.000Z",- endTime: "2026-07-14T01:10:00.000Z", // 70 minutes+ endTime: "2026-07-14T01:10:00.000Z",+ workCenterId: "wc-1",+ employeeId: "emp-1"+ };+ const slice = {+ sourceEventId: "evt-1",+ type: "Machine",workCenterId: "wc-1",employeeId: "emp-1"};- it("slices the 70-minute event into 10/40/20-minute per-member events", () => {- const plan = buildBatchCompletionPlan([machineEvent], members);-- expect(plan.memberEvents.map((e) => e.durationSeconds)).toEqual([- 10 * 60,- 40 * 60,- 20 * 60- ]);- // Each slice keeps its own member + the source event's metadata.- expect(plan.memberEvents.map((e) => e.jobOperationId)).toEqual([- "op-a",- "op-b",- "op-c"+ it("slices each event into one per-member event carrying the source's metadata", () => {+ expect(+ buildBatchCompletionPlan([machineEvent], members).memberEvents+ ).toEqual([+ {+ ...slice,+ jobOperationId: "op-a",+ startTime: "2026-07-14T00:00:00.000Z",+ endTime: "2026-07-14T00:10:00.000Z",+ durationSeconds: 600+ },+ {+ ...slice,+ jobOperationId: "op-b",+ startTime: "2026-07-14T00:10:00.000Z",+ endTime: "2026-07-14T00:50:00.000Z",+ durationSeconds: 2400+ },+ {+ ...slice,+ jobOperationId: "op-c",+ startTime: "2026-07-14T00:50:00.000Z",+ endTime: "2026-07-14T01:10:00.000Z",+ durationSeconds: 1200+ }]);- expect(plan.memberEvents.every((e) => e.type === "Machine")).toBe(true);- expect(plan.memberEvents.every((e) => e.sourceEventId === "evt-1")).toBe(- true- );- expect(plan.memberEvents.every((e) => e.workCenterId === "wc-1")).toBe(- true- );-- // Windows are contiguous and tile the parent span exactly.- const [a, b, c] = plan.memberEvents;- expect(a!.startTime).toBe("2026-07-14T00:00:00.000Z");- expect(a!.endTime).toBe(b!.startTime);- expect(b!.endTime).toBe(c!.startTime);- expect(c!.endTime).toBe("2026-07-14T01:10:00.000Z");});- it("emits a Production row per member and a Scrap row only where entered", () => {- const plan = buildBatchCompletionPlan([machineEvent], members);-- expect(plan.quantities).toEqual([+ it("emits a Production row per member and a Scrap row only where entered, with or without events", () => {+ const quantities = [{ jobOperationId: "op-a", type: "Production", quantity: 5 },{ jobOperationId: "op-b", type: "Production", quantity: 20 },{ jobOperationId: "op-b", type: "Scrap", quantity: 2 },{ jobOperationId: "op-c", type: "Production", quantity: 10 }- ]);- });-- it("handles a batch with no recorded events (quantities still produced)", () => {- const plan = buildBatchCompletionPlan([], members);- expect(plan.memberEvents).toEqual([]);- expect(plan.quantities.filter((q) => q.type === "Production")).toHaveLength(- 3- );+ ];+ expect(+ buildBatchCompletionPlan([machineEvent], members).quantities+ ).toEqual(quantities);+ expect(buildBatchCompletionPlan([], members)).toEqual({+ memberEvents: [],+ quantities+ });});});@@ -207,64 +219,36 @@ describe("assertAllOperationsClaimed", () => {});describe("assertBatchWorkCenterMutable", () => {- it("allows changing the work center of a Planned batch", () => {- // Planned is the staged, pre-release state — nothing has run, so the- // work center is still freely assignable.- expect(() => assertBatchWorkCenterMutable("Planned")).not.toThrow();- });-- it("allows changing the work center of an Active batch", () => {- expect(() => assertBatchWorkCenterMutable("Active")).not.toThrow();- });-- it("rejects changing the work center of a Completing batch", () => {- expect(() => assertBatchWorkCenterMutable("Completing")).toThrow(- /not active/- );- });-- it("rejects changing the work center of a Completed batch", () => {- expect(() => assertBatchWorkCenterMutable("Completed")).toThrow(- /not active/- );- });-- it("rejects changing the work center of a Cancelled batch", () => {- expect(() => assertBatchWorkCenterMutable("Cancelled")).toThrow(- /not active/- );- });+ it.each(["Planned", "Active"] as const)(+ "allows changing the work center of a %s batch",+ (status) => {+ expect(() => assertBatchWorkCenterMutable(status)).not.toThrow();+ }+ );++ it.each(["Completing", "Completed", "Cancelled"] as const)(+ "refuses changing the work center of a %s batch",+ (status) => {+ expect(() => assertBatchWorkCenterMutable(status)).toThrow(/not active/);+ }+ );});describe("planBatchCompletion", () => {- it("rejects a Planned batch (must be released first)", () => {- // A Planned batch has never been released to the floor — nothing has run- // against it, so there is nothing to complete.- expect(() => planBatchCompletion("Planned")).toThrow(- /Only an active batch can be completed/- );- });-- it("slices on the first attempt (Active batch)", () => {+ it("slices an Active batch", () => {expect(planBatchCompletion("Active")).toBe("slice");});- it("resumes an in-flight completion (Completing batch)", () => {- // The two-phase flow: a prior attempt committed the timer slice + flipped the- // batch to 'Completing', then a post-commit step (issue / Done / GL) failed.- // A retry must RESUME the idempotent post-commit steps, never re-slice.+ it("resumes a Completing batch rather than slicing it again", () => {+ // A prior attempt committed the slice; a post-commit step failed.expect(planBatchCompletion("Completing")).toBe("resume");});- it("rejects an already-completed batch", () => {- expect(() => planBatchCompletion("Completed")).toThrow(- /already been completed/- );- });-- it("rejects a cancelled batch", () => {- expect(() => planBatchCompletion("Cancelled")).toThrow(- /Only an active batch can be completed/- );+ it.each([+ ["Planned", /Only an active batch can be completed/],+ ["Cancelled", /Only an active batch can be completed/],+ ["Completed", /already been completed/]+ ] as const)("refuses to complete a %s batch", (status, error) => {+ expect(() => planBatchCompletion(status)).toThrow(error);});});diff --git a/packages/utils/src/status-colors.test.ts b/packages/utils/src/status-colors.test.tsdeleted file mode 100644index d4387fa5a5..0000000000--- a/packages/utils/src/status-colors.test.ts+++ /dev/null@@ -1,28 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { describe, expect, it } from "vitest";-import { statusColorMaps } from "./status-colors";--const maps = statusColorMaps as Record<string, Record<string, string>>;--describe("return order status colors", () => {- it("matches the RMA status badges", () => {- expect(maps.salesReturnOrder).toEqual({- Draft: "gray",- "To Receive": "blue",- Completed: "green",- Cancelled: "red"- });- });-- it("matches the supplier return status badges", () => {- expect(maps.purchaseReturnOrder).toEqual({- Draft: "gray",- "To Ship": "blue",- Completed: "green",- Cancelled: "red"- });- });-});diff --git a/packages/viewer/AGENTS.md b/packages/viewer/AGENTS.mdindex 769557384a..ba0d7d6c8f 100644--- a/packages/viewer/AGENTS.md+++ b/packages/viewer/AGENTS.md@@ -37,7 +37,7 @@```bashpnpm --filter @carbon/viewer test # vitest — camera, clip, display, fallback, graph, keyframes, orientation, path-editing, plan, quat, step-flags, subassembly, timing, validate-motion, visibility (shared helpers: src/test-utils.ts)-pnpm --filter @carbon/viewer typecheck # tsgo --noEmit+pnpm --filter @carbon/viewer typecheck # tsc --noEmit```## Key Exportsdiff --git a/packages/viewer/package.json b/packages/viewer/package.jsonindex d052504675..b9efadb620 100644--- a/packages/viewer/package.json+++ b/packages/viewer/package.json@@ -41,7 +41,7 @@"clean": "rimraf .turbo node_modules","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"sideEffects": false,"version": "0.0.0"diff --git a/packages/viewer/src/visibility.test.ts b/packages/viewer/src/visibility.test.tsindex 14cbeec9dc..7fce974ac0 100644--- a/packages/viewer/src/visibility.test.ts+++ b/packages/viewer/src/visibility.test.ts@@ -14,7 +14,7 @@ import {} from "./visibility";describe("visualForComponent", () => {- it("shows earlier-step components solid", () => {+ it("shows earlier-step components solid when no installed mode is given", () => {expect(visualForComponent(0, 2, "ghost")).toBe("solid");expect(visualForComponent(1, 2, "hidden")).toBe("solid");});@@ -47,35 +47,29 @@ describe("visualForComponent", () => {expect(visualForComponent(undefined, 10, "ghost")).toBe("ghost");});- it("defaults installed components to solid when the 4th arg is omitted", () => {- expect(visualForComponent(0, 2, "ghost")).toBe("solid");- expect(visualForComponent(1, 2, "hidden")).toBe("solid");- });-it("renders installed components per the installed mode", () => {expect(visualForComponent(0, 2, "ghost", "solid")).toBe("solid");expect(visualForComponent(0, 2, "ghost", "ghost")).toBe("ghost");expect(visualForComponent(0, 2, "ghost", "hidden")).toBe("hidden");});- it("never lets the installed mode affect the active step", () => {- for (const mode of ["solid", "ghost", "hidden"] as const) {- expect(visualForComponent(2, 2, "ghost", mode)).toBe("active");- }- });-- it("never lets the installed mode affect future components", () => {- expect(visualForComponent(3, 1, "ghost", "hidden")).toBe("ghost");- expect(visualForComponent(3, 1, "hidden", "ghost")).toBe("hidden");- expect(visualForComponent(3, 1, "solid", "hidden")).toBe("solid");- });-- it("never lets the installed mode affect never-installed components", () => {- for (const mode of ["solid", "ghost", "hidden"] as const) {- expect(visualForComponent(undefined, 5, "hidden", mode)).toBe("hidden");- expect(visualForComponent(undefined, 5, "ghost", mode)).toBe("ghost");+ it.each([+ ["the active step", 2, 2, "ghost", "active"],+ ["a future component", 3, 1, "ghost", "ghost"],+ ["a future component", 3, 1, "hidden", "hidden"],+ ["a future component", 3, 1, "solid", "solid"],+ ["a never-installed component", undefined, 5, "hidden", "hidden"],+ ["a never-installed component", undefined, 5, "ghost", "ghost"]+ ] as const)(+ "never lets the installed mode change %s (step %s of %s, future %s)",+ (_, stepIndex, activeStep, futureMode, expected) => {+ for (const installed of ["solid", "ghost", "hidden"] as const) {+ expect(+ visualForComponent(stepIndex, activeStep, futureMode, installed)+ ).toBe(expected);+ }}- });+ );});describe("occluderWeight", () => {@@ -148,53 +142,14 @@ describe("occluderWeight", () => {});describe("named views", () => {- it("names every view in VIEW_MODES", () => {- for (const view of ASSEMBLY_VIEWS) {- expect(VIEW_MODES[view]).toBeDefined();- }- expect(Object.keys(VIEW_MODES).sort()).toEqual([...ASSEMBLY_VIEWS].sort());- });-- it("gives each view a distinct axis pair", () => {- const pairs = ASSEMBLY_VIEWS.map(- (view) =>- `${VIEW_MODES[view].installedMode}/${VIEW_MODES[view].futureMode}`- );- expect(new Set(pairs).size).toBe(pairs.length);- });-- it("keeps 'build' the historical default (installed solid, future hidden)", () => {- // Three-argument callers rendered installed parts solid, and- // `defaultFutureMode` is "hidden" — so the default view must be a no-op.+ it("keeps 'build' a no-op for callers that pass no installed mode", () => {+ // Those callers render installed parts solid and default the future to hidden.expect(VIEW_MODES.build).toEqual({installedMode: "solid",futureMode: "hidden"});});- it("ghosts the built side in 'focus', keeping the future out of the way", () => {- expect(VIEW_MODES.focus).toEqual({- installedMode: "ghost",- futureMode: "hidden"- });- });-- it("hides the future side in every working view", () => {- // Build and Focus are "I am working this step" views; parts that are not- // on the bench yet only add clutter. Full is the exception.- for (const view of ["build", "focus"] as const) {- expect(VIEW_MODES[view].futureMode).toBe("hidden");- }- expect(VIEW_MODES.full.futureMode).toBe("solid");- });-- it("shows everything in 'full'", () => {- expect(VIEW_MODES.full).toEqual({- installedMode: "solid",- futureMode: "solid"- });- });-it("round-trips every view through viewForModes", () => {for (const view of ASSEMBLY_VIEWS) {const { installedMode, futureMode } = VIEW_MODES[view];@@ -202,26 +157,17 @@ describe("named views", () => {}});- it("falls back to 'build' for an axis pair no view names", () => {- // "hidden installed + solid future" is reachable from the props but is not- // a named view; it must seat a real button rather than none.- expect(viewForModes("hidden", "solid")).toBe("build");- // Nor is "hidden installed + hidden future" since the Isolate view went.- expect(viewForModes("hidden", "hidden")).toBe("build");- });-- it("renders the active step untouched in every view", () => {- for (const view of ASSEMBLY_VIEWS) {- const { installedMode, futureMode } = VIEW_MODES[view];- expect(visualForComponent(2, 2, futureMode, installedMode)).toBe(- "active"- );+ it.each([+ ["hidden", "solid"],+ ["hidden", "hidden"]+ ] as const)(+ "falls back to 'build' for the unnamed pair installed %s / future %s",+ (installed, future) => {+ expect(viewForModes(installed, future)).toBe("build");}- });+ );- it("ghosts rather than deletes the built side in 'focus'", () => {- // Focus is about seeing PAST what is already fitted while keeping its- // shape as context.+ it("ghosts the built side in 'focus' and still counts it as a weak occluder", () => {const { installedMode, futureMode } = VIEW_MODES.focus;expect(visualForComponent(0, 2, futureMode, installedMode)).toBe("ghost");expect(occluderWeight(0, 2, futureMode, installedMode)).toBe(diff --git a/packages/viewer/src/vite-env.d.ts b/packages/viewer/src/vite-env.d.tsindex 144b0072fc..fe2c011b3e 100644--- a/packages/viewer/src/vite-env.d.ts+++ b/packages/viewer/src/vite-env.d.ts@@ -4,7 +4,7 @@// This package ships raw source compiled by the consuming app's Vite build.// Type the Vite-injected globals the source references without depending on-// vite (typecheck runs standalone via tsgo).+// vite (typecheck runs standalone via tsc).declare module "*.wasm?url" {const url: string;export default url;diff --git a/packages/workflows-core/package.json b/packages/workflows-core/package.jsonindex c443324c70..51083272f6 100644--- a/packages/workflows-core/package.json+++ b/packages/workflows-core/package.json@@ -11,7 +11,7 @@"clean": "rimraf .turbo node_modules","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsc --noEmit"},"dependencies": {"zod": "catalog:"diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 97c78cee7b..05c34e9dd5 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -198,9 +198,6 @@ catalogs:'@types/node':specifier: '24'version: 24.12.2- '@typescript/native-preview':- specifier: 7.0.0-dev.20260703.1- version: 7.0.0-dev.20260703.1'@vercel/analytics':specifier: 1.6.1version: 1.6.1@@ -325,8 +322,8 @@ catalogs:specifier: 4.21.0version: 4.21.0typescript:- specifier: 5.8.3- version: 5.8.3+ specifier: 7.1.0-beta+ version: 7.1.0-betavite:specifier: 8.3.3version: 8.3.3@@ -413,92 +410,88 @@ patchedDependencies:importers:.:- dependencies:- '@carbon/api':- specifier: workspace:*- version: link:packages/api- '@opentelemetry/semantic-conventions':- specifier: 1.40.0- version: 1.40.0- '@react-router/remix-routes-option-adapter':- specifier: 'catalog:'- version: 7.18.4(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])- cookie:- specifier: 'catalog:'- version: 1.1.1- dompurify:- specifier: 'catalog:'- version: 3.4.17- fast-uri:- specifier: 3.1.8- version: 3.1.8- fdir:- specifier: 6.5.0- version: 6.5.0([email protected])- nanoid:- specifier: 'catalog:'- version: 5.1.16- react-pdf:- specifier: 'catalog:'- version: 10.4.1(@types/[email protected])([email protected]([email protected]))([email protected])- remix-flat-routes:- specifier: 'catalog:'- version: 0.8.5- sst:- specifier: 'catalog:'- version: 4.6.9- tsup:- specifier: 'catalog:'- version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])devDependencies:'@biomejs/biome':specifier: 2.5.15version: 2.5.15+ '@carbon/api':+ specifier: workspace:*+ version: link:packages/api'@lingui/cli':specifier: 'catalog:'+ '@opentelemetry/semantic-conventions':+ specifier: 1.40.0+ version: 1.40.0'@react-router/dev':specifier: 'catalog:'- version: 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ '@react-router/remix-routes-option-adapter':+ specifier: 'catalog:'+ version: 7.18.4(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])'@types/aws-lambda':specifier: 8.10.164version: 8.10.164'@types/node':specifier: 'catalog:'version: 24.12.2- '@typescript/native-preview':- specifier: 'catalog:'- version: 7.0.0-dev.20260703.1cli-table3:specifier: ^0.6.5version: 0.6.5+ cookie:+ specifier: 'catalog:'+ version: 1.1.1csv-parse:specifier: 5.6.0version: 5.6.0+ dompurify:+ specifier: 'catalog:'+ version: 3.4.17execa:specifier: ^8.0.1version: 8.0.1+ fast-uri:+ specifier: 3.1.8+ version: 3.1.8+ fdir:+ specifier: 6.5.0+ version: 6.5.0([email protected])linguito:specifier: ^0.5.2lint-staged:specifier: 16.4.0version: 16.4.0+ nanoid:+ specifier: 'catalog:'+ version: 5.1.16npm-run-all:specifier: 'catalog:'version: 4.1.5+ react-pdf:+ specifier: 'catalog:'+ version: 10.4.1(@types/[email protected])([email protected]([email protected]))([email protected])+ remix-flat-routes:+ specifier: 'catalog:'+ version: 0.8.5rimraf:specifier: 'catalog:'version: 5.0.10simple-git-hooks:specifier: 2.14.0version: 2.14.0+ sst:+ specifier: 'catalog:'+ version: 4.6.9supabase:specifier: 'catalog:'version: 2.89.0(patch_hash=f278052dbb83b89896a8f742e486a879c8f00b1b22e188717aeb199b1f1a4b4c)ts-morph:specifier: 28.0.0version: 28.0.0+ tsup:+ specifier: 'catalog:'+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])tsx:specifier: 'catalog:'version: 4.21.0@@ -507,7 +500,7 @@ importers:version: 2.11.7typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavite:specifier: 'catalog:'version: 8.3.3(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])@@ -559,10 +552,10 @@ importers:'@react-router/dev':specifier: 'catalog:'- version: 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])'@react-router/remix-routes-option-adapter':specifier: 'catalog:'- version: 7.18.4(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ version: 7.18.4(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])'@supabase/functions-js':specifier: 'catalog:'version: 2.117.2@@ -580,7 +573,7 @@ importers:version: 1.6.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])'@vercel/react-router':specifier: 'catalog:'- version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])cookie:specifier: 'catalog:'version: 1.1.1@@ -662,7 +655,7 @@ importers:version: 4.3.0typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavite:specifier: 'catalog:'version: 8.3.3(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])@@ -687,6 +680,13 @@ importers:'@ai-sdk/react':specifier: 'catalog:'version: 4.0.119([email protected])([email protected])+ '@carbon/serve':+ specifier: workspace:*+ version: link:../../packages/serve+ ai:+ specifier: 'catalog:'+ version: 7.0.116([email protected])+ devDependencies:'@base-ui-components/react':specifier: 1.0.0-rc.0version: 1.0.0-rc.0(@types/[email protected])([email protected]([email protected]))([email protected])@@ -699,12 +699,18 @@ importers:'@carbon/auth':specifier: workspace:*version: link:../../packages/auth+ '@carbon/config':+ specifier: workspace:*+ version: link:../../packages/config'@carbon/content':specifier: workspace:*version: link:../../docs/content'@carbon/database':specifier: workspace:*version: link:../../packages/database+ '@carbon/dev':+ specifier: workspace:*+ version: link:../../packages/dev'@carbon/documents':specifier: workspace:*version: link:../../packages/documents@@ -753,9 +759,6 @@ importers:'@carbon/react':specifier: workspace:*version: link:../../packages/react- '@carbon/serve':- specifier: workspace:*- version: link:../../packages/serve'@carbon/stripe':specifier: workspace:*version: link:../../packages/stripe@@ -789,12 +792,18 @@ importers:'@internationalized/date':specifier: 'catalog:'version: 3.12.0+ '@lingui/conf':+ specifier: 'catalog:'+ version: 6.9.0'@lingui/core':specifier: 'catalog:'version: 6.9.0(@babel/[email protected])([email protected])'@lingui/react':specifier: 'catalog:'+ '@lingui/vite-plugin':+ specifier: 'catalog:'+ version: 6.9.0(@babel/[email protected])(@lingui/[email protected](@babel/[email protected]))([email protected])([email protected])([email protected])([email protected])'@monaco-editor/react':specifier: 4.7.0@@ -810,12 +819,18 @@ importers:'@react-aria/i18n':specifier: 'catalog:'+ '@react-aria/optimize-locales-plugin':+ specifier: 'catalog:'+ version: 2.0.2'@react-pdf/renderer':specifier: 'catalog:'version: 3.4.5([email protected])([email protected])+ '@react-router/dev':+ specifier: 'catalog:'+ version: 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])'@react-router/remix-routes-option-adapter':specifier: 'catalog:'- version: 7.18.4(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ version: 7.18.4(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])'@react-types/datepicker':specifier: 3.13.5version: 3.13.5([email protected])@@ -837,9 +852,18 @@ importers:'@supabase/supabase-js':specifier: 'catalog:'version: 2.117.2(@opentelemetry/[email protected])+ '@tailwindcss/typography':+ specifier: 'catalog:'+ version: 0.5.19([email protected])+ '@tailwindcss/vite':+ specifier: 'catalog:'+ version: 4.3.0([email protected])'@tanstack/react-query':specifier: 'catalog:'version: 5.104.0([email protected])+ '@tanstack/react-query-devtools':+ specifier: 'catalog:'+ version: 5.104.0(@tanstack/[email protected]([email protected]))(@types/[email protected])([email protected])([email protected])'@tanstack/react-table':specifier: 8.21.3@@ -849,6 +873,39 @@ importers:'@tiptap/react':specifier: 'catalog:'version: 2.27.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])([email protected]([email protected]))([email protected])+ '@types/d3':+ specifier: 7.4.3+ version: 7.4.3+ '@types/d3-force':+ specifier: 3.0.10+ version: 3.0.10+ '@types/lodash':+ specifier: 4.17.26+ version: 4.17.26+ '@types/lodash.template':+ specifier: 4.5.3+ version: 4.5.3+ '@types/nprogress':+ specifier: 0.2.3+ version: 0.2.3+ '@types/papaparse':+ specifier: 5.5.2+ version: 5.5.2+ '@types/pg':+ specifier: 8.15.6+ version: 8.15.6+ '@types/react':+ specifier: 18.3.28+ version: 18.3.28+ '@types/react-csv':+ specifier: 1.1.10+ version: 1.1.10+ '@types/react-dom':+ specifier: 18.3.7+ version: 18.3.7(@types/[email protected])+ '@types/tar-stream':+ specifier: ^3.1.4+ version: 3.1.4'@upstash/ratelimit':specifier: 2.0.8version: 2.0.8(@upstash/[email protected])@@ -860,16 +917,19 @@ importers:version: 3.9.9(@aws-sdk/[email protected])([email protected])'@vercel/react-router':specifier: 'catalog:'- version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])'@visx/responsive':specifier: 2.17.0version: 2.17.0([email protected])+ '@vitejs/devtools':+ specifier: 'catalog:'+ version: 0.7.6(@devframes/[email protected](@devframes/[email protected](@devframes/[email protected])([email protected]([email protected]))([email protected]))([email protected]))(@vitejs/[email protected])([email protected]([email protected]))([email protected])([email protected])+ '@vitejs/devtools-rolldown':+ specifier: 'catalog:'+ version: 0.7.6(@devframes/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])'@xyflow/react':specifier: 12.10.2version: 12.10.2(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])- ai:- specifier: 'catalog:'- version: 7.0.116([email protected])assert-never:specifier: 1.4.0version: 1.4.0@@ -885,6 +945,9 @@ importers:cookie:specifier: 'catalog:'version: 1.1.1+ cross-env:+ specifier: 'catalog:'+ version: 7.0.3d3:specifier: 7.9.0version: 7.9.0@@ -902,7 +965,7 @@ importers:version: 5.6.0inngest:specifier: ^3.54.2- version: 3.54.2(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])+ version: 3.54.2(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])intl-parse-accept-language:specifier: 'catalog:'version: 1.0.0@@ -942,9 +1005,15 @@ importers:nanoid:specifier: 'catalog:'version: 5.1.16+ nodemon:+ specifier: 'catalog:'+ version: 3.1.14non.geist:specifier: 'catalog:'version: 1.0.4+ npm-run-all:+ specifier: 'catalog:'+ version: 4.1.5papaparse:specifier: 5.3.2version: 5.3.2@@ -957,6 +1026,9 @@ importers:performant-array-to-tree:specifier: 1.11.0version: 1.11.0+ pg:+ specifier: 8.20.0+ version: 8.20.0posthog-js:specifier: 'catalog:'version: 1.438.9(@types/[email protected])([email protected])@@ -1038,9 +1110,24 @@ importers:sst:specifier: 'catalog:'version: 4.6.9+ supabase:+ specifier: 'catalog:'+ version: 2.89.0(patch_hash=f278052dbb83b89896a8f742e486a879c8f00b1b22e188717aeb199b1f1a4b4c)tailwind-merge:specifier: 'catalog:'version: 3.3.0+ tailwind-scrollbar:+ specifier: 'catalog:'+ version: 4.0.2([email protected])([email protected])+ tailwind-scrollbar-hide:+ specifier: 'catalog:'+ version: 4.0.0([email protected])+ tailwindcss:+ specifier: 'catalog:'+ version: 4.3.0+ tailwindcss-animate:+ specifier: 'catalog:'+ version: 1.0.7([email protected])tar-stream:specifier: ^3.2.0version: 3.2.0@@ -1049,10 +1136,16 @@ importers:version: 1.3.3tsup:specifier: 'catalog:'- version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])tus-js-client:specifier: 4.3.1version: 4.3.1+ typescript:+ specifier: 'catalog:'+ version: 7.1.0-beta+ typescript5:+ specifier: npm:[email protected]+ version: [email protected]unified:specifier: 11.0.5version: 11.0.5@@ -1062,6 +1155,12 @@ importers:use-stick-to-bottom:specifier: 1.1.3version: 1.1.3([email protected])+ vite:+ specifier: 'catalog:'+ version: 8.3.3(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vitest:+ specifier: 'catalog:'+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])zbsearch:specifier: 'catalog:'version: 4.0.0@@ -1077,112 +1176,13 @@ importers:zustand:specifier: 'catalog:'version: 5.0.12(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))- devDependencies:- '@carbon/config':- specifier: workspace:*- version: link:../../packages/config- '@carbon/dev':- specifier: workspace:*- version: link:../../packages/dev- '@lingui/conf':- specifier: 'catalog:'- version: 6.9.0- '@lingui/vite-plugin':- specifier: 'catalog:'- version: 6.9.0(@babel/[email protected])(@lingui/[email protected](@babel/[email protected]))([email protected])([email protected])([email protected])([email protected])- '@react-aria/optimize-locales-plugin':- specifier: 'catalog:'- version: 2.0.2- '@react-router/dev':- specifier: 'catalog:'- version: 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])- '@tailwindcss/typography':- specifier: 'catalog:'- version: 0.5.19([email protected])- '@tailwindcss/vite':- specifier: 'catalog:'- version: 4.3.0([email protected])- '@tanstack/react-query-devtools':- specifier: 'catalog:'- version: 5.104.0(@tanstack/[email protected]([email protected]))(@types/[email protected])([email protected])([email protected])- '@types/d3':- specifier: 7.4.3- version: 7.4.3- '@types/d3-force':- specifier: 3.0.10- version: 3.0.10- '@types/lodash':- specifier: 4.17.26- version: 4.17.26- '@types/lodash.template':- specifier: 4.5.3- version: 4.5.3- '@types/nprogress':- specifier: 0.2.3- version: 0.2.3- '@types/papaparse':- specifier: 5.5.2- version: 5.5.2- '@types/pg':- specifier: 8.15.6- version: 8.15.6- '@types/react':- specifier: 18.3.28- version: 18.3.28- '@types/react-csv':- specifier: 1.1.10- version: 1.1.10- '@types/react-dom':- specifier: 18.3.7- version: 18.3.7(@types/[email protected])- '@types/tar-stream':- specifier: ^3.1.4- version: 3.1.4- '@vitejs/devtools':- specifier: 'catalog:'- version: 0.7.6(@devframes/[email protected](@devframes/[email protected](@devframes/[email protected])([email protected]([email protected]))([email protected]))([email protected]))(@vitejs/[email protected])([email protected]([email protected]))([email protected])([email protected])- '@vitejs/devtools-rolldown':- specifier: 'catalog:'- version: 0.7.6(@devframes/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])- cross-env:- specifier: 'catalog:'- version: 7.0.3- nodemon:- specifier: 'catalog:'- version: 3.1.14- npm-run-all:- specifier: 'catalog:'- version: 4.1.5- pg:- specifier: 8.20.0- version: 8.20.0- supabase:- specifier: 'catalog:'- version: 2.89.0(patch_hash=f278052dbb83b89896a8f742e486a879c8f00b1b22e188717aeb199b1f1a4b4c)- tailwind-scrollbar:- specifier: 'catalog:'- version: 4.0.2([email protected])([email protected])- tailwind-scrollbar-hide:- specifier: 'catalog:'- version: 4.0.0([email protected])- tailwindcss:- specifier: 'catalog:'- version: 4.3.0- tailwindcss-animate:- specifier: 'catalog:'- version: 1.0.7([email protected])- typescript:- specifier: 'catalog:'- version: 5.8.3- vite:- specifier: 'catalog:'- version: 8.3.3(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- vitest:- specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])apps/mes:dependencies:+ '@carbon/serve':+ specifier: workspace:*+ version: link:../../packages/serve+ devDependencies:'@carbon/account':specifier: workspace:*version: link:../../packages/account@@ -1192,9 +1192,15 @@ importers:'@carbon/auth':specifier: workspace:*version: link:../../packages/auth+ '@carbon/config':+ specifier: workspace:*+ version: link:../../packages/config'@carbon/database':specifier: workspace:*version: link:../../packages/database+ '@carbon/dev':+ specifier: workspace:*+ version: link:../../packages/dev'@carbon/documents':specifier: workspace:*version: link:../../packages/documents@@ -1234,9 +1240,6 @@ importers:'@carbon/react':specifier: workspace:*version: link:../../packages/react- '@carbon/serve':- specifier: workspace:*- version: link:../../packages/serve'@carbon/stripe':specifier: workspace:*version: link:../../packages/stripe@@ -1267,6 +1270,9 @@ importers:'@internationalized/date':specifier: 'catalog:'version: 3.12.0+ '@lingui/conf':+ specifier: 'catalog:'+ version: 6.9.0'@lingui/core':specifier: 'catalog:'version: 6.9.0(@babel/[email protected])([email protected])@@ -1275,19 +1281,22 @@ importers:'@lingui/vite-plugin':specifier: 'catalog:'- version: 6.9.0(@babel/[email protected])(@lingui/[email protected](@babel/[email protected]))([email protected])([email protected])([email protected])([email protected])+ version: 6.9.0(@babel/[email protected])(@lingui/[email protected](@babel/[email protected]))([email protected])([email protected])([email protected])([email protected])'@react-aria/i18n':specifier: 'catalog:'+ '@react-aria/optimize-locales-plugin':+ specifier: 'catalog:'+ version: 2.0.2'@react-pdf/renderer':specifier: 'catalog:'version: 3.4.5([email protected])([email protected])'@react-router/dev':specifier: 'catalog:'- version: 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])'@react-router/remix-routes-option-adapter':specifier: 'catalog:'- version: 7.18.4(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ version: 7.18.4(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])'@simplewebauthn/browser':specifier: ^13.3.0version: 13.3.0@@ -1309,6 +1318,9 @@ importers:'@tanstack/react-query':specifier: 'catalog:'version: 5.104.0([email protected])+ '@tanstack/react-query-devtools':+ specifier: 'catalog:'+ version: 5.104.0(@tanstack/[email protected]([email protected]))(@types/[email protected])([email protected])([email protected])'@tiptap/core':specifier: 'catalog:'version: 2.27.2(@tiptap/[email protected])@@ -1345,6 +1357,12 @@ importers:'@tiptap/starter-kit':specifier: 'catalog:'version: 2.27.2+ '@types/react':+ specifier: 18.3.28+ version: 18.3.28+ '@types/react-dom':+ specifier: 18.3.7+ version: 18.3.7(@types/[email protected])'@vercel/analytics':specifier: 'catalog:'version: 1.6.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])@@ -1353,7 +1371,13 @@ importers:version: 3.9.9(@aws-sdk/[email protected])([email protected])'@vercel/react-router':specifier: 'catalog:'- version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ '@vitejs/devtools':+ specifier: 'catalog:'+ version: 0.7.6(@devframes/[email protected](@devframes/[email protected](@devframes/[email protected])([email protected]([email protected]))([email protected]))([email protected]))(@vitejs/[email protected])([email protected]([email protected]))([email protected])([email protected])+ '@vitejs/devtools-rolldown':+ specifier: 'catalog:'+ version: 0.7.6(@devframes/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])'@xyflow/react':specifier: 12.10.2version: 12.10.2(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])@@ -1363,6 +1387,9 @@ importers:cookie:specifier: 'catalog:'version: 1.1.1+ cross-env:+ specifier: 'catalog:'+ version: 7.0.3dompurify:specifier: 'catalog:'version: 3.4.17@@ -1384,9 +1411,15 @@ importers:nanoid:specifier: 'catalog:'version: 5.1.16+ nodemon:+ specifier: 'catalog:'+ version: 3.1.14non.geist:specifier: 'catalog:'version: 1.0.4+ npm-run-all:+ specifier: 'catalog:'+ version: 4.1.5pdfjs-dist:specifier: 5.4.296version: 5.4.296@@ -1435,55 +1468,6 @@ importers:tailwind-merge:specifier: 'catalog:'version: 3.3.0- tailwindcss-animate:- specifier: 'catalog:'- version: 1.0.7([email protected])- tsup:- specifier: 'catalog:'- version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])- zod:- specifier: 'catalog:'- version: 4.5.4- zod-form-data:- specifier: 'catalog:'- version: 3.0.3([email protected])- devDependencies:- '@carbon/config':- specifier: workspace:*- version: link:../../packages/config- '@carbon/dev':- specifier: workspace:*- version: link:../../packages/dev- '@lingui/conf':- specifier: 'catalog:'- version: 6.9.0- '@react-aria/optimize-locales-plugin':- specifier: 'catalog:'- version: 2.0.2- '@tanstack/react-query-devtools':- specifier: 'catalog:'- version: 5.104.0(@tanstack/[email protected]([email protected]))(@types/[email protected])([email protected])([email protected])- '@types/react':- specifier: 18.3.28- version: 18.3.28- '@types/react-dom':- specifier: 18.3.7- version: 18.3.7(@types/[email protected])- '@vitejs/devtools':- specifier: 'catalog:'- version: 0.7.6(@devframes/[email protected](@devframes/[email protected](@devframes/[email protected])([email protected]([email protected]))([email protected]))([email protected]))(@vitejs/[email protected])([email protected]([email protected]))([email protected])([email protected])- '@vitejs/devtools-rolldown':- specifier: 'catalog:'- version: 0.7.6(@devframes/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])- cross-env:- specifier: 'catalog:'- version: 7.0.3- nodemon:- specifier: 'catalog:'- version: 3.1.14- npm-run-all:- specifier: 'catalog:'- version: 4.1.5tailwind-scrollbar:specifier: 'catalog:'version: 4.0.2([email protected])([email protected])@@ -1493,18 +1477,30 @@ importers:tailwindcss:specifier: 'catalog:'version: 4.3.0+ tailwindcss-animate:+ specifier: 'catalog:'+ version: 1.0.7([email protected])+ tsup:+ specifier: 'catalog:'+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavite:specifier: 'catalog:'- version: 8.3.3(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.3.3(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])wait-on:specifier: 'catalog:'version: 7.2.0+ zod:+ specifier: 'catalog:'+ version: 4.5.4+ zod-form-data:+ specifier: 'catalog:'+ version: 3.0.3([email protected])apps/starter:dependencies:@@ -1555,10 +1551,10 @@ importers:'@react-router/dev':specifier: 'catalog:'- version: 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])'@react-router/remix-routes-option-adapter':specifier: 'catalog:'- version: 7.18.4(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ version: 7.18.4(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])'@supabase/functions-js':specifier: 'catalog:'version: 2.117.2@@ -1579,7 +1575,7 @@ importers:version: 1.6.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])'@vercel/react-router':specifier: 'catalog:'- version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])cookie:specifier: 'catalog:'version: 1.1.1@@ -1664,7 +1660,7 @@ importers:version: 4.3.0typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavite:specifier: 'catalog:'version: 8.3.3(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])@@ -1707,10 +1703,10 @@ importers:version: link:../../../../packages/utils'@react-router/dev':specifier: 'catalog:'- version: 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])'@react-router/fs-routes':specifier: 7.14.0- version: 7.14.0(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ version: 7.14.0(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])'@supabase/functions-js':specifier: 'catalog:'version: 2.117.2@@ -1719,7 +1715,7 @@ importers:version: 2.117.2(@opentelemetry/[email protected])'@vercel/react-router':specifier: 'catalog:'- version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])non.geist:specifier: 'catalog:'version: 1.0.4@@ -1768,7 +1764,7 @@ importers:version: 4.3.0typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavite:specifier: 'catalog:'version: 8.3.3(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])@@ -1786,10 +1782,10 @@ importers:version: link:../../../../packages/utils'@react-router/dev':specifier: 'catalog:'- version: 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])'@react-router/fs-routes':specifier: 7.14.0- version: 7.14.0(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ version: 7.14.0(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])'@supabase/functions-js':specifier: 'catalog:'version: 2.117.2@@ -1798,7 +1794,7 @@ importers:version: 2.117.2(@opentelemetry/[email protected])'@vercel/react-router':specifier: 'catalog:'- version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])nanoid:specifier: 'catalog:'version: 5.1.16@@ -1844,7 +1840,7 @@ importers:version: 4.3.0typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavite:specifier: 'catalog:'version: 8.3.3(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])@@ -1941,7 +1937,7 @@ importers:version: 1.0.7([email protected])typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betadocs/content:dependencies:@@ -1966,7 +1962,7 @@ importers:version: 5.0.10typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavite:specifier: 'catalog:'version: 8.3.3(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])@@ -1979,9 +1975,6 @@ importers:'@carbon/auth':specifier: workspace:*version: link:../auth- '@carbon/database':- specifier: workspace:*- version: link:../database'@carbon/files':specifier: workspace:*version: link:../files@@ -2001,11 +1994,8 @@ importers:specifier: workspace:*version: link:../react'@carbon/utils':- specifier: workspace:*- version: link:../utils- '@lingui/core':- specifier: 'catalog:'- version: 6.9.0(@babel/[email protected])([email protected])+ specifier: workspace:*+ version: link:../utils'@lingui/react':specifier: 'catalog:'@@ -2034,6 +2024,12 @@ importers:'@carbon/config':specifier: workspace:*version: link:../config+ '@carbon/database':+ specifier: workspace:*+ version: link:../database+ '@lingui/core':+ specifier: 'catalog:'+ version: 6.9.0(@babel/[email protected])([email protected])'@types/react':specifier: 18.3.28version: 18.3.28@@ -2042,53 +2038,53 @@ importers:version: 5.0.10typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betapackages/api:dependencies:'@carbon/auth':specifier: workspace:*version: link:../auth- '@carbon/database':- specifier: workspace:*- version: link:../database- '@carbon/kv':- specifier: workspace:*- version: link:../kv'@carbon/logger':specifier: workspace:*version: link:../logger'@carbon/utils':specifier: workspace:*version: link:../utils+ zod:+ specifier: 'catalog:'+ version: 4.5.4+ devDependencies:+ '@carbon/config':+ specifier: workspace:*+ version: link:../config+ '@carbon/database':+ specifier: workspace:*+ version: link:../database+ '@carbon/kv':+ specifier: workspace:*+ version: link:../kv'@orpc/client':specifier: 'catalog:'version: 1.15.0(@opentelemetry/[email protected])'@orpc/contract':specifier: 'catalog:'version: 1.15.0(@opentelemetry/[email protected])+ '@orpc/openapi':+ specifier: 'catalog:'+ version: 1.15.0(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])'@orpc/openapi-client':specifier: 'catalog:'version: 1.15.0(@opentelemetry/[email protected])'@supabase/supabase-js':specifier: 'catalog:'version: 2.117.2(@opentelemetry/[email protected])- zod:- specifier: 'catalog:'- version: 4.5.4- devDependencies:- '@carbon/config':- specifier: workspace:*- version: link:../config- '@orpc/openapi':- specifier: 'catalog:'- version: 1.15.0(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])tsx:specifier: 'catalog:'version: 4.21.0typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -2118,7 +2114,7 @@ importers:version: link:../react'@react-router/dev':specifier: 'catalog:'- version: 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])'@simplewebauthn/server':specifier: ^13.3.2version: 13.3.3@@ -2133,22 +2129,16 @@ importers:version: 1.6.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])'@vercel/react-router':specifier: 'catalog:'- version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])botid:specifier: 'catalog:'version: 1.5.11([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])cookie:specifier: 'catalog:'version: 1.1.1- dompurify:- specifier: 'catalog:'- version: 3.4.17jose:specifier: 'catalog:'version: 6.0.11- nanoid:- specifier: 'catalog:'- version: 5.1.16react:specifier: 18.3.1version: 18.3.1@@ -2164,9 +2154,6 @@ importers:zod-form-data:specifier: 'catalog:'version: 3.0.3([email protected])- zustand:- specifier: 'catalog:'- version: 5.0.12(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))devDependencies:'@carbon/config':specifier: workspace:*@@ -2180,18 +2167,27 @@ importers:'@types/react':specifier: 18.3.28version: 18.3.28+ dompurify:+ specifier: 'catalog:'+ version: 3.4.17+ nanoid:+ specifier: 'catalog:'+ version: 5.1.16sst:specifier: 'catalog:'version: 4.6.9tsup:specifier: 'catalog:'- version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])+ zustand:+ specifier: 'catalog:'+ version: 5.0.12(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))packages/checks:devDependencies:@@ -2201,6 +2197,9 @@ importers:'@carbon/ee':specifier: workspace:*version: link:../ee+ '@carbon/env':+ specifier: workspace:*+ version: link:../env'@types/node':specifier: ^22version: 22.19.7@@ -2218,7 +2217,10 @@ importers:version: 4.21.0typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-beta+ typescript5:+ specifier: npm:[email protected]+ version: [email protected]vitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -2268,21 +2270,18 @@ importers:'@jitl/quickjs-singlefile-browser-release-sync':specifier: 0.32.0version: 0.32.0- '@supabase/postgrest-js':- specifier: 'catalog:'- version: 2.117.2- cookie:- specifier: 'catalog:'- version: 1.1.1- dompurify:+ '@supabase/supabase-js':specifier: 'catalog:'- version: 3.4.17+ version: 2.117.2(@opentelemetry/[email protected])+ dotenv:+ specifier: 16.3.1+ version: 16.3.1kysely:specifier: 'catalog:'version: 0.28.17- kysely-supabase:- specifier: 0.2.1- version: 0.2.1([email protected])([email protected](patch_hash=f278052dbb83b89896a8f742e486a879c8f00b1b22e188717aeb199b1f1a4b4c))+ libpg-query:+ specifier: 18.1.5+ version: 18.1.5nanoid:specifier: 'catalog:'version: 5.1.16@@ -2292,12 +2291,6 @@ importers:quickjs-emscripten-core:specifier: 0.32.0version: 0.32.0- react-pdf:- specifier: 'catalog:'- version: 10.4.1(@types/[email protected])([email protected]([email protected]))([email protected])- sst:- specifier: 'catalog:'- version: 4.6.9sucrase:specifier: 3.35.1version: 3.35.1@@ -2308,9 +2301,9 @@ importers:'@carbon/config':specifier: workspace:*version: link:../config- '@supabase/supabase-js':+ '@supabase/postgrest-js':specifier: 'catalog:'- version: 2.117.2(@opentelemetry/[email protected])+ version: 2.117.2'@types/node':specifier: 20.19.39version: 20.19.39@@ -2320,30 +2313,39 @@ importers:'@types/uuid':specifier: 8.3.4version: 8.3.4- dotenv:- specifier: 16.3.1- version: 16.3.1- libpg-query:- specifier: 18.1.5- version: 18.1.5+ cookie:+ specifier: 'catalog:'+ version: 1.1.1+ dompurify:+ specifier: 'catalog:'+ version: 3.4.17+ kysely-supabase:+ specifier: 0.2.1+ version: 0.2.1([email protected])([email protected](patch_hash=f278052dbb83b89896a8f742e486a879c8f00b1b22e188717aeb199b1f1a4b4c))npm-run-all:specifier: 'catalog:'version: 4.1.5+ react-pdf:+ specifier: 'catalog:'+ version: 10.4.1(@types/[email protected])([email protected]([email protected]))([email protected])rimraf:specifier: 'catalog:'version: 5.0.10+ sst:+ specifier: 'catalog:'+ version: 4.6.9supabase:specifier: 'catalog:'version: 2.89.0(patch_hash=f278052dbb83b89896a8f742e486a879c8f00b1b22e188717aeb199b1f1a4b4c)tsup:specifier: 'catalog:'- version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])tsx:specifier: 'catalog:'version: 4.21.0typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betauuid:specifier: 9.0.0version: 9.0.0@@ -2432,39 +2434,24 @@ importers:'@carbon/notifications':specifier: workspace:*version: link:../notifications- '@carbon/react':- specifier: workspace:*- version: link:../react'@carbon/utils':specifier: workspace:*version: link:../utils- '@hookform/resolvers':- specifier: 3.10.0- version: 3.10.0([email protected]([email protected]))+ '@internationalized/date':+ specifier: 'catalog:'+ version: 3.12.0'@react-pdf/renderer':specifier: 'catalog:'version: 3.4.5([email protected])([email protected])- cookie:- specifier: 'catalog:'- version: 1.1.1- dompurify:- specifier: 'catalog:'- version: 3.4.17- nanoid:- specifier: 'catalog:'- version: 5.1.16+ react:+ specifier: 18.3.1+ version: 18.3.1react-email:specifier: 'catalog:'- react-icons:- specifier: 'catalog:'- version: 5.6.0([email protected])react-pdf-tailwind:specifier: 2.3.0- sst:- specifier: 'catalog:'- version: 4.6.9zod:specifier: 'catalog:'version: 4.5.4@@ -2475,6 +2462,9 @@ importers:'@carbon/database':specifier: workspace:*version: link:../database+ '@carbon/react':+ specifier: workspace:*+ version: link:../react'@fontsource/inter':specifier: ^5.0.0version: 5.2.8@@ -2499,9 +2489,9 @@ importers:'@fontsource/roboto':specifier: ^5.0.0version: 5.2.10- '@internationalized/date':- specifier: 'catalog:'- version: 3.12.0+ '@hookform/resolvers':+ specifier: 3.10.0+ version: 3.10.0([email protected]([email protected]))'@react-email/ui':specifier: 6.11.3version: 6.11.3(@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])@@ -2514,18 +2504,30 @@ importers:'@types/react':specifier: 18.3.28version: 18.3.28+ cookie:+ specifier: 'catalog:'+ version: 1.1.1+ dompurify:+ specifier: 'catalog:'+ version: 3.4.17+ nanoid:+ specifier: 'catalog:'+ version: 5.1.16postcss:specifier: 8.5.29version: 8.5.29- react:- specifier: 18.3.1- version: 18.3.1+ react-icons:+ specifier: 'catalog:'+ version: 5.6.0([email protected])+ sst:+ specifier: 'catalog:'+ version: 4.6.9tsup:specifier: 'catalog:'- version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -2541,6 +2543,9 @@ importers:'@carbon/auth':specifier: workspace:*version: link:../auth+ '@carbon/content':+ specifier: workspace:*+ version: link:../../docs/content'@carbon/database':specifier: workspace:*version: link:../database@@ -2586,27 +2591,15 @@ importers:'@slack/oauth':specifier: 3.0.5version: 3.0.5- '@slack/types':- specifier: 2.20.1- version: 2.20.1'@slack/web-api':specifier: 'catalog:'version: 7.10.0- '@supabase/supabase-js':- specifier: 'catalog:'- version: 2.117.2(@opentelemetry/[email protected])ai:specifier: 'catalog:'version: 7.0.116([email protected])axios:specifier: 1.20.0version: 1.20.0- cookie:- specifier: 'catalog:'- version: 1.1.1- dompurify:- specifier: 'catalog:'- version: 3.4.17jose:specifier: 'catalog:'version: 6.0.11@@ -2625,21 +2618,9 @@ importers:react-icons:specifier: 'catalog:'version: 5.6.0([email protected])- react-pdf:- specifier: 'catalog:'- version: 10.4.1(@types/[email protected])([email protected]([email protected]))([email protected])react-router:specifier: 'catalog:'- sst:- specifier: 'catalog:'- version: 4.6.9- supabase:- specifier: 'catalog:'- version: 2.89.0(patch_hash=f278052dbb83b89896a8f742e486a879c8f00b1b22e188717aeb199b1f1a4b4c)- tsup:- specifier: 'catalog:'- version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])zbsearch:specifier: 'catalog:'version: 4.0.0@@ -2653,9 +2634,6 @@ importers:'@carbon/config':specifier: workspace:*version: link:../config- '@carbon/content':- specifier: workspace:*- version: link:../../docs/content'@logtape/logtape':specifier: 'catalog:'version: 2.2.3@@ -2665,15 +2643,39 @@ importers:'@modelcontextprotocol/client':specifier: 2.3.1version: 2.3.1+ '@slack/types':+ specifier: 2.20.1+ version: 2.20.1+ '@supabase/supabase-js':+ specifier: 'catalog:'+ version: 2.117.2(@opentelemetry/[email protected])'@types/nodemailer':specifier: 6.4.21version: 6.4.21'@types/react':specifier: 18.3.28version: 18.3.28+ cookie:+ specifier: 'catalog:'+ version: 1.1.1+ dompurify:+ specifier: 'catalog:'+ version: 3.4.17+ react-pdf:+ specifier: 'catalog:'+ version: 10.4.1(@types/[email protected])([email protected]([email protected]))([email protected])+ sst:+ specifier: 'catalog:'+ version: 4.6.9+ supabase:+ specifier: 'catalog:'+ version: 2.89.0(patch_hash=f278052dbb83b89896a8f742e486a879c8f00b1b22e188717aeb199b1f1a4b4c)+ tsup:+ specifier: 'catalog:'+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -2683,9 +2685,6 @@ importers:'@carbon/utils':specifier: workspace:*version: link:../utils- '@types/node':- specifier: 20.19.39- version: 20.19.39zod:specifier: 'catalog:'version: 4.5.4@@ -2693,9 +2692,12 @@ importers:'@carbon/config':specifier: workspace:*version: link:../config+ '@types/node':+ specifier: 20.19.39+ version: 20.19.39typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -2723,9 +2725,6 @@ importers:'@supabase/storage-js':specifier: 'catalog:'version: 2.117.2- '@supabase/supabase-js':- specifier: 'catalog:'- version: 2.117.2(@opentelemetry/[email protected])'@tiptap/pm':specifier: 'catalog:'version: 2.27.2@@ -2748,21 +2747,21 @@ importers:'@carbon/config':specifier: workspace:*version: link:../config+ '@supabase/supabase-js':+ specifier: 'catalog:'+ version: 2.117.2(@opentelemetry/[email protected])'@types/papaparse':specifier: 5.5.2version: 5.5.2typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])packages/form:dependencies:- '@carbon/content':- specifier: workspace:*- version: link:../../docs/content'@carbon/logger':specifier: workspace:*version: link:../logger@@ -2772,21 +2771,12 @@ importers:'@carbon/utils':specifier: workspace:*version: link:../utils- '@internationalized/date':- specifier: 'catalog:'- version: 3.12.0'@react-aria/i18n':specifier: 'catalog:'- '@remix-run/server-runtime':- specifier: 2.17.5- version: 2.17.5([email protected])- cookie:- specifier: 'catalog:'- version: 1.1.1- immer:- specifier: 9.0.21- version: 9.0.21+ '@remix-run/server-runtime':+ specifier: 2.17.5+ version: 2.17.5([email protected])lodash.get:specifier: 4.4.2version: 4.4.2@@ -2805,9 +2795,6 @@ importers:remeda:specifier: 1.61.0version: 1.61.0- sst:- specifier: 'catalog:'- version: 4.6.9tiny-invariant:specifier: 1.3.3version: 1.3.3@@ -2821,6 +2808,12 @@ importers:'@carbon/config':specifier: workspace:*version: link:../config+ '@carbon/content':+ specifier: workspace:*+ version: link:../../docs/content+ '@internationalized/date':+ specifier: 'catalog:'+ version: 3.12.0'@lingui/react':specifier: 'catalog:'@@ -2833,15 +2826,24 @@ importers:'@types/react-dom':specifier: 18.3.7version: 18.3.7(@types/[email protected])+ cookie:+ specifier: 'catalog:'+ version: 1.1.1fetch-blob:specifier: 3.2.0version: 3.2.0+ immer:+ specifier: 9.0.21+ version: 9.0.21react:specifier: 18.3.1version: 18.3.1react-dom:specifier: 18.3.1version: 18.3.1([email protected])+ sst:+ specifier: 'catalog:'+ version: 4.6.9ts-toolbelt:specifier: 9.6.0version: 9.6.0@@ -2850,7 +2852,7 @@ importers:version: 7.0.0typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -2874,7 +2876,7 @@ importers:version: 4.21.0typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -2941,12 +2943,6 @@ importers:'@slack/web-api':specifier: 'catalog:'version: 7.10.0- '@supabase/functions-js':- specifier: 'catalog:'- version: 2.117.2- '@supabase/supabase-js':- specifier: 'catalog:'- version: 2.117.2(@opentelemetry/[email protected])ai:specifier: 'catalog:'version: 7.0.116([email protected])@@ -2955,34 +2951,16 @@ importers:version: 1.20.0inngest:specifier: ^3.54.2- version: 3.54.2(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])+ version: 3.54.2(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])kysely:specifier: 'catalog:'version: 0.28.17nanoid:specifier: 'catalog:'version: 5.1.16- react:- specifier: 18.3.1- version: 18.3.1- react-dom:- specifier: 18.3.1- version: 18.3.1([email protected])react-email:specifier: 'catalog:'- react-pdf:- specifier: 'catalog:'- version: 10.4.1(@types/[email protected])([email protected]([email protected]))([email protected])- sst:- specifier: 'catalog:'- version: 4.6.9- supabase:- specifier: 'catalog:'- version: 2.89.0(patch_hash=f278052dbb83b89896a8f742e486a879c8f00b1b22e188717aeb199b1f1a4b4c)- tsup:- specifier: 'catalog:'- version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])undici:specifier: ^8.10.2version: 8.11.2@@ -2996,6 +2974,12 @@ importers:'@carbon/config':specifier: workspace:*version: link:../config+ '@supabase/functions-js':+ specifier: 'catalog:'+ version: 2.117.2+ '@supabase/supabase-js':+ specifier: 'catalog:'+ version: 2.117.2(@opentelemetry/[email protected])'@types/pg':specifier: 8.15.6version: 8.15.6@@ -3008,12 +2992,30 @@ importers:pg:specifier: 8.20.0version: 8.20.0+ react:+ specifier: 18.3.1+ version: 18.3.1+ react-dom:+ specifier: 18.3.1+ version: 18.3.1([email protected])+ react-pdf:+ specifier: 'catalog:'+ version: 10.4.1(@types/[email protected])([email protected]([email protected]))([email protected])+ sst:+ specifier: 'catalog:'+ version: 4.6.9+ supabase:+ specifier: 'catalog:'+ version: 2.89.0(patch_hash=f278052dbb83b89896a8f742e486a879c8f00b1b22e188717aeb199b1f1a4b4c)+ tsup:+ specifier: 'catalog:'+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])tsx:specifier: 'catalog:'version: 4.21.0typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -3026,18 +3028,9 @@ importers:'@carbon/logger':specifier: workspace:*version: link:../logger- cookie:- specifier: 'catalog:'- version: 1.1.1- dompurify:- specifier: 'catalog:'- version: 3.4.17ioredis:specifier: 5.10.1version: 5.10.1- nanoid:- specifier: 'catalog:'- version: 5.1.16devDependencies:'@carbon/config':specifier: workspace:*@@ -3048,12 +3041,21 @@ importers:'@types/node':specifier: 20.19.39version: 20.19.39+ cookie:+ specifier: 'catalog:'+ version: 1.1.1+ dompurify:+ specifier: 'catalog:'+ version: 3.4.17dotenv:specifier: 16.3.1version: 16.3.1ioredis-mock:specifier: 8.13.1+ nanoid:+ specifier: 'catalog:'+ version: 5.1.16rimraf:specifier: 'catalog:'version: 5.0.10@@ -3062,22 +3064,19 @@ importers:version: 4.6.9tsup:specifier: 'catalog:'- version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])tsx:specifier: 'catalog:'version: 4.21.0typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])packages/lib:dependencies:- '@carbon/database':- specifier: workspace:*- version: link:../database'@carbon/documents':specifier: workspace:*version: link:../documents@@ -3093,27 +3092,18 @@ importers:'@carbon/logger':specifier: workspace:*version: link:../logger- '@carbon/notifications':- specifier: workspace:*- version: link:../notifications'@carbon/utils':specifier: workspace:*version: link:../utils- '@carbon/workflows-core':- specifier: workspace:*- version: link:../workflows-core'@react-pdf/renderer':specifier: 'catalog:'version: 3.4.5([email protected])([email protected])'@slack/web-api':specifier: 'catalog:'version: 7.10.0- '@supabase/supabase-js':- specifier: 'catalog:'- version: 2.117.2(@opentelemetry/[email protected])inngest:specifier: 3.54.2- version: 3.54.2(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])+ version: 3.54.2(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])nanoid:specifier: 'catalog:'version: 5.1.16@@ -3123,12 +3113,6 @@ importers:resend:specifier: 3.5.0- sst:- specifier: 'catalog:'- version: 4.6.9- supabase:- specifier: 'catalog:'- version: 2.89.0(patch_hash=f278052dbb83b89896a8f742e486a879c8f00b1b22e188717aeb199b1f1a4b4c)zod:specifier: 'catalog:'version: 4.5.4@@ -3136,6 +3120,18 @@ importers:'@carbon/config':specifier: workspace:*version: link:../config+ '@carbon/database':+ specifier: workspace:*+ version: link:../database+ '@carbon/notifications':+ specifier: workspace:*+ version: link:../notifications+ '@carbon/workflows-core':+ specifier: workspace:*+ version: link:../workflows-core+ '@supabase/supabase-js':+ specifier: 'catalog:'+ version: 2.117.2(@opentelemetry/[email protected])'@types/node':specifier: 20.19.39version: 20.19.39@@ -3148,15 +3144,21 @@ importers:rimraf:specifier: 'catalog:'version: 5.0.10+ sst:+ specifier: 'catalog:'+ version: 4.6.9+ supabase:+ specifier: 'catalog:'+ version: 2.89.0(patch_hash=f278052dbb83b89896a8f742e486a879c8f00b1b22e188717aeb199b1f1a4b4c)tsup:specifier: 'catalog:'- version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])tsx:specifier: 'catalog:'version: 4.21.0typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -3184,10 +3186,10 @@ importers:version: 18.3.1tsup:specifier: 'catalog:'- version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -3242,7 +3244,7 @@ importers:version: 5.0.10typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -3260,25 +3262,16 @@ importers:version: 4.6.9typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])packages/onboarding:dependencies:- '@carbon/database':- specifier: workspace:*- version: link:../database- '@carbon/form':- specifier: workspace:*- version: link:../form'@carbon/react':specifier: workspace:*version: link:../react- '@carbon/utils':- specifier: workspace:*- version: link:../utils'@internationalized/date':specifier: 'catalog:'version: 3.12.0@@ -3288,9 +3281,6 @@ importers:'@lingui/react':specifier: 'catalog:'- '@supabase/supabase-js':- specifier: 'catalog:'- version: 2.117.2(@opentelemetry/[email protected])react:specifier: 18.3.1version: 18.3.1@@ -3307,6 +3297,18 @@ importers:'@carbon/config':specifier: workspace:*version: link:../config+ '@carbon/database':+ specifier: workspace:*+ version: link:../database+ '@carbon/form':+ specifier: workspace:*+ version: link:../form+ '@carbon/utils':+ specifier: workspace:*+ version: link:../utils+ '@supabase/supabase-js':+ specifier: 'catalog:'+ version: 2.117.2(@opentelemetry/[email protected])'@types/react':specifier: 18.3.28version: 18.3.28@@ -3315,10 +3317,10 @@ importers:version: 5.0.10tsup:specifier: 'catalog:'- version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -3337,9 +3339,6 @@ importers:'@internationalized/date':specifier: 'catalog:'version: 3.12.0- '@supabase/supabase-js':- specifier: 'catalog:'- version: 2.117.2(@opentelemetry/[email protected])kysely:specifier: 'catalog:'version: 0.28.17@@ -3350,9 +3349,12 @@ importers:'@carbon/config':specifier: workspace:*version: link:../config+ '@supabase/supabase-js':+ specifier: 'catalog:'+ version: 2.117.2(@opentelemetry/[email protected])typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -3404,13 +3406,10 @@ importers:version: 18.3.28typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betapackages/query:dependencies:- '@carbon/database':- specifier: workspace:*- version: link:../database'@carbon/env':specifier: workspace:*version: link:../env@@ -3433,6 +3432,9 @@ importers:'@carbon/config':specifier: workspace:*version: link:../config+ '@carbon/database':+ specifier: workspace:*+ version: link:../database'@types/react':specifier: 18.3.28version: 18.3.28@@ -3444,7 +3446,7 @@ importers:typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -3457,12 +3459,6 @@ importers:'@carbon/content':specifier: workspace:*version: link:../../docs/content- '@carbon/database':- specifier: workspace:*- version: link:../database- '@carbon/env':- specifier: workspace:*- version: link:../env'@carbon/files':specifier: workspace:*version: link:../files@@ -3493,9 +3489,6 @@ importers:'@radix-ui/react-accordion':specifier: 1.2.12version: 1.2.12(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-avatar':- specifier: 1.1.11- version: 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])'@radix-ui/react-checkbox':specifier: 1.3.3version: 1.3.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])@@ -3571,33 +3564,9 @@ importers:'@react-stately/datepicker':specifier: 3.16.1version: 3.16.1([email protected])- '@react-types/button':- specifier: 3.15.1- version: 3.15.1([email protected])- '@react-types/calendar':- specifier: 3.8.3- version: 3.8.3([email protected])- '@react-types/datepicker':- specifier: 3.13.5- version: 3.13.5([email protected])'@shikijs/langs':specifier: 'catalog:'version: 4.2.0- '@shikijs/themes':- specifier: 'catalog:'- version: 4.2.0- '@shikijs/types':- specifier: 'catalog:'- version: 4.2.0- '@supabase/supabase-js':- specifier: 'catalog:'- version: 2.117.2(@opentelemetry/[email protected])- '@tailwindcss/typography':- specifier: 'catalog:'- version: 0.5.19([email protected])- '@tanstack/react-table':- specifier: 8.21.3'@tanstack/react-virtual':specifier: 3.13.23@@ -3628,9 +3597,6 @@ importers:'@tiptap/extension-underline':specifier: 'catalog:'version: 2.27.2(@tiptap/[email protected](@tiptap/[email protected]))- '@tiptap/extension-youtube':- specifier: 'catalog:'- version: 2.27.2(@tiptap/[email protected](@tiptap/[email protected]))'@tiptap/pm':specifier: 'catalog:'version: 2.27.2@@ -3667,9 +3633,6 @@ importers:cmdk:specifier: 0.2.0- cookie:- specifier: 'catalog:'- version: 1.1.1dompurify:specifier: 'catalog:'version: 3.4.17@@ -3679,21 +3642,12 @@ importers:input-otp:specifier: 1.4.2- intl-parse-accept-language:- specifier: 'catalog:'- version: 1.0.0- is-hotkey:- specifier: 0.2.0- version: 0.2.0match-sorter:specifier: 'catalog:'version: 8.1.0motion:specifier: 'catalog:'version: 12.38.0(@emotion/[email protected])([email protected]([email protected]))([email protected])- nanoid:- specifier: 'catalog:'- version: 5.1.16nprogress:specifier: 0.2.0version: 0.2.0@@ -3712,9 +3666,6 @@ importers:react-icons:specifier: 'catalog:'version: 5.6.0([email protected])- react-resizable-panels:- specifier: 'catalog:'react-router:specifier: 'catalog:'@@ -3730,19 +3681,49 @@ importers:tailwind-merge:specifier: 'catalog:'version: 3.3.0- tailwindcss-animate:- specifier: 'catalog:'- version: 1.0.7([email protected])- zustand:- specifier: 'catalog:'- version: 5.0.12(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))devDependencies:'@carbon/config':specifier: workspace:*version: link:../config+ '@carbon/database':+ specifier: workspace:*+ version: link:../database+ '@carbon/env':+ specifier: workspace:*+ version: link:../env+ '@radix-ui/react-avatar':+ specifier: 1.1.11+ version: 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@react-types/button':+ specifier: 3.15.1+ version: 3.15.1([email protected])+ '@react-types/calendar':+ specifier: 3.8.3+ version: 3.8.3([email protected])+ '@react-types/datepicker':+ specifier: 3.13.5+ version: 3.13.5([email protected])+ '@shikijs/themes':+ specifier: 'catalog:'+ version: 4.2.0+ '@shikijs/types':+ specifier: 'catalog:'+ version: 4.2.0+ '@supabase/supabase-js':+ specifier: 'catalog:'+ version: 2.117.2(@opentelemetry/[email protected])+ '@tailwindcss/typography':+ specifier: 'catalog:'+ version: 0.5.19([email protected])+ '@tanstack/react-table':+ specifier: 8.21.3'@testing-library/dom':specifier: 8.20.1version: 8.20.1+ '@tiptap/extension-youtube':+ specifier: 'catalog:'+ version: 2.27.2(@tiptap/[email protected](@tiptap/[email protected]))'@types/dompurify':specifier: 2.4.0version: 2.4.0@@ -3761,27 +3742,48 @@ importers:'@types/react-window':specifier: 1.8.8version: 1.8.8+ cookie:+ specifier: 'catalog:'+ version: 1.1.1+ intl-parse-accept-language:+ specifier: 'catalog:'+ version: 1.0.0+ is-hotkey:+ specifier: 0.2.0+ version: 0.2.0jsdom:specifier: 26.1.0version: 26.1.0+ nanoid:+ specifier: 'catalog:'+ version: 5.1.16react:specifier: 18.3.1version: 18.3.1+ react-resizable-panels:+ specifier: 'catalog:'sst:specifier: 'catalog:'version: 4.6.9tailwindcss:specifier: 'catalog:'version: 4.3.0+ tailwindcss-animate:+ specifier: 'catalog:'+ version: 1.0.7([email protected])tsup:specifier: 'catalog:'- version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])+ zustand:+ specifier: 'catalog:'+ version: 5.0.12(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))packages/serve:dependencies:@@ -3818,7 +3820,7 @@ importers:version: 20.19.39typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -3852,22 +3854,25 @@ importers:'@internationalized/date':specifier: 'catalog:'version: 3.12.0- '@supabase/supabase-js':- specifier: 'catalog:'- version: 2.117.2(@opentelemetry/[email protected])+ dotenv:+ specifier: 16.3.1+ version: 16.3.1stripe:specifier: 22.4.0version: 22.4.0(@types/[email protected])+ zod:+ specifier: 'catalog:'+ version: 4.5.4devDependencies:'@carbon/config':specifier: workspace:*version: link:../config+ '@supabase/supabase-js':+ specifier: 'catalog:'+ version: 2.117.2(@opentelemetry/[email protected])'@types/node':specifier: 20.19.39version: 20.19.39- dotenv:- specifier: 16.3.1- version: 16.3.1rimraf:specifier: 'catalog:'version: 5.0.10@@ -3876,16 +3881,13 @@ importers:version: 4.6.9tsup:specifier: 'catalog:'- version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])tsx:specifier: 'catalog:'version: 4.21.0typescript:specifier: 'catalog:'- version: 5.8.3- zod:- specifier: 'catalog:'- version: 4.5.4+ version: 7.1.0-betapackages/tiptap:dependencies:@@ -3922,9 +3924,6 @@ importers:'@tiptap/extension-link':specifier: 2.27.2- '@tiptap/extension-mention':- specifier: 2.27.2- version: 2.27.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))'@tiptap/extension-placeholder':specifier: 2.27.2@@ -3955,24 +3954,9 @@ importers:'@tiptap/suggestion':specifier: 2.27.2- '@types/node':- specifier: 22.19.7- version: 22.19.7cmdk:specifier: 0.2.0- cookie:- specifier: 'catalog:'- version: 1.1.1- dompurify:- specifier: 'catalog:'- version: 3.4.17- linkifyjs:- specifier: 4.3.2- version: 4.3.2- nanoid:- specifier: 'catalog:'- version: 5.1.16react-icons:specifier: 'catalog:'version: 5.6.0([email protected])@@ -4004,12 +3988,18 @@ importers:'@testing-library/dom':specifier: 8.20.1version: 8.20.1+ '@tiptap/extension-mention':+ specifier: 2.27.2+ version: 2.27.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))'@types/dompurify':specifier: 2.4.0version: 2.4.0'@types/forge-viewer':specifier: 7.99.3version: 7.99.3+ '@types/node':+ specifier: 22.19.7+ version: 22.19.7'@types/react':specifier: 18.3.28version: 18.3.28@@ -4019,6 +4009,18 @@ importers:'@types/react-window':specifier: 1.8.8version: 1.8.8+ cookie:+ specifier: 'catalog:'+ version: 1.1.1+ dompurify:+ specifier: 'catalog:'+ version: 3.4.17+ linkifyjs:+ specifier: 4.3.2+ version: 4.3.2+ nanoid:+ specifier: 'catalog:'+ version: 5.1.16react:specifier: 18.3.1version: 18.3.1@@ -4027,10 +4029,10 @@ importers:version: 4.6.9tsup:specifier: 'catalog:'- version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -4043,27 +4045,18 @@ importers:'@internationalized/date':specifier: 'catalog:'version: 3.12.0- '@supabase/supabase-js':- specifier: 'catalog:'- version: 2.117.2(@opentelemetry/[email protected])- '@tiptap/react':- specifier: 'catalog:'- version: 2.27.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])([email protected]([email protected]))([email protected])cookie:specifier: 'catalog:'version: 1.1.1- dompurify:- specifier: 'catalog:'- version: 3.4.17+ humanize-duration:+ specifier: 3.35.0+ version: 3.35.0intl-parse-accept-language:specifier: 'catalog:'version: 1.0.0lodash.template:specifier: 4.18.1version: 4.18.1- nanoid:- specifier: 'catalog:'- version: 5.1.16zod:specifier: 'catalog:'version: 4.5.4@@ -4071,6 +4064,12 @@ importers:'@carbon/config':specifier: workspace:*version: link:../config+ '@supabase/supabase-js':+ specifier: 'catalog:'+ version: 2.117.2(@opentelemetry/[email protected])+ '@tiptap/react':+ specifier: 'catalog:'+ version: 2.27.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])([email protected]([email protected]))([email protected])'@types/lodash.template':specifier: 4.5.3version: 4.5.3@@ -4080,9 +4079,12 @@ importers:'@types/react-dom':specifier: 18.3.7version: 18.3.7(@types/[email protected])- humanize-duration:- specifier: 3.35.0- version: 3.35.0+ dompurify:+ specifier: 'catalog:'+ version: 3.4.17+ nanoid:+ specifier: 'catalog:'+ version: 5.1.16react:specifier: 18.3.1version: 18.3.1@@ -4091,10 +4093,10 @@ importers:version: 4.6.9tsup:specifier: 'catalog:'- version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -4158,7 +4160,7 @@ importers:version: 18.3.1([email protected])typescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -4174,7 +4176,7 @@ importers:version: link:../configtypescript:specifier: 'catalog:'- version: 5.8.3+ version: 7.1.0-betavitest:specifier: 'catalog:'version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])@@ -10282,52 +10284,131 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==}- '@typescript/[email protected]':- resolution: {integrity: sha512-EwJEd6hfaHrrbSLat6+xX8fZiAvG+/Ae1gqvJEayTNdDbkrZxmeLS23YdjUmDMIOKI2wa7zXQDid8WtrvDfMTQ==}+ '@typescript/[email protected]':+ resolution: {integrity: sha512-DXDG+jIWxBHGdoO70tcHON33rCnSzsEZj9P13oyf/r/KEGIo6awsdSNVNjAw0uMwEpqRu75IrgCcW58YcVkZHg==}+ engines: {node: '>=16.20.0'}+ cpu: [ppc64]+ os: [aix]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-UZx6PxoQavuvaVTrSf3aw0Oy/J/uJpRylipA0kzc038jMvZXh0UtE8vnQp20FqtdgD5bhXZ0aJrRJyoTSUO58Q==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [android]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-q7mxblcyX0E7hXsY4k+Q6KWKK5mGmfVq+BDesdTgRVgjodk27aIxER77Zyj9+TgSTlCje8F7+JM6f6hl2BuNdw==}engines: {node: '>=16.20.0'}cpu: [arm64]os: [darwin]- '@typescript/[email protected]':- resolution: {integrity: sha512-tcS3gpivMq+BAiaupFqM5vuERykogJlfD4CjoxkSCksmmsKgWV96S2U/LjrKgll8R6/OEkg2VL2ycRG9+tIuHw==}+ '@typescript/[email protected]':+ resolution: {integrity: sha512-D5EYqG5Wm/guw9+0j8+Mn1Jbr/gfS/VtFTuoH8PJtFbcqeDaQGMulc7SW8q51QG6Y3wGOGX3nbsTOw6fIKWWAA==}engines: {node: '>=16.20.0'}cpu: [x64]os: [darwin]- '@typescript/[email protected]':- resolution: {integrity: sha512-m8IJTOneLXRtq6prLz8uuhp463kEt+AHV5Ceqp7G0o3eAvbKP059OwzK6WXCS5J0B3ZxX+BwBf9wDXSNidWJCw==}+ '@typescript/[email protected]':+ resolution: {integrity: sha512-9A0XX0tcnH9qPdolSKKzSjTb93dlB0UEcAJbHYEsrFX2fkFNSum9+dvkQQJ9vLc+7vxHetDPujq9Qe6wx+Xhow==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [freebsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-EDf/dBHfY0TxX3NmUTek0hbffeyZlh3+ls6WQW3ICB8vYxwYLFnzg7wkgEUvl9eRlpiJ/nmc2S8arPMzINJ7rg==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [freebsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-hNqQBgQ5b5oGqN76QqbAU6CwYhJZ6iOcWc2kPTUs2OentgpxZktETziH6KIyRFJPaiBncognwn2ZLu3DNhHiWw==}engines: {node: '>=16.20.0'}cpu: [arm64]os: [linux]- '@typescript/[email protected]':- resolution: {integrity: sha512-nluwnKcdGo6laWWYtWF3zFUDfi7nNrcD5S/T5382fVmtKmNqIdzFm9ANgSSGAavuzfdu9YJLaVWpx72Oe40AEQ==}+ '@typescript/[email protected]':+ resolution: {integrity: sha512-AvN9HmzOQh46G4312ooSgMHhbB7DtnLwg8D9mo324X49B7weMwtJrBG1MxT9IyI8kzDd7YRtW+1hWGun7WG7Qw==}engines: {node: '>=16.20.0'}cpu: [arm]os: [linux]- '@typescript/[email protected]':- resolution: {integrity: sha512-5ga94rso68kaxJUzaufDVhka1zPaSbPgNXaemQO8faPW0crvRIkbv0g8bpG4pdWMV0tTylmluDles4ZcAzOprg==}+ '@typescript/[email protected]':+ resolution: {integrity: sha512-xbUustlBrFflt2pNEyG5ye+d4WGPc/rfr2xK29MXeobPSw297JqwuKRrvbKM5o3fE/eUM/c+urVm6jQ3IaMVTw==}+ engines: {node: '>=16.20.0'}+ cpu: [loong64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-fS4/G7/0bXZ3NSq3nBMAXyg65I3tO4S7j08VNQ2g1aNC/qq79gE7Qne1BNjVsjMFfHBVBFjQYoTQCjmVU2iFlg==}+ engines: {node: '>=16.20.0'}+ cpu: [mips64el]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-0upCCxYPX8X6gOwkvfv+Ee7/ufyy7k97mTrGE0e5BxLlnUEa+w+rtgnv2dsKcxFdwdeZYVlZKCqgN/xCBV08+A==}+ engines: {node: '>=16.20.0'}+ cpu: [ppc64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-0jKU9YRgOPRgiy5V/UWv37kB53PaTpIbwGCbbOMUPPAkrjVRNOIAJaz7Wa7s3H7mdDebX1LopUEPEJR+7Xa7zg==}+ engines: {node: '>=16.20.0'}+ cpu: [riscv64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-j+d04s2kxaPQh6DLPb01sknAQfzsrdSZy15jBRHyLEZoaaQ19dVjbFRlkNVvYwUG7ZdP8+y5b/7RmPxdtHUKdQ==}+ engines: {node: '>=16.20.0'}+ cpu: [s390x]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-kcD51ihf+pnI5KT4uQQYG04OpwznaZYBlIQhDhl8fflFd27NktxXsUeguxZyvUMyWfum7IF2bBS6Jv7ox0AgFQ==}engines: {node: '>=16.20.0'}cpu: [x64]os: [linux]- '@typescript/[email protected]':- resolution: {integrity: sha512-YeRqOUuSyhbtryBSUE073OLpReIQXWJVyjP45gPLJ+0KAGvkd1VFz2FY1JEo++LyHoqXsGD2+qvdPpnTfSAIJg==}+ '@typescript/[email protected]':+ resolution: {integrity: sha512-8W85YyoGK+rgGoSU9jJQUpELbrKcZcbdJk2jPNQ6UKDKI7ryPlPFTrV2jCE5RQuv4Tt96hMDTc33s4YfRrLFBA==}engines: {node: '>=16.20.0'}cpu: [arm64]- os: [win32]+ os: [netbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-iGsTE0ve2PG0AcyZinwAR0LnGEZhu/y4dceS0hZsYCaKdYETvQtvtlNWlmYKempsBr6C7Il7dMXHVk+VFm9u0g==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [netbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-Z2FERdHB9fAKI+KGqdWn04O7uNlnB+VYiEm6INE1aZuzzLNd3KBqQ6IpKUJF2ny4GigGU6nVu75XD9tAUODPng==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [openbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-NVG3qeyCq/rJEOhaRjR3LsWgjrjo5vJW25omVLeHAVnpKIG4pE4cenwwKGR06DiJ1s0QTOymcJeKXMEpsiNBVg==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [openbsd]- '@typescript/[email protected]':- resolution: {integrity: sha512-WYNcbTaxCPgiDLrL2aPJ3BJA05nJU8DK0fUFGkGAER0oM+KcJcQUBeUkXg/7A4HBTNYcj7zIxqNgkJU1TRa/Kw==}+ '@typescript/[email protected]':+ resolution: {integrity: sha512-ovAdoWXEn2B5/fyWG69pLU3FWmQwPWOjQV5TFbcxtpnOv+R3g8ySGHl1NYRq7Lb/GYdFDvaGcZ+SiU7iKuiMsA==}engines: {node: '>=16.20.0'}cpu: [x64]+ os: [sunos]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-lJbo71IEOfL7ZZIZnArRaOLqjn9BAfoSzyUQn0aSjfSpDZL4ru0afUsdBfo6PQEjD6ssdmi0n/RwaPADX6bsvQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]os: [win32]- '@typescript/[email protected]':- resolution: {integrity: sha512-qyEHkEeRWCSGLa6a8oArnMPdn3Vcl1AZj8YHLO7lK0VjEEF/YJfz1FvxmpEeuhy0ZDfvJ7GtgXbvbjcU3zpPjQ==}+ '@typescript/[email protected]':+ resolution: {integrity: sha512-UKcHvbybY2tDTvFW2b1vwiAvDlIRooo69lh8CXWVhOQejcvpM5+IgbiFW9EIwR5Wi5X/v+BdN7gdWbigBuJ3rw==}engines: {node: '>=16.20.0'}- hasBin: true+ cpu: [x64]+ os: [win32]'@ungap/[email protected]':resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==}@@ -16182,6 +16263,11 @@ packages:engines: {node: '>=14.17'}hasBin: true+ resolution: {integrity: sha512-cjWjZAJDsmZzsNC5GwHNlW0YPM65jZa5oR0KyQcYX3KSVIfTvtBq//vewISyatKk4OLi5grZjHhIVE9fdrw1UQ==}+ engines: {node: '>=16.20.0'}+ hasBin: true+resolution: {integrity: sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==}@@ -18460,10 +18546,10 @@ snapshots:- babel-plugin-macros- supports-color- '@lingui/[email protected]([email protected])':+ '@lingui/[email protected]([email protected])':dependencies:'@babel/runtime': 7.29.2- cosmiconfig: 8.3.6([email protected])+ cosmiconfig: 8.3.6([email protected])jest-validate: 29.7.0jiti: 2.7.0picocolors: 1.1.1@@ -21814,7 +21900,7 @@ snapshots:'@react-pdf/primitives': 4.2.0'@react-pdf/stylesheet': 6.1.4- '@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])':+ '@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])':dependencies:'@babel/core': 7.29.6'@babel/generator': 7.29.1@@ -21823,7 +21909,7 @@ snapshots:'@babel/preset-typescript': 7.28.5(@babel/[email protected])'@babel/traverse': 7.29.0'@babel/types': 7.29.0- '@react-router/node': 7.18.4([email protected]([email protected]([email protected]))([email protected]))([email protected])+ '@react-router/node': 7.18.4([email protected]([email protected]([email protected]))([email protected]))([email protected])'@remix-run/node-fetch-server': 0.13.1arg: 5.0.2babel-dead-code-elimination: 1.0.12@@ -21843,12 +21929,12 @@ snapshots:semver: 7.7.4tinyglobby: 0.2.17- valibot: 1.4.2([email protected])+ valibot: 1.4.2([email protected])vite: 8.3.3(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vite-node: 3.2.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])optionalDependencies:- '@react-router/serve': 7.18.4([email protected]([email protected]([email protected]))([email protected]))([email protected])- typescript: 5.8.3+ '@react-router/serve': 7.18.4([email protected]([email protected]([email protected]))([email protected]))([email protected])+ typescript: 7.1.0-betatransitivePeerDependencies:- '@types/node'- babel-plugin-macros@@ -21864,7 +21950,7 @@ snapshots:- tsx- yaml- '@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])':+ '@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])':dependencies:'@babel/core': 7.29.6'@babel/generator': 7.29.1@@ -21873,7 +21959,7 @@ snapshots:'@babel/preset-typescript': 7.28.5(@babel/[email protected])'@babel/traverse': 7.29.0'@babel/types': 7.29.0- '@react-router/node': 7.18.4([email protected]([email protected]([email protected]))([email protected]))([email protected])+ '@react-router/node': 7.18.4([email protected]([email protected]([email protected]))([email protected]))([email protected])'@remix-run/node-fetch-server': 0.13.1arg: 5.0.2babel-dead-code-elimination: 1.0.12@@ -21893,12 +21979,12 @@ snapshots:semver: 7.7.4tinyglobby: 0.2.17- valibot: 1.4.2([email protected])+ valibot: 1.4.2([email protected])vite: 8.3.3(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vite-node: 3.2.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])optionalDependencies:- '@react-router/serve': 7.18.4([email protected]([email protected]([email protected]))([email protected]))([email protected])- typescript: 5.8.3+ '@react-router/serve': 7.18.4([email protected]([email protected]([email protected]))([email protected]))([email protected])+ typescript: 7.1.0-betatransitivePeerDependencies:- '@types/node'- babel-plugin-macros@@ -21914,46 +22000,46 @@ snapshots:- tsx- yaml- '@react-router/[email protected]([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])':+ '@react-router/[email protected]([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])':dependencies:- '@react-router/node': 7.18.4([email protected]([email protected]([email protected]))([email protected]))([email protected])+ '@react-router/node': 7.18.4([email protected]([email protected]([email protected]))([email protected]))([email protected])express: 4.22.3optionalDependencies:- typescript: 5.8.3+ typescript: 7.1.0-betaoptional: true- '@react-router/[email protected](@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':+ '@react-router/[email protected](@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':dependencies:- '@react-router/dev': 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ '@react-router/dev': 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])minimatch: 9.0.9optionalDependencies:- typescript: 5.8.3+ typescript: 7.1.0-beta- '@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected])':+ '@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected])':dependencies:'@mjackson/node-fetch-server': 0.2.0optionalDependencies:- typescript: 5.8.3+ typescript: 7.1.0-beta- '@react-router/[email protected](@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':+ '@react-router/[email protected](@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':dependencies:- '@react-router/dev': 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ '@react-router/dev': 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])optionalDependencies:- typescript: 5.8.3+ typescript: 7.1.0-beta- '@react-router/[email protected](@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':+ '@react-router/[email protected](@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':dependencies:- '@react-router/dev': 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ '@react-router/dev': 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])optionalDependencies:- typescript: 5.8.3+ typescript: 7.1.0-beta- '@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected])':+ '@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected])':dependencies:'@mjackson/node-fetch-server': 0.2.0- '@react-router/express': 7.18.4([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])- '@react-router/node': 7.18.4([email protected]([email protected]([email protected]))([email protected]))([email protected])+ '@react-router/express': 7.18.4([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])+ '@react-router/node': 7.18.4([email protected]([email protected]([email protected]))([email protected]))([email protected])compression: 1.8.2express: 4.22.3get-port: 5.1.1@@ -22437,7 +22523,7 @@ snapshots:'@remix-run/[email protected]': {}- '@remix-run/[email protected]([email protected])':+ '@remix-run/[email protected]([email protected])':dependencies:'@remix-run/router': 1.23.3'@types/cookie': 0.6.0@@ -22447,7 +22533,7 @@ snapshots:source-map: 0.7.6turbo-stream: 3.0.0optionalDependencies:- typescript: 5.8.3+ typescript: 7.1.0-beta'@rolldown/[email protected]':optional: true@@ -24091,36 +24177,68 @@ snapshots:dependencies:'@types/yargs-parser': 21.0.3- '@typescript/[email protected]':+ '@typescript/[email protected]':optional: true- '@typescript/[email protected]':+ '@typescript/[email protected]':optional: true- '@typescript/[email protected]':+ '@typescript/[email protected]':optional: true- '@typescript/[email protected]':+ '@typescript/[email protected]':optional: true- '@typescript/[email protected]':+ '@typescript/[email protected]':optional: true- '@typescript/[email protected]':+ '@typescript/[email protected]':optional: true- '@typescript/[email protected]':+ '@typescript/[email protected]':optional: true- '@typescript/[email protected]':- optionalDependencies:- '@typescript/native-preview-darwin-arm64': 7.0.0-dev.20260703.1- '@typescript/native-preview-darwin-x64': 7.0.0-dev.20260703.1- '@typescript/native-preview-linux-arm': 7.0.0-dev.20260703.1- '@typescript/native-preview-linux-arm64': 7.0.0-dev.20260703.1- '@typescript/native-preview-linux-x64': 7.0.0-dev.20260703.1- '@typescript/native-preview-win32-arm64': 7.0.0-dev.20260703.1- '@typescript/native-preview-win32-x64': 7.0.0-dev.20260703.1+ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true'@ungap/[email protected]': {}@@ -24173,10 +24291,10 @@ snapshots:'@vercel/cli-exec': 1.0.1jose: 5.10.0- '@vercel/[email protected](patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])':+ '@vercel/[email protected](patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])':dependencies:- '@react-router/dev': 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])- '@react-router/node': 7.18.4([email protected]([email protected]([email protected]))([email protected]))([email protected])+ '@react-router/dev': 7.18.4(patch_hash=26f651e284eca5bd3bc5389f089a09f3ae8d2dbb58b8b3bee0321aebb2960a03)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ '@react-router/node': 7.18.4([email protected]([email protected]([email protected]))([email protected]))([email protected])'@vercel/static-config': 3.2.0isbot: 5.1.37react: 18.3.1@@ -25143,14 +25261,14 @@ snapshots:yaml: 1.10.3optional: truedependencies:import-fresh: 3.3.1js-yaml: 4.3.2parse-json: 5.2.0path-type: 4.0.0optionalDependencies:- typescript: 5.8.3+ typescript: 7.1.0-beta@@ -26845,7 +26963,7 @@ snapshots:- [email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]):+ [email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]):dependencies:'@bufbuild/protobuf': 2.11.0'@inngest/ai': 0.1.7@@ -26878,13 +26996,13 @@ snapshots:fastify: 5.12.5hono: 4.13.7next: 15.5.28(@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])- typescript: 5.8.3+ typescript: 7.1.0-betatransitivePeerDependencies:- '@opentelemetry/core'- encoding- supports-color- [email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]):+ [email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]):dependencies:'@bufbuild/protobuf': 2.11.0'@inngest/ai': 0.1.7@@ -26917,7 +27035,7 @@ snapshots:fastify: 5.12.5hono: 4.13.7next: 15.5.28(@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])- typescript: 5.8.3+ typescript: 7.1.0-betatransitivePeerDependencies:- '@opentelemetry/core'- encoding@@ -27488,13 +27606,13 @@ snapshots:- [email protected](@types/[email protected])([email protected])([email protected])([email protected]):+ [email protected](@types/[email protected])([email protected])([email protected])([email protected]):dependencies:'@ai-sdk/anthropic': 1.2.12([email protected])'@ai-sdk/openai': 1.3.24([email protected])'@ai-sdk/openai-compatible': 0.2.16([email protected])- '@lingui/conf': 5.9.4([email protected])+ '@lingui/conf': 5.9.4([email protected])'@madeja-studio/cepillo': 0.7.1([email protected])([email protected])'@oclif/core': 4.11.7'@oclif/plugin-help': 6.2.50@@ -30925,7 +31043,7 @@ snapshots:- [email protected]([email protected])([email protected])([email protected])([email protected])([email protected]):+ [email protected]([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:bundle-require: 5.1.0([email protected])cac: 6.7.14@@ -30946,7 +31064,7 @@ snapshots:tree-kill: 1.2.2optionalDependencies:postcss: 8.5.29- typescript: 5.8.3+ typescript: 7.1.0-betatransitivePeerDependencies:- jiti- supports-color@@ -30981,6 +31099,34 @@ snapshots:- tsx- yaml+ [email protected]([email protected])([email protected])([email protected])([email protected])([email protected]):+ dependencies:+ bundle-require: 5.1.0([email protected])+ cac: 6.7.14+ chokidar: 4.0.3+ consola: 3.4.2+ debug: 4.4.3([email protected])+ esbuild: 0.27.7+ fix-dts-default-cjs-exports: 1.0.1+ joycon: 3.1.1+ picocolors: 1.1.1+ postcss-load-config: 6.0.1([email protected])([email protected])([email protected])([email protected])+ resolve-from: 5.0.0+ rollup: 4.60.1+ source-map: 0.7.6+ sucrase: 3.35.1+ tinyexec: 0.3.2+ tinyglobby: 0.2.17+ tree-kill: 1.2.2+ optionalDependencies:+ postcss: 8.5.29+ typescript: 7.1.0-beta+ transitivePeerDependencies:+ - jiti+ - supports-color+ - tsx+ - yaml+dependencies:esbuild: 0.27.7@@ -31084,6 +31230,30 @@ snapshots:+ optionalDependencies:+ '@typescript/typescript-aix-ppc64': 7.1.0-beta+ '@typescript/typescript-android-arm64': 7.1.0-beta+ '@typescript/typescript-darwin-arm64': 7.1.0-beta+ '@typescript/typescript-darwin-x64': 7.1.0-beta+ '@typescript/typescript-freebsd-arm64': 7.1.0-beta+ '@typescript/typescript-freebsd-x64': 7.1.0-beta+ '@typescript/typescript-linux-arm': 7.1.0-beta+ '@typescript/typescript-linux-arm64': 7.1.0-beta+ '@typescript/typescript-linux-loong64': 7.1.0-beta+ '@typescript/typescript-linux-mips64el': 7.1.0-beta+ '@typescript/typescript-linux-ppc64': 7.1.0-beta+ '@typescript/typescript-linux-riscv64': 7.1.0-beta+ '@typescript/typescript-linux-s390x': 7.1.0-beta+ '@typescript/typescript-linux-x64': 7.1.0-beta+ '@typescript/typescript-netbsd-arm64': 7.1.0-beta+ '@typescript/typescript-netbsd-x64': 7.1.0-beta+ '@typescript/typescript-openbsd-arm64': 7.1.0-beta+ '@typescript/typescript-openbsd-x64': 7.1.0-beta+ '@typescript/typescript-sunos-x64': 7.1.0-beta+ '@typescript/typescript-win32-arm64': 7.1.0-beta+ '@typescript/typescript-win32-x64': 7.1.0-beta+@@ -31228,9 +31398,9 @@ snapshots:optionalDependencies:- typescript: 5.8.3+ typescript: 7.1.0-betadependencies:diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex c53916b98f..6b7d262a91 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -129,7 +129,6 @@ catalog:'@tiptap/pm': 2.27.2'@tiptap/react': 2.27.2'@tiptap/starter-kit': 2.27.2- '@typescript/native-preview': '7.0.0-dev.20260703.1''@types/react': 18.3.28'@types/react-dom': 18.3.7'@types/node': '24'@@ -177,7 +176,7 @@ catalog:tailwindcss-animate: 1.0.7tsup: 8.5.1tsx: 4.21.0- typescript: 5.8.3+ typescript: 7.1.0-betavite: 8.3.3vitest: 4.1.11wait-on: 7.2.0diff --git a/scripts/lib/generate-db-types.test.ts b/scripts/lib/generate-db-types.test.tsdeleted file mode 100644index b5a6a2981d..0000000000--- a/scripts/lib/generate-db-types.test.ts+++ /dev/null@@ -1,230 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import assert from "node:assert/strict";-import { spawnSync } from "node:child_process";-import {- copyFileSync,- existsSync,- mkdirSync,- mkdtempSync,- readdirSync,- readFileSync,- realpathSync,- rmSync,- symlinkSync,- writeFileSync-} from "node:fs";-import { createRequire } from "node:module";-import { tmpdir } from "node:os";-import { dirname, join } from "node:path";-import { test } from "node:test";-import { fileURLToPath } from "node:url";-import {- sortRelationships,- stripPerTenantTables-} from "./generate-db-types";--const require = createRequire(import.meta.url);-const root = fileURLToPath(new URL("../../", import.meta.url));-const targets = ["packages/database/src/types.ts"] as const;-const original = "export type Database = { public: { Tables: {} } };\n";-const generated =- "export type Database = { public: { Tables: { example: {} } } };\n";--function runGenerator(- output: string,- options: {- exit?: number;- databaseUrl?: string;- missingExecutable?: boolean;- envFiles?: Record<string, string>;- } = {}-) {- const directory = realpathSync(- mkdtempSync(join(tmpdir(), "carbon-db-generation-"))- );- try {- for (const [file, content] of Object.entries(options.envFiles ?? {})) {- writeFileSync(join(directory, file), content);- }- for (const target of targets) {- mkdirSync(dirname(join(directory, target)), { recursive: true });- writeFileSync(join(directory, target), original);- }- mkdirSync(join(directory, "scripts/lib"), { recursive: true });- for (const file of [- "scripts/generate-db-types.ts",- "scripts/lib/generate-db-types.ts",- "scripts/lib/local-script-config.ts"- ]) {- copyFileSync(join(root, file), join(directory, file));- }- symlinkSync(- join(root, "node_modules"),- join(directory, "node_modules"),- "dir"- );- const bin = join(directory, "bin");- mkdirSync(bin);- const marker = join(directory, "invoked");- writeFileSync(join(directory, "output.txt"), output);- if (!options.missingExecutable) {- writeFileSync(- join(bin, "supabase"),- `#!${process.execPath}\nconst fs = require('node:fs');\nfs.writeFileSync(${JSON.stringify(marker)}, 'yes');\nfs.writeSync(1, fs.readFileSync(${JSON.stringify(join(directory, "output.txt"))}));\nprocess.exit(${options.exit ?? 0});\n`,- { mode: 0o755 }- );- }- const result = spawnSync(- process.execPath,- ["--import", require.resolve("tsx"), join(directory, "scripts/generate-db-types.ts")],- {- cwd: directory,- encoding: "utf8",- timeout: 20_000,- env: {- ...process.env,- NODE_PATH: undefined,- PATH: bin,- SUPABASE_DB_URL:- options.databaseUrl ??- "postgresql://example:[email protected]:5432/example"- }- }- );- return {- ...result,- invoked: existsSync(marker),- contents: targets.map((target) =>- readFileSync(join(directory, target), "utf8")- ),- remaining: targets.map((target) =>- readdirSync(dirname(join(directory, target)))- )- };- } finally {- rmSync(directory, { recursive: true, force: true });- }-}--test("default .env preserves the caller's database URL", () => {- const result = runGenerator(generated, {- envFiles: {- ".env": "SUPABASE_DB_URL=postgresql://external.example.com/database\n"- }- });- assert.equal(result.status, 0, result.stderr);- assert.equal(result.invoked, true);-});--test(".env.local overrides the caller's URL before the local-host safety check", () => {- const result = runGenerator(generated, {- envFiles: {- ".env.local":- "SUPABASE_DB_URL=postgresql://external.example.com/database\n"- }- });- assert.notEqual(result.status, 0);- assert.equal(result.invoked, false);- assert.deepEqual(result.contents, [original]);-});--test("failed subprocess preserves the last-good output and cleans temporary files", () => {- const result = runGenerator("partial output", { exit: 7 });- assert.equal(result.invoked, true, result.stderr);- assert.notEqual(result.status, 0);- assert.deepEqual(result.contents, [original]);- assert.deepEqual(result.remaining, [["types.ts"]]);-});--test("missing generator executable preserves the last-good output", () => {- const result = runGenerator(generated, { missingExecutable: true });- assert.notEqual(result.status, 0);- assert.deepEqual(result.contents, [original]);- assert.deepEqual(result.remaining, [["types.ts"]]);-});--for (const output of ["", " \n", "export const unrelated = 42;", "type Database = {};"]) {- test(`rejects unusable successful output (${JSON.stringify(output)})`, () => {- const result = runGenerator(output);- assert.equal(result.invoked, true, result.stderr);- assert.notEqual(result.status, 0);- assert.deepEqual(result.contents, [original]);- assert.deepEqual(result.remaining, [["types.ts"]]);- });-}--for (const databaseUrl of [- "postgresql://localhost:[email protected]/example",- "postgresql://example:[email protected]/example",- "postgresql://example:[email protected]/localhost",- "http://example:synthetic-secret@localhost/example",- "postgresql://example:synthetic-secret@localhost/example?host=example.com",- "postgresql://example:synthetic-secret@localhost/example?hostaddr=192.0.2.1",- "not-a-database-url"-]) {- test(`rejects a malformed or non-local database URL (${databaseUrl.split(":")[0]})`, () => {- const result = runGenerator(generated, { databaseUrl });- assert.notEqual(result.status, 0);- assert.equal(result.invoked, false);- assert.deepEqual(result.contents, [original]);- assert.doesNotMatch(- result.stdout + result.stderr,- /synthetic-secret|example\.com/- );- });-}--for (const host of ["localhost", "127.0.0.1", "[::1]"]) {- test(`publishes identical validated outputs for local host ${host}`, () => {- const result = runGenerator(generated, {- databaseUrl: `postgresql://example:synthetic@${host}:5432/example`- });- assert.equal(result.status, 0, result.stderr);- assert.deepEqual(result.contents, [generated]);- assert.deepEqual(result.remaining, [["types.ts"]]);- });-}--test("MCP generation does not cache incomplete transitive input coverage", () => {- const turbo = JSON.parse(readFileSync(join(root, "turbo.json"), "utf8"));- assert.equal(turbo.tasks["//#generate:mcp"].cache, false);-});--test("sortRelationships orders each Relationships block deterministically", () => {- const block = (entries: string[]) =>- [" x: {", " Relationships: [", ...entries, " ]", " }"].join("\n");- const entry = (fk: string, col: string, last = false) =>- [- " {",- ` foreignKeyName: "${fk}"`,- ` columns: ["${col}"]`,- " isOneToOne: false",- ' referencedRelation: "country"',- ' referencedColumns: ["code"]',- last ? " }" : " },"- ].join("\n");- const a = block([entry("x_fkey", "supplierCountryCode"), entry("x_fkey", "customerCountryCode", true)]);- const b = block([entry("x_fkey", "customerCountryCode"), entry("x_fkey", "supplierCountryCode", true)]);- assert.equal(sortRelationships(a), sortRelationships(b));- assert.equal(sortRelationships(a), b, "sorted output keeps a trailing comma on every entry but the last");- assert.equal(sortRelationships(" Relationships: []\n }"), " Relationships: []\n }");-});--test("strips per-tenant tables, including company ids that need quoting", () => {- const table = (name: string) =>- [` ${name}: {`, " Row: {}", " }"].join("\n");- const source = [- table("searchIndexRegistry"),- table("searchIndex_dal7910g60gg2egcfj40"),- table('"searchIndex_accttest-08e7f74786d6-company"'),- table('"auditLog_accttest-08e7f74786d6-company"'),- table("auditLogArchive")- ].join("\n");- assert.equal(- stripPerTenantTables(source),- [table("searchIndexRegistry"), table("auditLogArchive")].join("\n")- );-});diff --git a/scripts/lib/generate-db-types.ts b/scripts/lib/generate-db-types.tsindex c680ce34a7..00a86a7433 100644--- a/scripts/lib/generate-db-types.ts+++ b/scripts/lib/generate-db-types.ts@@ -14,7 +14,7 @@ import {} from "node:fs";import { dirname, join, resolve } from "node:path";-function validateDatabaseUrl(value: string | undefined): string {+export function validateDatabaseUrl(value: string | undefined): string {if (!value?.trim()) {throw new Error("SUPABASE_DB_URL is not set. Configure the local database before generating types."@@ -75,7 +75,7 @@ export function sortRelationships(source: string): string {const lines = source.split("\n");const out: string[] = [];for (let i = 0; i < lines.length; i++) {- const line = lines[i];+ const line = lines[i] ?? "";out.push(line);if (!/^\s*Relationships: \[$/.test(line)) continue;const indent = line.match(/^\s*/)?.[0] ?? "";@@ -83,24 +83,24 @@ export function sortRelationships(source: string): string {let j = i + 1;while (j < lines.length && lines[j] !== `${indent}]`) {if (lines[j] === `${indent} {`) {- const entry = [lines[j]];+ const entry = [lines[j] ?? ""];j++;- while (j < lines.length && !/^\s*\},?$/.test(lines[j]))- entry.push(lines[j++]);- entry.push(lines[j]);+ while (j < lines.length && !/^\s*\},?$/.test(lines[j] ?? ""))+ entry.push(lines[j++] ?? "");+ entry.push(lines[j] ?? "");entries.push(entry);}j++;}if (j >= lines.length) continue;- const closing = lines[j];+ const closing = lines[j] ?? "";entries.sort((a, b) => {const ka = a.slice(1, -1).join("\n");const kb = b.slice(1, -1).join("\n");return ka < kb ? -1 : ka > kb ? 1 : 0;});entries.forEach((entry, index) => {- const last = entry[entry.length - 1].replace(/,$/, "");+ const last = (entry[entry.length - 1] ?? "").replace(/,$/, "");out.push(...entry.slice(0, -1),index < entries.length - 1 ? `${last},` : lastdiff --git a/scripts/lib/local-script-config.test.ts b/scripts/lib/local-script-config.test.tsdeleted file mode 100644index e80f63c152..0000000000--- a/scripts/lib/local-script-config.test.ts+++ /dev/null@@ -1,117 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import assert from "node:assert/strict";-import { spawnSync } from "node:child_process";-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";-import { createRequire } from "node:module";-import { tmpdir } from "node:os";-import { join, resolve } from "node:path";-import { test } from "node:test";-import { pathToFileURL } from "node:url";-import { readLocalScriptConfig } from "./local-script-config";--test("readLocalScriptConfig returns the requested values from the environment", () => {- const config = readLocalScriptConfig(["A_KEY", "B_KEY"], {- A_KEY: "a",- B_KEY: "b",- C_KEY: "ignored"- });- assert.deepEqual(config, { A_KEY: "a", B_KEY: "b" });-});--test("readLocalScriptConfig names missing keys without disclosing configured values", () => {- assert.throws(- () =>- readLocalScriptConfig(["A_KEY", "B_KEY", "C_KEY"], {- A_KEY: "private-value-sentinel",- B_KEY: " "- }),- (error: Error) => {- assert.match(error.message, /B_KEY/);- assert.match(error.message, /C_KEY/);- assert.doesNotMatch(error.message, /private-value-sentinel/);- return true;- }- );-});--for (const script of ["sandbox", "model-upload", "sales-invoice-report"]) {- test(`${script} CLI reaches its configuration error with NODE_PATH unset`, () => {- const directory = mkdtempSync(join(tmpdir(), "carbon-script-config-"));- try {- const result = spawnSync(- process.execPath,- [- "--import",- createRequire(import.meta.url).resolve("tsx"),- resolve(`scripts/${script}.ts`)- ],- { cwd: directory, env: {}, encoding: "utf8", timeout: 15_000 }- );- assert(result.status === 1, "Missing configuration must fail the CLI");- assert(- result.stderr.includes("Missing required local configuration"),- "CLI must reach the configuration guard before any dependency or IO error"- );- assert(!result.stderr.includes("ERR_MODULE_NOT_FOUND"));- } finally {- rmSync(directory, { recursive: true, force: true });- }- });-}--test("real .env parser and pinned SDK load without root dependency aliases or network", () => {- const directory = mkdtempSync(join(tmpdir(), "carbon-script-client-"));- try {- writeFileSync(- join(directory, ".env"),- 'SUPABASE_URL="https://database.example.com"\nCARBON_API_KEY="fixture-api-key"\n'- );- writeFileSync(- join(directory, ".env.local"),- 'CARBON_API_KEY="fixture-local-override"\n'- );- const result = spawnSync(- process.execPath,- [- "--import",- createRequire(import.meta.url).resolve("tsx"),- "--input-type=module",- "--eval",- `import assert from "node:assert/strict";-import helpers from ${JSON.stringify(- pathToFileURL(resolve("scripts/lib/local-script-config.ts")).href- )};-const { createScriptClient, readLocalScriptConfig } = helpers;-const config = readLocalScriptConfig(- ["SUPABASE_URL", "SUPABASE_ANON_KEY", "CARBON_API_KEY"],- { SUPABASE_ANON_KEY: "fixture-public-key", CARBON_API_KEY: "fixture-environment" }-);-let calls = 0;-globalThis.fetch = async (input, init) => {- calls += 1;- assert(String(input).startsWith("https://database.example.com/rest/v1/fixture"));- assert(new Headers(init.headers).get("carbon-key") === "fixture-local-override");- return new Response('[{"id":"fixture"}]', {- status: 200,- headers: { "content-type": "application/json" }- });-};-const client = createScriptClient(config.SUPABASE_URL, config.SUPABASE_ANON_KEY, config.CARBON_API_KEY);-const result = await client.from("fixture").select("*");-assert.equal(result.error, null);-assert.equal(result.data[0].id, "fixture");-assert.equal(calls, 1);`- ],- { cwd: directory, env: {}, encoding: "utf8", timeout: 15_000 }- );- assert(- result.status === 0,- "Real environment parsing, pinned SDK resolution, and stubbed request must succeed"- );- } finally {- rmSync(directory, { recursive: true, force: true });- }-});diff --git a/scripts/lib/swagger-schema.test.ts b/scripts/lib/swagger-schema.test.tsdeleted file mode 100644index f5d9a3439e..0000000000--- a/scripts/lib/swagger-schema.test.ts+++ /dev/null@@ -1,153 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import assert from "node:assert/strict";-import { spawn } from "node:child_process";-import {- copyFileSync,- mkdirSync,- mkdtempSync,- readdirSync,- readFileSync,- rmSync,- writeFileSync-} from "node:fs";-import { createServer } from "node:http";-import { tmpdir } from "node:os";-import { dirname, join } from "node:path";-import { test } from "node:test";-import { fileURLToPath } from "node:url";-import { normalizeSwaggerSchema } from "./swagger-schema";--const pk = "This is a Primary Key.<pk/>";-const fk =- "This is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>";-const fixture = (chosen: "id" | "supplierLocationId") => ({- swagger: "2.0",- definitions: {- partners: {- properties: {- id: {- type: "string",- format: "text",- description: `Original id documentation.\n\nNote:\n${chosen === "id" ? `${pk}\n` : ""}${fk}`- },- supplierLocationId: {- type: "string",- format: "text",- description: `Alias documentation.\n\nNote:\n${chosen === "supplierLocationId" ? `${pk}\n` : ""}${fk}`- }- }- },- unrelated: { properties: { id: { description: `Leave untouched: ${pk}` } } }- },- paths: { "/partners": { get: { description: "Public API contract" } } }-});--test("both observed alias choices normalize to identical metadata", () => {- assert.deepEqual(- normalizeSwaggerSchema(fixture("supplierLocationId")),- fixture("id")- );- assert.deepEqual(normalizeSwaggerSchema(fixture("id")), fixture("id"));-});--test("keeps the alias note when id has no Note anchor to receive it", () => {- const input = fixture("supplierLocationId");- input.definitions.partners.properties.id.description = "No note block here.";- assert.deepEqual(normalizeSwaggerSchema(input), input);-});--test("normalization is idempotent and leaves the input object intact", () => {- const input = fixture("supplierLocationId");- const saved = structuredClone(input);- const first = normalizeSwaggerSchema(input);- assert.deepEqual(first, normalizeSwaggerSchema(first));- assert.deepEqual(input, saved);-});--async function runCli(options: { failStatus?: number; repeat?: boolean } = {}) {- const root = fileURLToPath(new URL("../../", import.meta.url));- const directory = mkdtempSync(join(tmpdir(), "carbon-swagger-generation-"));- const output = join(directory, "packages/database/src/swagger-docs-schema.ts");- const previous = "export default { previous: true };\n";- let generations = 0;- const server = createServer((request, response) => {- response.setHeader("Content-Type", "application/json");- if (options.failStatus) {- response.statusCode = options.failStatus;- response.end(JSON.stringify({ error: "synthetic-private-diagnostic" }));- return;- }- response.end(- JSON.stringify(- fixture(generations++ % 2 === 0 ? "supplierLocationId" : "id")- )- );- });- try {- await new Promise<void>((resolve) =>- server.listen(0, "127.0.0.1", resolve)- );- const address = server.address();- assert.ok(address && typeof address !== "string");- mkdirSync(dirname(output), { recursive: true });- writeFileSync(output, previous);- mkdirSync(join(directory, "scripts/lib"), { recursive: true });- for (const path of [- "scripts/generate-swagger-docs.ts",- "scripts/lib/swagger-schema.ts",- "scripts/lib/local-script-config.ts"- ])- copyFileSync(join(root, path), join(directory, path));- const results = [];- for (let iteration = 0; iteration < (options.repeat ? 2 : 1); iteration++) {- const child = spawn(- process.execPath,- [- "--import",- join(root, "node_modules/tsx/dist/loader.mjs"),- join(directory, "scripts/generate-swagger-docs.ts")- ],- {- cwd: directory,- env: {- PATH: process.env.PATH,- PORT_STUDIO: String(address.port),- NODE_PATH: undefined- },- stdio: ["ignore", "pipe", "pipe"]- }- );- let stderr = "";- child.stderr.on("data", (chunk) => {- stderr += chunk;- });- const code = await new Promise<number | null>((resolve, reject) => {- child.once("error", reject);- child.once("close", resolve);- });- results.push({ code, stderr, output: readFileSync(output, "utf8") });- }- return { results, previous, remaining: readdirSync(dirname(output)) };- } finally {- await new Promise<void>((resolve) => server.close(() => resolve()));- rmSync(directory, { recursive: true, force: true });- }-}--test("real CLI produces identical files for both observed alias variants", async () => {- const result = await runCli({ repeat: true });- for (const run of result.results) assert.equal(run.code, 0, run.stderr);- assert.equal(result.results[0]!.output, result.results[1]!.output);- assert.deepEqual(result.remaining, ["swagger-docs-schema.ts"]);-});--test("real CLI preserves last-good output when the request fails", async () => {- const result = await runCli({ failStatus: 500 });- assert.notEqual(result.results[0]!.code, 0);- assert.equal(result.results[0]!.output, result.previous);- assert.deepEqual(result.remaining, ["swagger-docs-schema.ts"]);- assert.doesNotMatch(result.results[0]!.stderr, /synthetic/);-});