Skip to content

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.

fix(items): create a make method version and its copy in one transaction (#1965)

Naveen Kashyap37f71945a4dc
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 78d7b3fe01..bce4c0141e 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -4040,6 +4040,16 @@ The write was then removed (nothing reads it), so the rail always starts collaps
**Applies to:** `postReceipt` / `postShipment` and every posting in `inventory.service.ts` that builds update maps before its write loop.
+## A header and the get-method copy into it share one transaction
+
+**Context:** New Version on a make method inserted the `makeMethod` header through supabase-js, set the source version Active, then ran get-method's `makeMethodToMakeMethod` copy, which opened its own Kysely transaction. A version change notice and the Onshape panel's Draft did the same in their own code.
+
+**Problem:** When the copy failed it rolled back only its own rows. The empty Draft stayed, numbered above a source that was now Active and read-only. A first fix deleted them again after the failure; that cleanup could fail too, and it needed a delete the caller may not be allowed to make.
+
+**Rule:** Put the header insert, any status change and the copy in ONE Kysely transaction and pass the transaction to `copyMakeMethod` as `db`. A function that may be handed a transaction opens its own through `withTransaction` (`@carbon/database/client`), never `db.transaction()`: Kysely refuses `transaction()` on a `Transaction`. Every get-method body, and `createMakeMethodVersion` itself, joins that way, so a caller can add its own writes to the same commit (the change notice writes its `changeOrderId` in the insert; the Onshape Draft adds its line ownership and marker) instead of a second write after the commit that can fail alone. Kysely bypasses RLS, so check the policy's permission through the caller's client first (`requireCompanyPermission`), as `createRevision` does.
+
+**Applies to:** `createMakeMethodVersion` (`items.service.ts`) and its callers (`createMethodVersion`, `createChangeNoticeDraftMethod`, `ensureDraftMakeMethod`); any other header insert followed by a get-method copy (quote and job duplication, revisions).
+
## An import wizard enum Default fills every blank cell before the server sees it
**Context:** The method import (#1977) was made to fill a blank BOM Unit of Measure with the material's own unit and a blank Operation Type with the process's type, as the BOM and BOP editors do.
diff --git a/.ai/playbooks/make-method-new-version.md b/.ai/playbooks/make-method-new-version.md
new file mode 100644
index 0000000000..ca1935a63e
--- /dev/null
+++ b/.ai/playbooks/make-method-new-version.md
@@ -0,0 +1,56 @@
+# Make Method — New Version, Version change notice, Get Method
+
+Last tested: 2026-10-22
+Routes: /x/part/{itemId}/details?methodId={makeMethodId} · /x/change-notice/new · /x/items/change-notice/{id}/details
+
+## Prerequisites
+- The satellite demo dataset (`pnpm db:seed:dev --dataset satellite`). Useful parts:
+ - a Make part whose only version is a Draft with BoM + BoP (COMMS-001 had v1 Draft, 3 materials, 2 operations);
+ - a Make part with an Active v1 (EPS-001, ADCS-001).
+
+## Steps
+### 1. New Version from the only (Draft) version
+- Open the part's details page. The version button reads `V1 Draft`; click it → menu item **New Version**.
+- The modal warns "This will set the current version of the make method to Active". Hidden inputs: `copyFromId` = `activeVersionId` = the current method id, `version` = max + 1.
+- `requestSubmit` the form whose button reads "Create Version" (NOT a click).
+- Verify: the URL gets `?methodId=<new id>`, the button reads `V2 Draft`. In the DB the source is Active and the new Draft has the same material, operation and step counts.
+
+### 2. New Version from an Active version
+- Open `?methodId=<v1 id>` (button `V1 Active`) → **New Version**. `activeVersionId` is empty (only sent when the item has one method).
+- Verify: v1 stays Active, the new Draft has v1's counts.
+
+### 3. Version change notice
+- `/x/change-notice/new` → fill the first textbox (Name) → `requestSubmit` "Save" → redirects to `/x/items/change-notice/{id}/details`.
+- **Add Affected Item** → Change Type stays `Version` → open the second combobox, type the part number, click the option → `requestSubmit` "Add".
+- Verify: lands on `/{id}/{affectedId}/details` with the Bill of Process and Bill of Material of the draft. In the DB the draft is `max(version)+1`, `changeOrderId` = the notice, counts match the Active base.
+
+### 4. Get Method into a Draft version (regression)
+- On a Draft version click **Get Method** → first combobox: type the source part, pick it → second combobox: pick its version → `requestSubmit` "Confirm".
+- Verify: the Draft's lines are replaced by the source's.
+
+### 5. A failed copy leaves nothing (the atomicity check)
+- Make the copy fail with a temporary trigger (drop it afterwards; check `pg_trigger` is clean):
+ `CREATE FUNCTION test_fail_op_copy() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'operation copy refused (test)'; END $$;`
+ `CREATE TRIGGER test_fail_op_copy BEFORE INSERT ON "methodOperation" FOR EACH ROW WHEN (NEW."companyId" = '<companyId>') EXECUTE FUNCTION test_fail_op_copy();`
+ (`methodOperationStepSlide` only fires when the source has steps; the satellite methods have none.)
+- New Version on a part whose only version is a Draft → `requestSubmit` "Create Version".
+- Verify: toast "Failed to create new version", the URL keeps no `methodId` of a new version, the DB has no new row and the source is still Draft. Drop the trigger; New Version then succeeds with the SAME version number (nothing held it).
+
+## Selector Notes
+- The version button is `button "V<n> <Status>"`; its menu has "Version N …", "New Version", "New Change Notice".
+- Item pickers: click the combobox, `agent-browser keyboard type "<part number>"`, then click the `option`.
+- Read hidden form values with `[...document.querySelectorAll('[role=dialog] form input')]`.
+
+## DB verification
+```sql
+select m.version, m.status, m."changeOrderId",
+ (select count(*) from "methodMaterial" x where x."makeMethodId" = m.id) as bom,
+ (select count(*) from "methodOperation" x where x."makeMethodId" = m.id) as ops
+from "makeMethod" m where m."itemId" = '<itemId>' order by m.version;
+```
+
+## Common Failures
+- `agent-browser screenshot .context/x.png` with a relative path saves nowhere useful: pass an absolute path.
+- No `psql` on the host: query with `pg` from `packages/database` (`node -e` / a small script) and `SUPABASE_DB_URL` from `.env.local` (the shell exports another stack's).
+- Portless URLs need `NODE_EXTRA_CA_CERTS=~/.portless/ca.pem` for scripts; the browser works as is.
+- `crbn up --no-portless` pins port 54321 and fails when another worktree's localhost stack holds it; use portless mode.
diff --git a/.ai/research/2026-10-09-service-function-inventory.md b/.ai/research/2026-10-09-service-function-inventory.md
index 7425ebccbb..80bdfb84f4 100644
--- a/.ai/research/2026-10-09-service-function-inventory.md
+++ b/.ai/research/2026-10-09-service-function-inventory.md
@@ -319,7 +319,7 @@ Each row is an action whose logic lives in the route today: it makes two or more
| `items.material.purchasing.create` | `x+/material+/$itemId.purchasing.new.tsx` | `upsertSupplierPart`; 1 direct write | 68 |
| `items.methods.get` | `x+/items+/methods+/get.tsx` | `copyItem`, `copyMakeMethod` | 54 |
| `items.methods.save` | `x+/items+/methods+/save.tsx` | `copyItem`, `copyMakeMethod` | 54 |
-| `items.methods.version.create` | `x+/items+/methods+/version.new.tsx` | `copyMakeMethod`, `upsertMakeMethodVersion` | 73 |
+| `items.methods.version.create` | `x+/items+/methods+/version.new.tsx` | `createMakeMethodVersion` (which copies through `copyMakeMethod`) | 73 |
| `items.part.create` | `x+/part+/new.tsx` | `upsertPart`; event | 49 |
| `items.part.purchasing.create` | `x+/part+/$itemId.purchasing.new.tsx` | `upsertSupplierPart`; 1 direct write | 71 |
| `items.part.sales` | `x+/part+/$itemId.sales.tsx` | `upsertItemRentalRate`, `upsertItemUnitSalePrice` | 74 |
@@ -1175,7 +1175,7 @@ These already exist and a route calls each one directly. Under the pattern they
| `upsertConfigurationParameterGroup` | `items.configurationParameterGroup.upsert` | | 1 | upsert | `items.service.ts` |
| `upsertConfigurationRule` | `items.configurationRule.upsert` | | 1 | upsert | `items.service.ts` |
| `upsertItemSupersession` | `items.itemSupersession.upsert` | | 1 | upsert | `items.service.ts` |
-| `upsertMakeMethodVersion` | `items.makeMethodVersion.upsert` | | 1 | upsert | `items.service.ts` |
+| `createMakeMethodVersion` | `items.makeMethodVersion.create` | | 1 | create | `items.service.ts` |
| `upsertMethodOperationStepSlide` | `items.methodOperationStepSlide.upsert` | | 1 | upsert | `items.service.ts` |
</details>
diff --git a/.claude/rules/database-patterns.md b/.claude/rules/database-patterns.md
index 430e6b99e2..d0003c941d 100644
--- a/.claude/rules/database-patterns.md
+++ b/.claude/rules/database-patterns.md
@@ -291,6 +291,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
- Never query inside a loop — one set-based statement (`UPDATE … FROM (VALUES …)`, `.in()`, a
join) per logical write.
- Single writes are already atomic — don't reach for a transaction.
+- A building block that may be handed a transaction opens its own with `withTransaction(db, fn)`
+ (`@carbon/database/client`), never `db.transaction()`: Kysely refuses `transaction()` on a
+ `Transaction`, and joining lets the caller commit its own writes with it
+ (`createMakeMethodVersion`, every `getMethod` body).
- Kysely auto-quotes reserved column names (e.g. `order`), so `.set({ order: sortOrder })` is
safe; in raw `sql`, use `sql.ref(column)`.
diff --git a/.claude/rules/onshape-panel.md b/.claude/rules/onshape-panel.md
index 13dc309716..3d693f412b 100644
--- a/.claude/rules/onshape-panel.md
+++ b/.claude/rules/onshape-panel.md
@@ -77,7 +77,7 @@ Every push is two requests. PLAN (`api+/integrations.onshape.panel.plan-{part,as
- BOM lines take only Part, Material or Consumable items (`BOM_LINE_ITEM_TYPES`). The plan lists a part number Carbon holds as another type under `skipped`; apply reports it as an error.
- Assembly BOM pushes are a diff. An owned line (one a previous push wrote, per its mapping row) is updated in place (`quantity`, `order`, `materialMakeMethodId`) or skipped when those match; owned lines Onshape no longer lists are deleted with their mappings. New lines and their mapping rows are inserted in one Kysely transaction (`insertOwnedMethodLines`, `modules/settings/settings.service.ts`; a count mismatch rolls back).
- A manual line for a part number Onshape also lists is taken over (`pairManualLines` in `plan.ts`, applied by `claimManualMethodLine`): Onshape's quantity, order and child method, its operation and scrap kept. Only a line whose `itemType` matches is taken over. Other manual lines are left alone.
-- Active make methods are never edited. An Active method whose lines already match Onshape's is left as is. The plan marks it `unchanged` when part numbers and quantities match in order with nothing taken over and no reusable Draft; apply decides again (`linesWouldChange`): owned lines paired by item id (FIFO), each with the same `quantity`, `order` and `materialMakeMethodId` (the child method apply resolves), and no owned line left over. Otherwise the push writes into a Draft (`ensureDraftMakeMethod`, `modules/settings/settings.service.ts`). It reuses a Draft only when the panel made it from the current Active method and no change notice holds it (`pickReusableDraft`); otherwise it makes version `max(version) + 1`, copies through `copyMakeMethod` and carries ownership with `pairOwnedCopiedLines`. The marker row is written last; if the copy, the carry or the marker fails, the service role deletes the new Draft (`externalIntegrationMapping` has no user DELETE policy). The assembly plan loads the reusable Draft (`loadReusableDrafts`), so the review names the Draft the push writes into.
+- Active make methods are never edited. An Active method whose lines already match Onshape's is left as is. The plan marks it `unchanged` when part numbers and quantities match in order with nothing taken over and no reusable Draft; apply decides again (`linesWouldChange`): owned lines paired by item id (FIFO), each with the same `quantity`, `order` and `materialMakeMethodId` (the child method apply resolves), and no owned line left over. Otherwise the push writes into a Draft (`ensureDraftMakeMethod`, `modules/settings/settings.service.ts`). It reuses a Draft only when the panel made it from the current Active method and no change notice holds it (`pickReusableDraft`); otherwise it makes version `max(version) + 1` through `createMakeMethodVersion`, which copies the BOM and routing as the system (a parts user need not hold production update). The Draft, its copy, the ownership carried with `pairOwnedCopiedLines` (`carryLineOwnership`, which reads the copied lines in the same transaction) and the marker row are one Kysely transaction, so any failure leaves no Draft. The assembly plan loads the reusable Draft (`loadReusableDrafts`), so the review names the Draft the push writes into.
- With no Active method, `activeMakeMethods` returns the newest Draft, which can be a change notice's; `loadActiveMakeMethods` reads its `changeOrderId` from `makeMethod`. `loadMethodWriteRefusals` (`modules/settings/settings.service.ts`) refuses a change notice's Draft whatever the notice's stage, and a released (Production) revision when `plmReleaseControl` is `enforce` (`getLockVerdict`, the verdict `checkRevisionLock` gives the BOM editor). Plan drops those methods into `skipped` with the reason (`withRefusedMethods`; an `unchanged` Active method is not refused). Apply checks again before it makes a Draft and reports a refusal under `skipped`.
- Every delete is scoped by `companyId`. Never build a PostgREST `.or()` string from CAD values.
- Item page: one mount point, `ExternalSourceCard` in `x+/part+/$itemId.details.tsx`. It shows the fields a push replaces (`everyPushTargets`), last push time, Open in Onshape and Detach (`api+/integrations.onshape.detach` deletes the item's `onshape-v2` row only). A later push can link the item again by part number.
diff --git a/.claude/rules/revision-system.md b/.claude/rules/revision-system.md
index cfca075323..759f4ed0a5 100644
--- a/.claude/rules/revision-system.md
+++ b/.claude/rules/revision-system.md
@@ -64,8 +64,10 @@ the type-scoped `revisions` array.
revision label. After the commit, if `replenishmentSystem !== "Buy"`, it calls
`getMethod` (`production.service.ts`, ported from the `get-method` server function) (`~/modules/production/production.service`,
`type: "itemToItem"`) to copy the method/BOM from source to the new revision.
- That call runs its own transaction, so it cannot join this one: a failure is
- logged and the revision stands (the method can be copied again). Three callers, one behaviour: the New Revision
+ That call runs after the commit, in its own transaction: a failure is
+ logged and the revision stands (the method can be copied again). get-method
+ would now join a transaction it is handed (`withTransaction`), so the copy
+ could move inside; it has not been. Three callers, one behaviour: the New Revision
route, material sizes (`upsertMaterial`), and a change notice's Revision draft
(`createChangeNoticeDraftMethod`, `active: false`).
- **Authorization.** Kysely bypasses RLS, so before the transaction
diff --git a/apps/erp/app/modules/items/AGENTS.md b/apps/erp/app/modules/items/AGENTS.md
index 801779e4a6..a49cafc15b 100644
--- a/apps/erp/app/modules/items/AGENTS.md
+++ b/apps/erp/app/modules/items/AGENTS.md
@@ -67,6 +67,7 @@ pnpm --filter erp test
- `updateMaterialProperties(client, db, material)` — the one path for substance/form/type/finish/grade/dimension changes (properties panel, `upsertMaterial`, MCP): dependent resets, pick-list checks, generated-ID renames in one transaction. See `.claude/rules/material-tables.md`
- `getMakeMethods` / `getMethodMaterials` / `getMethodOperations` / `getMethodTreeArray` — BOM/routing reads
- `copyItem` / `copyMakeMethod` — duplicates via `getMethod` (`production.service.ts`, ported from the `get-method` server function)
+- `createMakeMethodVersion(client, db, args)` — a new Draft version of a make method, behind `createMethodVersion` (the **New Version** route, the API and MCP), a `Version` change notice's draft and the Onshape panel's Draft. One Kysely transaction inserts the Draft (with `args.changeOrderId`, else the source's), sets a Draft source Active when `args.activate` is set (an Active or Archived source is left alone), and copies the BoM/BoP through `copyMakeMethod`. A failed copy therefore leaves no empty version and no source set Active. Handed a transaction, it joins it (`withTransaction`, `@carbon/database/client`), so a caller can add its own writes to the same commit; get-method joins the same way. Kysely bypasses RLS, so it first checks `parts_create` (and `parts_update` when it activates) through the caller's client, then copies as the system: the method line policies ask for no more than `parts_create`, while get-method's own gate asks for production update. A refused copy comes back as the posting's `ServerFnError`; `createMethodVersion` refuses an `activeVersionId` other than `copyFromId` before it calls it
- `createRevision(client, db, args)` / `activateMethodVersion` — revision and version management; the revision's item row and the planning and purchasing setup it inherits from the source are written in one Kysely transaction, gated by `assert_company_access(companyId, 'parts_create')` through the caller's client
- `updateItemMethodAndSourcing` — cascades replenishment/sourcing changes to Draft method materials
- `getItemCost` / `getItemQuantities` / `getItemDemand` — cost and planning reads
@@ -91,7 +92,7 @@ Each is a `defineServiceFn` const in `items.server.ts`. The route calls it as `a
- `copyMethod` (Get Method and Save Method, behind `checkRevisionLock`), `createMethodVersion`, `syncOnshapeMethod` (the Onshape panel's Sync, `api+/integrations.onshape.sync.ts`: `syncMakeMethod` (`items.service.ts`, ported from the `sync` server function) rewrites the bill of materials, then the item is mapped to its Onshape document). `deleteMethodOperation` (behind `checkRevisionLock`). `deleteMethodMaterials` / `deleteMethodOperations` (unpublished; the bill of material and bill of process Delete Selected, `methods+/material.delete.tsx` and `operation.delete.tsx`) take rows of ONE make method (`getSingleMakeMethodId`) and check that method's lock once. Every other published bill of materials / process write holds the same lock its `methods+/` route checks: material, operation, parameter, tool and step create / update / delete, `activateMethodVersion` (`checkRevisionLocks` checks both the row's own method and the one an update names). With release control on warn the write goes ahead and returns the lock's message as `notice` (`withLockNotice`). `updateMaterialOrder` / `updateOperationOrder` (the `methods+/*.order.tsx` routes) take rows of ONE make method and write the order with `updateSortOrder`. Step, slide and step-link writes also need a Draft method (`methodStepRefusal`); `assertMethodOperationIsDraft` returns that refusal as `rule`. `recalculateItemCost` (the costing card's Recalculate).
- `createChangeNotice` (with the picked parts), `createChangeNoticeForItem`, `setChangeNoticeStatus` (the approval gate, the release through `applyChangeNotice`, the stage notifications), `decideChangeNoticeApproval`. The notice and child writes (`updateChangeNotice`, the affected-item and action-task operations) hold `requireChangeNoticeEditable` themselves: engineering scope for affected items and the narrative, workflow scope for action tasks and header fields; a child row addressed by its own id resolves its notice through `requireChangeNoticeChildEditable`.
-The building blocks they call are in `items.service.ts` (`upsertPart`, `upsertItemPlanning`, `upsertItemManufacturing`, `upsertItemSupersession`, `upsertSupplierPart`, `copyItem`, `copyMakeMethod`, `upsertMakeMethodVersion`, `insertChangeNotice`, `updateChangeNoticeStatus`, `cascadeItemTrackingType`, `updateItemMethodAndSourcing`). A building block is never a tool. Import other modules' code from the file that defines it (`*.service.ts`, `*.models.ts`).
+The building blocks they call are in `items.service.ts` (`upsertPart`, `upsertItemPlanning`, `upsertItemManufacturing`, `upsertItemSupersession`, `upsertSupplierPart`, `copyItem`, `copyMakeMethod`, `createMakeMethodVersion`, `insertChangeNotice`, `updateChangeNoticeStatus`, `cascadeItemTrackingType`, `updateItemMethodAndSourcing`). A building block is never a tool. Import other modules' code from the file that defines it (`*.service.ts`, `*.models.ts`).
## Key Exports
@@ -120,7 +121,7 @@ Change-order code follows the one-service/models/server-per-module convention
- `Replacement Part` — a new part **number** derived from the affected part, BoM/BoP **and** attributes (embedded `PartProperties`); auto affected→new supersession at release. The 1:1 replacement (renamed from the old "New Part"). Restricted to Parts. Embedded attribute editing is currently wired for **Parts** only.
- `New Part` — a **net-new** part (no predecessor, **no supersession**) minted + released under the CO (Make or Buy). Used to introduce a part under change control, including the consolidated "1" in an N→1 assembly BOM change. Added via the "Add Affected Item" modal's change-type Select → create-new-part mini-form (`changeNoticeNewPartValidator` — Part Number, Name, Replenishment System, Tracking Type; **no Part/Tool choice — always a Part**; `addChangeNoticeAffectedItem`'s `newPart` path mints the item with the chosen `itemTrackingType`). Its type **cannot** be switched (net-new by construction), and it shows no cutover card. Restricted to Parts.
- **Buy (purchased) items have no BoM/BoP** — `isManufactured = replenishmentSystem !== "Buy"` gates the embedded editors (mirrors the part page). `Version` is hidden from the change-type picker for Buy items, and `addChangeNoticeAffectedItem` coerces a Buy item's default `Version` → `Revision` on add. Complementarily, the Add Affected Item item picker restricts to **Make parts** (`Item` `replenishmentSystem="Make"` → `Make` or `Buy and Make`) whenever the selected change type is `Version`, so a Buy part can't be picked for a Version in the first place; other change types show all Parts.
-- **Draft creation (`createChangeNoticeDraftMethod`, called by `addChangeNoticeAffectedItem`)** — per change type: `Version` → `upsertMakeMethodVersion` + `copyMakeMethod` on the same item; `Revision` → `createRevision(active:false)`, which also copies the source revision's planning and purchasing setup (batch size, scrap, lead time, per-location reorder policy, item group, preferred supplier, supplier parts + price breaks — see `.claude/rules/revision-system.md`); `Replacement Part` → mint a new numeric `readableId` derived from the source (`getNextItemIdFromSource`) + `copyItem`; `New Part` → the item is minted by `addChangeNoticeAffectedItem`'s `newPart` path (net-new, no source copy), and this just stamps its trigger-created Draft method CO-owned (`baseMakeMethodId` null). The resulting Draft method's `changeOrderId` is stamped to the CO (and the new item's, for Revision/Replacement Part/New Part). The draft refs (`draftMakeMethodId`, `baseMakeMethodId`, `newItemId`) are written back onto the affected-item row. **The Version draft is numbered `max(all versions)+1`, not `active+1`** (with a unique-violation retry) so parallel COs on the same part get distinct versions instead of colliding on `makeMethod (itemId, version)`. **Switching change type discards + recreates the draft** (`updateChangeNoticeAffectedItemChangeType`), resetting edits — but a `New Part` cannot be switched to/from. Removing an affected item (or deleting the notice) discards its draft through `discardChangeNoticeDrafts(client, db, drafts, companyId)`: one Kysely transaction, gated by `parts_delete`, that deletes the draft items' supplier price breaks before the items (`supplierPartPrice → supplierPart` is `ON DELETE RESTRICT` and would otherwise block the item delete) and the Version draft methods. It returns the error, and the callers stop on it rather than remove the affected row or notice and orphan the draft.
+- **Draft creation (`createChangeNoticeDraftMethod`, called by `addChangeNoticeAffectedItem`)** — per change type: `Version` → `createMakeMethodVersion` on the same item, which writes the CO's `changeOrderId` in the Draft's own insert; `Revision` → `createRevision(active:false)`, which also copies the source revision's planning and purchasing setup (batch size, scrap, lead time, per-location reorder policy, item group, preferred supplier, supplier parts + price breaks — see `.claude/rules/revision-system.md`); `Replacement Part` → mint a new numeric `readableId` derived from the source (`getNextItemIdFromSource`) + `copyItem`; `New Part` → the item is minted by `addChangeNoticeAffectedItem`'s `newPart` path (net-new, no source copy), and this just stamps its trigger-created Draft method CO-owned (`baseMakeMethodId` null). For Revision/Replacement Part/New Part the resulting Draft method's `changeOrderId` (and the new item's) is stamped to the CO afterwards. The draft refs (`draftMakeMethodId`, `baseMakeMethodId`, `newItemId`) are written back onto the affected-item row. **The Version draft is numbered `max(all versions)+1`, not `active+1`** (with a unique-violation retry) so parallel COs on the same part get distinct versions instead of colliding on `makeMethod (itemId, version)`. **Switching change type discards + recreates the draft** (`updateChangeNoticeAffectedItemChangeType`), resetting edits — but a `New Part` cannot be switched to/from. Removing an affected item (or deleting the notice) discards its draft through `discardChangeNoticeDrafts(client, db, drafts, companyId)`: one Kysely transaction, gated by `parts_delete`, that deletes the draft items' supplier price breaks before the items (`supplierPartPrice → supplierPart` is `ON DELETE RESTRICT` and would otherwise block the item delete) and the Version draft methods. It returns the error, and the callers stop on it rather than remove the affected row or notice and orphan the draft.
- **Authoring diff (git-style end-state)** — `getChangeNoticeDiff` + pure `diffMethod` (unit-tested in `items.service.test.ts`) diffs the CO-owned Draft method against the **base Active method** the draft was copied from (both real methods), correlating rows by natural key (material → component `itemId`, operation → `order`, operation children → `name`/`key`/`toolId`) since the copied draft carries no back-pointer ids. Classifies each material/operation/attribute added/removed/modified/unchanged. For a Revision/Replacement Part/New Part draft item it also diffs the draft's **supplier parts** (`diffMethod`'s `baseSupplierParts`/`targetSupplierParts`, paired by `supplierId`). A **Revision** draft starts with a copy of its source revision's supplier parts, so it is diffed against the source item's and shows only what was added, changed or removed on the CO line. A Replacement Part / New Part draft starts with none (the source's suppliers are NOT copied by `copyItem`), so the base is null and every `supplierPart` row is `added`; a `Version` shares the live item's suppliers and shows none. Rendered **read-only** by `ChangeNoticeDiffViewer` — the single diff renderer, reused by the affected-item "Changes" card (`AffectedItemDetail`), the CO-wide `ChangeNoticeChanges` rollup on the overview, and the release dialog (shown during authoring, not just at release).
- **Release confirmation** — `ChangeNoticeReleaseMerge` (properties panel, at Implementation) is a plain review-then-confirm dialog: it shows each affected item's authoring diff (`getChangeNoticeDiff`) and posts Implementation → Done. **No merge/conflict step** — releasing a Version just appends a new Active version and archives the prior one, so a same-part parallel CO that released first is not clobbered (its version stays as method history). The old 2-way merge / conflict-resolver UI + `getChangeNoticeReleaseDiff` / `reconcileDraftWithLive` were removed.
- **Release (`applyChangeNotice` → `releaseAffectedItem`)** — the Implementation → Done action. Dispatch by change type per affected item: `Version` activates the Draft (prior Active → Archived), no new item, no supersession; `Revision`/`Replacement Part` activate the Draft, reveal the new item (`item.active = true`, stamp `item.changeOrderId`), and auto-write the affected→new `itemSupersession`; `New Part` activates the Draft + reveals the net-new item but writes **no** supersession (no predecessor). `applyChangeNotice` releases **New Part items first** (stable sort) so a parent assembly's BOM line resolves to an already-active new part. Final Kysely CAS flip to Done. Idempotent: a released draft has its `makeMethod.changeOrderId` cleared, so a re-run skips it.
diff --git a/apps/erp/app/modules/items/items.server.ts b/apps/erp/app/modules/items/items.server.ts
index dc20b05e92..8c322af40c 100644
--- a/apps/erp/app/modules/items/items.server.ts
+++ b/apps/erp/app/modules/items/items.server.ts
@@ -2,6 +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 { ServerFnError } from "@carbon/api/errors";
import { CarbonError, defineServiceFn } from "@carbon/api/service-fn.server";
import { paged, payload, unwrap } from "@carbon/api/service-tools.server";
import {
@@ -953,10 +954,11 @@ export const copyMethod = defineServiceFn({
*
* @remarks
* The new version takes `copyFromId`'s header and, through get-method, its
- * whole bill of materials and process. `activeVersionId` is made Active first
- * (the item's only version, when its successor is drafted). With strict
- * backflush on, that activation is refused while a pulled line has no Pull
- * From storage unit, as `methodVersionToActive` refuses it.
+ * whole bill of materials and process. `activeVersionId` must be `copyFromId`:
+ * a Draft source is made Active first (the item's only version, when its
+ * successor is drafted). With strict backflush on, that activation is refused
+ * while a pulled line has no Pull From storage unit, as `methodVersionToActive`
+ * refuses it. A failed copy leaves no new version behind.
*
* @mcp
*/
@@ -965,59 +967,52 @@ export const createMethodVersion = defineServiceFn({
permission: { create: "parts" },
async run(ctx, input) {
- const companyId = ctx.company.id;
- const userId = ctx.auditUserId;
-
- if (input.activeVersionId) {
+ const { copyFromId, activeVersionId, version } = input;
+ // Any other id could be another item's version, set Active beside its own.
+ if (activeVersionId && activeVersionId !== copyFromId) {
+ return ctx.error(
+ "rule",
+ "Only the version being copied can be set Active"
+ );
+ }
+ if (activeVersionId) {
const db = ctx.asSystem.pg;
- const { strict } = await getStrictBackflushSettings(db, companyId);
+ const { strict } = await getStrictBackflushSettings(db, ctx.company.id);
if (strict) {
const parts = await getMethodPartsMissingPullFrom(db, {
- makeMethodId: input.activeVersionId,
- companyId
+ makeMethodId: activeVersionId,
+ companyId: ctx.company.id
});
if (parts.length > 0) {
return ctx.error("rule", activationRefusalMessage(parts));
}
}
}
- const insert = await service.upsertMakeMethodVersion(
+
+ const result = await service.createMakeMethodVersion(
ctx.asCaller.supabase,
+ ctx.asSystem.pg,
{
- ...input,
- companyId,
- createdBy: userId
+ copyFromId,
+ version,
+ activate: Boolean(activeVersionId),
+ companyId: ctx.company.id,
+ createdBy: ctx.auditUserId
}
);
- const version = insert.data;
- if (insert.error || !version?.id || !version.type || !version.itemId) {
+ // The copy runs as the system, so its refusal is ours, as `copyMethod` reads it.
+ if (result.error instanceof ServerFnError) {
return ctx.error(
"internal",
- "Failed to insert new version",
- insert.error
+ "Failed to create new version",
+ result.error
);
}
-
- const copy = await service.copyMakeMethod(
- ctx.asSystem.supabase,
- ctx.asSystem.pg,
- {
- sourceId: input.copyFromId,
- targetId: version.id,
- billOfMaterial: true,
- billOfProcess: true,
- parameters: true,
- tools: true,
- steps: true,
- workInstructions: true,
- companyId,
- userId
- }
+ // `data` is set whenever `error` is not; the null is the union's, not a case.
+ return (
+ unwrap(ctx, result) ??
+ ctx.error("internal", "Failed to create new version")
);
- if (copy.error) {
- return ctx.error("internal", "Failed to copy make method", copy.error);
- }
- return { id: version.id, itemId: version.itemId, type: version.type };
}
});
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 4ccf5f7f93..89c0bf0849 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.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 { NotFoundError } from "@carbon/api/errors";
+import { NotFoundError, ServerFnError } from "@carbon/api/errors";
import type { PermissionRule } from "@carbon/api/permissions";
import {
CarbonError,
@@ -18,12 +18,14 @@ import {
fetchAllRecords,
getCompanyTimeZone
} from "@carbon/database";
-import type {
- ExpressionBuilder,
- Kysely,
- KyselyDatabase,
- KyselyTx
+import {
+ type ExpressionBuilder,
+ type Kysely,
+ type KyselyDatabase,
+ type KyselyTx,
+ withTransaction
} from "@carbon/database/client";
+import { toJson } from "@carbon/database/json";
import { insertRows, many, maybeSingle } from "@carbon/database/rows";
import {
hasPendingApproval,
@@ -112,7 +114,6 @@ import {
type itemValidator,
type MethodDiffEntry,
type MethodDiffStatus,
- type makeMethodVersionValidator,
type materialDimensionValidator,
type materialFinishValidator,
type materialFormValidator,
@@ -4298,47 +4299,132 @@ export async function upsertItemUnitSalePrice(
.eq("itemId", itemUnitSalePrice.itemId);
}
-/** The header insert only; `createMethodVersion` also copies the method. */
-export async function upsertMakeMethodVersion(
+/**
+ * A new Draft version of a make method with `copyFromId`'s header, bill of
+ * materials and bill of process. With `activate`, a Draft source is set Active
+ * first, so the new Draft never outranks it. The insert, the activation and the
+ * copy run in one transaction, or in the one `db` already is: a failed copy
+ * leaves no empty version and no source set Active. Kysely bypasses RLS, so the
+ * caller's client is checked for what the makeMethod policies ask; the copy then
+ * runs as the system, since the method line policies ask for no more than
+ * parts_create, while get-method's own gate asks for production update.
+ */
+export async function createMakeMethodVersion(
client: SupabaseClient<Database>,
- makeMethodVersion: z.infer<typeof makeMethodVersionValidator> & {
+ db: Kysely<KyselyDatabase>,
+ args: {
+ copyFromId: string;
+ version: number;
+ /** Set a Draft source Active. An Active or Archived source is left alone. */
+ activate?: boolean;
+ /** The change notice the new Draft belongs to; else the source's. */
+ changeOrderId?: string;
companyId: string;
createdBy: string;
}
-) {
- const currentMakeMethod = await client
+): Promise<
+ | {
+ data: {
+ id: string;
+ itemId: string;
+ type: Database["public"]["Tables"]["item"]["Row"]["type"];
+ };
+ error: null;
+ }
+ | { data: null; error: ServiceError | ServerFnError }
+> {
+ const { copyFromId, version, companyId, createdBy } = args;
+
+ const source = await client
.from("makeMethod")
- .select("*")
- .eq("id", makeMethodVersion.copyFromId)
- .eq("companyId", makeMethodVersion.companyId)
+ .select("itemId, status, customFields, tags, changeOrderId, ...item(type)")
+ .eq("id", copyFromId)
+ .eq("companyId", companyId)
.single();
+ if (source.error) return { data: null, error: source.error };
- if (currentMakeMethod.error) return currentMakeMethod;
+ // The makeMethod policies ask for parts_create to insert and parts_update to
+ // set a version Active.
+ const activate = args.activate === true && source.data.status === "Draft";
+ const permitted = await requireCompanyPermission(
+ client,
+ companyId,
+ "parts_create"
+ );
+ if (permitted.error) return { data: null, error: permitted.error };
+ if (activate) {
+ const canActivate = await requireCompanyPermission(
+ client,
+ companyId,
+ "parts_update"
+ );
+ if (canActivate.error) return { data: null, error: canActivate.error };
+ }
- // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
- const { id, version, ...data } = currentMakeMethod.data;
+ try {
+ const draftId = await withTransaction(db, async (trx) => {
+ const draft = await trx
+ .insertInto("makeMethod")
+ .values({
+ itemId: source.data.itemId,
+ customFields: toJson(source.data.customFields),
+ tags: source.data.tags,
+ changeOrderId: args.changeOrderId ?? source.data.changeOrderId,
+ status: "Draft",
+ version,
+ companyId,
+ createdBy
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
- const insert = await client
- .from("makeMethod")
- .insert({
- ...data,
- status: "Draft",
- version: makeMethodVersion.version,
- createdBy: makeMethodVersion.createdBy
- })
- .select("id, ...item(itemId:id, type)")
- .single();
+ if (activate) {
+ // A source set Active meanwhile, or archived behind a newer Active, is
+ // not outranked by the new Draft either: nothing to refuse.
+ await trx
+ .updateTable("makeMethod")
+ .set({ status: "Active" })
+ .where("id", "=", copyFromId)
+ .where("companyId", "=", companyId)
+ .where("status", "=", "Draft")
+ .execute();
+ }
- if (insert.error) return insert;
+ const copy = await copyMakeMethod(getCarbonServiceRole(), trx, {
+ sourceId: copyFromId,
+ targetId: draft.id,
+ billOfMaterial: true,
+ billOfProcess: true,
+ parameters: true,
+ tools: true,
+ steps: true,
+ workInstructions: true,
+ companyId,
+ userId: createdBy
+ });
+ if (copy.error) throw copy.error;
- if (makeMethodVersion.activeVersionId) {
- await client
- .from("makeMethod")
- .update({ status: "Active" })
- .eq("id", makeMethodVersion.activeVersionId);
- }
+ return draft.id;
+ });
- return insert;
+ return {
+ data: { id: draftId, itemId: source.data.itemId, type: source.data.type },
+ error: null
+ };
+ } catch (error) {
+ // The copy's refusal, with the status its category is read from.
+ if (error instanceof ServerFnError) return { data: null, error };
+ // A taken version number is the caller's to retry.
+ if (!isUniqueViolation(error)) {
+ logger.error("Failed to create make method version", {
+ companyId,
+ copyFromId,
+ version,
+ error
+ });
+ }
+ return { data: null, error: writeError(error) };
+ }
}
/**
@@ -6845,18 +6931,18 @@ export async function createChangeNoticeDraftMethod(
// highest-version draft when there is no Active — and `get-method` would hand
// the CO's UNRELEASED edits to jobs/quotes. Freezing the base as Active keeps
// production on the current method until the CO is released.
- const activeVersionId = base.status === "Draft" ? base.id : undefined;
- // New Draft version on the same item, then copy the BoM/BoP rows (the
- // canonical new-version flow: header insert + copyMakeMethod). Number it
+ // `createMakeMethodVersion` activates only a Draft base, and writes the new
+ // Draft with the CO's id and its BoM/BoP rows in one transaction. Number it
// above ALL existing versions (maxVersion + 1), not the Active one, so a
// second CO on the same part doesn't collide on (itemId, version). Retry on
// a concurrent unique-violation by recomputing the next free version.
let draftId: string | null = null;
let nextVersion = base.maxVersion + 1;
for (let attempt = 0; attempt < 3; attempt++) {
- const res = await upsertMakeMethodVersion(client, {
+ const res = await createMakeMethodVersion(client, db, {
copyFromId: base.id,
- activeVersionId,
+ activate: true,
+ changeOrderId: changeNoticeId,
version: nextVersion,
companyId,
createdBy: userId
@@ -6883,22 +6969,6 @@ export async function createChangeNoticeDraftMethod(
error: { message: "Failed to create draft version" }
};
}
- // @ts-expect-error TS2345 - getMethodValidator flags default in get-method
- const copy = await copyMakeMethod(client, db, {
- sourceId: base.id,
- targetId: draftId,
- companyId,
- userId
- });
- if (copy.error) {
- return { data: null, error: { message: "Failed to copy make method" } };
- }
- const stamp = await client
- .from("makeMethod")
- .update({ changeOrderId: changeNoticeId })
- .eq("id", draftId)
- .eq("companyId", companyId);
- if (stamp.error) return { data: null, error: stamp.error };
return {
data: {
draftMakeMethodId: draftId,
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index c01dfb52c7..4a59c0ed03 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -5,7 +5,7 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced
## Key Domain Concepts
- **Job** — production work order. Statuses: Draft → Planned → Ready → In Progress → Paused → Completed → Closed → Cancelled. `isJobLocked(status)` returns true for Completed/Closed/Cancelled. MUST check before allowing edits.
-- **Job Make Method** — a job's manufacturing method (BOM + routing). Root method has `parentMaterialId = null`; sub-assemblies nest via `parentMaterialId`. Created by `getMethod` (`production.service.ts`, ported from the `get-method` server function; its live and unit tests include `production.sandbox.test.ts`).
+- **Job Make Method** — a job's manufacturing method (BOM + routing). Root method has `parentMaterialId = null`; sub-assemblies nest via `parentMaterialId`. Created by `getMethod` (`production.service.ts`, ported from the `get-method` server function; its live and unit tests include `production.sandbox.test.ts`). Every `getMethod` body opens its transaction through `withTransaction` (`@carbon/database/client`), so it joins one it is handed: `createMakeMethodVersion` copies into a Draft it has not committed yet.
- **Job Operation** — routing step within a make method. `operationType` (shared enum): `Process`, `Assembly`, `Inspection` (in-house on a work center), or `Outside Processing` (subcontracted to a supplier process). Statuses: Todo → Ready → In Progress → Done. Ordered by `order` column.
- **Job Material** — BOM line within a make method. Each has a `methodType` (Pull from Inventory, Purchase to Order, Make to Order) that drives procurement.
- **Production Event** — time tracking (Labor/Machine/Setup) against an operation.
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 73d35bab04..8c57689123 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -29,7 +29,11 @@ import {
journalReference
} from "@carbon/database";
import { DOCUMENT_JOURNAL_STATUSES } from "@carbon/database/accounting-posting";
-import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import {
+ type Kysely,
+ type KyselyDatabase,
+ withTransaction
+} from "@carbon/database/client";
import {
runConfigurationRule,
transpileRule
@@ -13141,7 +13145,7 @@ export async function getMethod(
throw new Error("Failed to get source materials or operations");
}
- await db.transaction().execute(async (trx) => {
+ await withTransaction(db, async (trx) => {
// Delete existing materials and operations from target method
await Promise.all([
parts.billOfMaterial
@@ -13627,7 +13631,7 @@ export async function getMethod(
return acc;
}, {});
- await db.transaction().execute(async (trx) => {
+ await withTransaction(db, async (trx) => {
const insertedJobMaterialIds: string[] = [];
if (isConfigured) {
await trx
@@ -14742,7 +14746,7 @@ export async function getMethod(
return acc;
}, {});
- await db.transaction().execute(async (trx) => {
+ await withTransaction(db, async (trx) => {
await itemDefaults.load(
trx,
treeItemIds(methodTree, supersessionRedirect)
@@ -15517,673 +15521,670 @@ export async function getMethod(
supplierProcesses?.data
);
- await db
- .transaction()
- .execute(async (trx: Transaction<KyselyDatabase>) => {
- if (isConfigured) {
- await trx
- .updateTable("quoteLine")
- .set({
- configuration: JSON.stringify(configuration),
- updatedAt: datetime.timestamp(),
- updatedBy: userId
- })
- .where("id", "=", quoteLineId)
- .where("companyId", "=", companyId)
- .execute();
- }
-
- // Delete existing quoteMakeMethod, quoteMakeMethodOperation, quoteMakeMethodMaterial
- await Promise.all([
- parts.billOfMaterial
- ? trx
- .deleteFrom("quoteMakeMethod")
- .where((eb) =>
- eb.and([
- eb("quoteLineId", "=", quoteLineId),
- eb("parentMaterialId", "is not", null)
- ])
- )
- .where("companyId", "=", companyId)
- .execute()
- : Promise.resolve(),
- parts.billOfMaterial
- ? trx
- .deleteFrom("quoteMaterial")
- .where("quoteLineId", "=", quoteLineId)
- .where("companyId", "=", companyId)
- .execute()
- : Promise.resolve(),
- // Prevent cascade deletion of materials when only replacing operations
- !parts.billOfMaterial && parts.billOfProcess
- ? trx
- .updateTable("quoteMaterial")
- .set({ quoteOperationId: null })
- .where("quoteLineId", "=", quoteLineId)
- .where("companyId", "=", companyId)
- .execute()
- : Promise.resolve(),
- parts.billOfProcess
- ? trx
- .deleteFrom("quoteOperation")
- .where("quoteLineId", "=", quoteLineId)
- .where("companyId", "=", companyId)
- .execute()
- : Promise.resolve(),
- trx
- .updateTable("quoteMakeMethod")
- .set({ version: makeMethod.data.version ?? 1 })
- .where("id", "=", quoteMakeMethod.data!.id!)
- .where("companyId", "=", companyId)
- .execute()
- ]);
-
- async function getConfiguredValue<
- T extends number | string | boolean | null
- >({
- id,
- field,
- defaultValue
- }: {
- id: string;
- field: string;
- defaultValue: T;
- }): Promise<T> {
- if (!configurationCodeByField) return defaultValue;
-
- const fieldKey = getFieldKey(field, id);
-
- if (configurationCodeByField[fieldKey]) {
- try {
- const code = configurationCodeByField[fieldKey];
- const mod = await importTypeScript(code);
- const result = await mod.configure(hydratedConfiguration);
-
- return (result ?? defaultValue) as T;
- } catch (err) {
- getMethodLogger.error("configuration field resolver failed", {
- error: String((err as Error)?.stack ?? err)
- });
- return defaultValue;
- }
- }
-
- return defaultValue;
- }
-
- // traverse method tree and create:
- // - quoteMakeMethod
- // - quoteMakeMethodOperation
- // - quoteMakeMethodMaterial
- async function traverseMethod(
- node: MethodTreeItem,
- parentQuoteMakeMethodId: string | null
- ) {
- getMethodLogger.debug("[traverseMethod]", {
- isRoot: node.data.isRoot,
- itemId: node.data.itemId,
- methodType: node.data.methodType,
- materialMakeMethodId: node.data.materialMakeMethodId,
- childCount: node.children.length,
- childMethodTypes: node.children.map((c) => ({
- itemId: c.data.itemId,
- methodType: c.data.methodType
- })),
- parentQuoteMakeMethodId
- });
-
- let methodOperationsToQuoteOperations: Record<string, string> = {};
+ await withTransaction(db, async (trx) => {
+ if (isConfigured) {
+ await trx
+ .updateTable("quoteLine")
+ .set({
+ configuration: JSON.stringify(configuration),
+ updatedAt: datetime.timestamp(),
+ updatedBy: userId
+ })
+ .where("id", "=", quoteLineId)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
- const nodeLevelConfigurationKey = `${
- node.data.materialMakeMethodId
- }:${node.data.isRoot ? "undefined" : node.data.methodMaterialId}`;
+ // Delete existing quoteMakeMethod, quoteMakeMethodOperation, quoteMakeMethodMaterial
+ await Promise.all([
+ parts.billOfMaterial
+ ? trx
+ .deleteFrom("quoteMakeMethod")
+ .where((eb) =>
+ eb.and([
+ eb("quoteLineId", "=", quoteLineId),
+ eb("parentMaterialId", "is not", null)
+ ])
+ )
+ .where("companyId", "=", companyId)
+ .execute()
+ : Promise.resolve(),
+ parts.billOfMaterial
+ ? trx
+ .deleteFrom("quoteMaterial")
+ .where("quoteLineId", "=", quoteLineId)
+ .where("companyId", "=", companyId)
+ .execute()
+ : Promise.resolve(),
+ // Prevent cascade deletion of materials when only replacing operations
+ !parts.billOfMaterial && parts.billOfProcess
+ ? trx
+ .updateTable("quoteMaterial")
+ .set({ quoteOperationId: null })
+ .where("quoteLineId", "=", quoteLineId)
+ .where("companyId", "=", companyId)
+ .execute()
+ : Promise.resolve(),
+ parts.billOfProcess
+ ? trx
+ .deleteFrom("quoteOperation")
+ .where("quoteLineId", "=", quoteLineId)
+ .where("companyId", "=", companyId)
+ .execute()
+ : Promise.resolve(),
+ trx
+ .updateTable("quoteMakeMethod")
+ .set({ version: makeMethod.data.version ?? 1 })
+ .where("id", "=", quoteMakeMethod.data!.id!)
+ .where("companyId", "=", companyId)
+ .execute()
+ ]);
- // For child nodes, always include operations regardless of parts flags
- if (!node.data.isRoot || parts.billOfProcess) {
- const relatedOperations = {
- data: treeOperations.get(node.data.materialMakeMethodId) ?? []
- };
+ async function getConfiguredValue<
+ T extends number | string | boolean | null
+ >({
+ id,
+ field,
+ defaultValue
+ }: {
+ id: string;
+ field: string;
+ defaultValue: T;
+ }): Promise<T> {
+ if (!configurationCodeByField) return defaultValue;
- let quoteOperationsInserts: Database["public"]["Tables"]["quoteOperation"]["Insert"][] =
- [];
- // Index-aligned with quoteOperationsInserts, as in itemToJob:
- // a blank configured processId skips a row and a billOfProcess
- // configuration reorders and filters them, so the returned ids
- // cannot be paired against relatedOperations.data.
- let sourceOperations: typeof relatedOperations.data = [];
- for await (const op of relatedOperations?.data ?? []) {
- const [
- processId,
- procedureId,
- workCenterId,
- description,
- setupTime,
- setupUnit,
- laborTime,
- laborUnit,
- machineTime,
- machineUnit,
- operationOrder,
- operationType
- ] = await Promise.all([
- getConfiguredValue({
- id: op.id,
- field: "processId",
- defaultValue: op.processId
- }),
- getConfiguredValue({
- id: op.id,
- field: "procedureId",
- defaultValue: op.procedureId
- }),
- getConfiguredValue({
- id: op.id,
- field: "workCenterId",
- defaultValue: op.workCenterId
- }),
- getConfiguredValue({
- id: op.id,
- field: "description",
- defaultValue: op.description
- }),
- getConfiguredValue({
- id: op.id,
- field: "setupTime",
- defaultValue: op.setupTime
- }),
- getConfiguredValue({
- id: op.id,
- field: "setupUnit",
- defaultValue: op.setupUnit
- }),
- getConfiguredValue({
- id: op.id,
- field: "laborTime",
- defaultValue: op.laborTime
- }),
- getConfiguredValue({
- id: op.id,
- field: "laborUnit",
- defaultValue: op.laborUnit
- }),
- getConfiguredValue({
- id: op.id,
- field: "machineTime",
- defaultValue: op.machineTime
- }),
- getConfiguredValue({
- id: op.id,
- field: "machineUnit",
- defaultValue: op.machineUnit
- }),
- getConfiguredValue({
- id: op.id,
- field: "operationOrder",
- defaultValue: op.operationOrder
- }),
- getConfiguredValue({
- id: op.id,
- field: "operationType",
- defaultValue: op.operationType
- })
- ]);
+ const fieldKey = getFieldKey(field, id);
- if (processId === "") continue;
+ if (configurationCodeByField[fieldKey]) {
+ try {
+ const code = configurationCodeByField[fieldKey];
+ const mod = await importTypeScript(code);
+ const result = await mod.configure(hydratedConfiguration);
- const operationRates = getLaborAndOverheadRates(
- processId,
- op.workCenterId
- );
- getMethodLogger.debug("traverseMethod", {
- processId,
- ...operationRates
- });
+ return (result ?? defaultValue) as T;
+ } catch (err) {
+ getMethodLogger.error("configuration field resolver failed", {
+ error: String((err as Error)?.stack ?? err)
+ });
+ return defaultValue;
+ }
+ }
- sourceOperations.push(op);
- quoteOperationsInserts.push({
- quoteId,
- quoteLineId,
- quoteMakeMethodId: parentQuoteMakeMethodId!,
- processId,
- procedureId,
- assemblyInstructionId: op.assemblyInstructionId,
- inspectionDocumentId: op.inspectionDocumentId,
- workCenterId,
- description,
- setupTime,
- setupUnit,
- laborTime,
- laborUnit,
- machineTime,
- machineUnit,
- ...getLaborAndOverheadRates(processId, op.workCenterId),
- order: op.order,
- operationOrder,
- operationType: normalizeOperationType(operationType),
- operationSupplierProcessId: op.operationSupplierProcessId,
- operationUnitCost: op.operationUnitCost ?? 0,
- ...getOutsideOperationRates(
- processId,
- op.operationSupplierProcessId
- ),
- operationMinimumCost: op.operationMinimumCost ?? 0,
- tags: op.tags ?? [],
- workInstruction: toJson(
- !node.data.isRoot || parts.workInstructions
- ? op.workInstruction
- : {}
- ),
- companyId,
- createdBy: userId,
- customFields: {}
- });
- }
+ return defaultValue;
+ }
- const bopConfigurationKey = `billOfProcess:${nodeLevelConfigurationKey}`;
- let bopConfiguration: string[] | null = null;
+ // traverse method tree and create:
+ // - quoteMakeMethod
+ // - quoteMakeMethodOperation
+ // - quoteMakeMethodMaterial
+ async function traverseMethod(
+ node: MethodTreeItem,
+ parentQuoteMakeMethodId: string | null
+ ) {
+ getMethodLogger.debug("[traverseMethod]", {
+ isRoot: node.data.isRoot,
+ itemId: node.data.itemId,
+ methodType: node.data.methodType,
+ materialMakeMethodId: node.data.materialMakeMethodId,
+ childCount: node.children.length,
+ childMethodTypes: node.children.map((c) => ({
+ itemId: c.data.itemId,
+ methodType: c.data.methodType
+ })),
+ parentQuoteMakeMethodId
+ });
- if (configurationCodeByField?.[bopConfigurationKey]) {
- const mod = await importTypeScript(
- configurationCodeByField[bopConfigurationKey]
- );
- bopConfiguration = await mod.configure(hydratedConfiguration);
- }
+ let methodOperationsToQuoteOperations: Record<string, string> = {};
- if (bopConfiguration) {
- const configuredInserts: typeof quoteOperationsInserts = [];
- const configuredSources: typeof sourceOperations = [];
- bopConfiguration.forEach((description, index) => {
- const position = quoteOperationsInserts.findIndex(
- (operation) => operation.description === description
- );
- if (position !== -1) {
- configuredInserts.push({
- ...quoteOperationsInserts[position]!,
- order: index + 1
- });
- configuredSources.push(sourceOperations[position]!);
- }
- });
- quoteOperationsInserts = configuredInserts;
- sourceOperations = configuredSources;
- }
+ const nodeLevelConfigurationKey = `${
+ node.data.materialMakeMethodId
+ }:${node.data.isRoot ? "undefined" : node.data.methodMaterialId}`;
- if (quoteOperationsInserts?.length > 0) {
- const operationIds = await trx
- .insertInto("quoteOperation")
- .values(quoteOperationsInserts)
- .returning(["id"])
- .execute();
+ // For child nodes, always include operations regardless of parts flags
+ if (!node.data.isRoot || parts.billOfProcess) {
+ const relatedOperations = {
+ data: treeOperations.get(node.data.materialMakeMethodId) ?? []
+ };
- for (const [index, operation] of sourceOperations.entries()) {
- const operationId = operationIds[index]?.id;
+ let quoteOperationsInserts: Database["public"]["Tables"]["quoteOperation"]["Insert"][] =
+ [];
+ // Index-aligned with quoteOperationsInserts, as in itemToJob:
+ // a blank configured processId skips a row and a billOfProcess
+ // configuration reorders and filters them, so the returned ids
+ // cannot be paired against relatedOperations.data.
+ let sourceOperations: typeof relatedOperations.data = [];
+ for await (const op of relatedOperations?.data ?? []) {
+ const [
+ processId,
+ procedureId,
+ workCenterId,
+ description,
+ setupTime,
+ setupUnit,
+ laborTime,
+ laborUnit,
+ machineTime,
+ machineUnit,
+ operationOrder,
+ operationType
+ ] = await Promise.all([
+ getConfiguredValue({
+ id: op.id,
+ field: "processId",
+ defaultValue: op.processId
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "procedureId",
+ defaultValue: op.procedureId
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "workCenterId",
+ defaultValue: op.workCenterId
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "description",
+ defaultValue: op.description
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "setupTime",
+ defaultValue: op.setupTime
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "setupUnit",
+ defaultValue: op.setupUnit
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "laborTime",
+ defaultValue: op.laborTime
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "laborUnit",
+ defaultValue: op.laborUnit
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "machineTime",
+ defaultValue: op.machineTime
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "machineUnit",
+ defaultValue: op.machineUnit
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "operationOrder",
+ defaultValue: op.operationOrder
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "operationType",
+ defaultValue: op.operationType
+ })
+ ]);
- if (operationId) {
- const {
- methodOperationTool,
- methodOperationParameter,
- methodOperationStep,
- procedureId
- } = operation;
+ if (processId === "") continue;
- if (
- (!node.data.isRoot || parts.tools) &&
- Array.isArray(methodOperationTool) &&
- methodOperationTool.length > 0
- ) {
- await trx
- .insertInto("quoteOperationTool")
- .values(
- methodOperationTool.map((tool) => ({
- toolId: tool.toolId,
- quantity: tool.quantity,
- operationId,
- companyId,
- createdBy: userId
- }))
- )
- .execute();
- }
+ const operationRates = getLaborAndOverheadRates(
+ processId,
+ op.workCenterId
+ );
+ getMethodLogger.debug("traverseMethod", {
+ processId,
+ ...operationRates
+ });
- if (!procedureId) {
- if (
- (!node.data.isRoot || parts.parameters) &&
- Array.isArray(methodOperationParameter) &&
- methodOperationParameter.length > 0
- ) {
- const parameters = await Promise.all(
- methodOperationParameter.map(async (param) => ({
- operationId,
- key: param.key,
- value: await getConfiguredValue({
- id: operation.id,
- field: `parameter:${param.id}:value`,
- defaultValue: param.value
- }),
- companyId,
- createdBy: userId
- }))
- );
+ sourceOperations.push(op);
+ quoteOperationsInserts.push({
+ quoteId,
+ quoteLineId,
+ quoteMakeMethodId: parentQuoteMakeMethodId!,
+ processId,
+ procedureId,
+ assemblyInstructionId: op.assemblyInstructionId,
+ inspectionDocumentId: op.inspectionDocumentId,
+ workCenterId,
+ description,
+ setupTime,
+ setupUnit,
+ laborTime,
+ laborUnit,
+ machineTime,
+ machineUnit,
+ ...getLaborAndOverheadRates(processId, op.workCenterId),
+ order: op.order,
+ operationOrder,
+ operationType: normalizeOperationType(operationType),
+ operationSupplierProcessId: op.operationSupplierProcessId,
+ operationUnitCost: op.operationUnitCost ?? 0,
+ ...getOutsideOperationRates(
+ processId,
+ op.operationSupplierProcessId
+ ),
+ operationMinimumCost: op.operationMinimumCost ?? 0,
+ tags: op.tags ?? [],
+ workInstruction: toJson(
+ !node.data.isRoot || parts.workInstructions
+ ? op.workInstruction
+ : {}
+ ),
+ companyId,
+ createdBy: userId,
+ customFields: {}
+ });
+ }
- await trx
- .insertInto("quoteOperationParameter")
- .values(parameters)
- .execute();
- }
+ const bopConfigurationKey = `billOfProcess:${nodeLevelConfigurationKey}`;
+ let bopConfiguration: string[] | null = null;
- if (
- (!node.data.isRoot || parts.steps) &&
- Array.isArray(methodOperationStep) &&
- methodOperationStep.length > 0
- ) {
- const attributes = await Promise.all(
- methodOperationStep.map(
- async ({
- id,
- // quoteOperationStep has no provenance marker
- assemblyInstructionStepId:
- _assemblyInstructionStepId,
- ...attribute
- }) => ({
- ...attribute,
- description: toTiptapDoc(attribute.description),
- operationId,
- minValue: await getConfiguredValue({
- id: operation.id,
- field: `attribute:${id}:minValue`,
- defaultValue: attribute.minValue
- }),
- maxValue: await getConfiguredValue({
- id: operation.id,
- field: `attribute:${id}:maxValue`,
- defaultValue: attribute.maxValue
- }),
- companyId,
- createdBy: userId
- })
- )
- );
-
- const insertedSteps = await trx
- .insertInto("quoteOperationStep")
- .values(attributes)
- .returning(["id"])
- .execute();
-
- await copyStepSlides(
- trx,
- methodOperationStep,
- insertedSteps,
- "methodOperationStepSlide",
- "quoteOperationStepSlide",
- companyId,
- userId
- );
- }
- }
- }
+ if (configurationCodeByField?.[bopConfigurationKey]) {
+ const mod = await importTypeScript(
+ configurationCodeByField[bopConfigurationKey]
+ );
+ bopConfiguration = await mod.configure(hydratedConfiguration);
+ }
+
+ if (bopConfiguration) {
+ const configuredInserts: typeof quoteOperationsInserts = [];
+ const configuredSources: typeof sourceOperations = [];
+ bopConfiguration.forEach((description, index) => {
+ const position = quoteOperationsInserts.findIndex(
+ (operation) => operation.description === description
+ );
+ if (position !== -1) {
+ configuredInserts.push({
+ ...quoteOperationsInserts[position]!,
+ order: index + 1
+ });
+ configuredSources.push(sourceOperations[position]!);
}
+ });
+ quoteOperationsInserts = configuredInserts;
+ sourceOperations = configuredSources;
+ }
- methodOperationsToQuoteOperations = sourceOperations.reduce<
- Record<string, string>
- >((acc, op, index) => {
- const operationId = operationIds[index]?.id;
- if (operationId) {
- acc[op.id!] = operationId;
- }
- return acc;
- }, {});
- }
- } // end if (parts.billOfProcess)
+ if (quoteOperationsInserts?.length > 0) {
+ const operationIds = await trx
+ .insertInto("quoteOperation")
+ .values(quoteOperationsInserts)
+ .returning(["id"])
+ .execute();
- if (parts.billOfMaterial) {
- const mapMethodMaterialToQuoteMaterial = async (
- child: MethodTreeItem
- ) => {
- let [
- itemId,
- description,
- quantity,
- methodType,
- unitOfMeasureCode
- ] = await Promise.all([
- getConfiguredValue({
- id: child.data.methodMaterialId,
- field: "itemId",
- defaultValue: child.data.itemId
- }),
- getConfiguredValue({
- id: child.data.methodMaterialId,
- field: "description",
- defaultValue: child.data.description
- }),
- getConfiguredValue({
- id: child.data.methodMaterialId,
- field: "quantity",
- defaultValue: child.data.quantity
- }),
- getConfiguredValue({
- id: child.data.methodMaterialId,
- field: "methodType",
- defaultValue: child.data.methodType
- }),
- getConfiguredValue({
- id: child.data.methodMaterialId,
- field: "unitOfMeasureCode",
- defaultValue: child.data.unitOfMeasureCode
- })
- ]);
+ for (const [index, operation] of sourceOperations.entries()) {
+ const operationId = operationIds[index]?.id;
- if (itemId === "") return null;
- // A configured (or authored) quantity of 0 removes the line from
- // the BOM (and its sub-tree, via configuredChildren below).
- if (isZeroQuantity(quantity)) return null;
+ if (operationId) {
+ const {
+ methodOperationTool,
+ methodOperationParameter,
+ methodOperationStep,
+ procedureId
+ } = operation;
- let itemType = child.data.itemType;
- let unitCost = child.data.unitCost;
+ if (
+ (!node.data.isRoot || parts.tools) &&
+ Array.isArray(methodOperationTool) &&
+ methodOperationTool.length > 0
+ ) {
+ await trx
+ .insertInto("quoteOperationTool")
+ .values(
+ methodOperationTool.map((tool) => ({
+ toolId: tool.toolId,
+ quantity: tool.quantity,
+ operationId,
+ companyId,
+ createdBy: userId
+ }))
+ )
+ .execute();
+ }
- // TODO: if the methodType is Make and the default value is not Make, we need to do itemToQuoteMakeMethod for that material
+ if (!procedureId) {
+ if (
+ (!node.data.isRoot || parts.parameters) &&
+ Array.isArray(methodOperationParameter) &&
+ methodOperationParameter.length > 0
+ ) {
+ const parameters = await Promise.all(
+ methodOperationParameter.map(async (param) => ({
+ operationId,
+ key: param.key,
+ value: await getConfiguredValue({
+ id: operation.id,
+ field: `parameter:${param.id}:value`,
+ defaultValue: param.value
+ }),
+ companyId,
+ createdBy: userId
+ }))
+ );
- if (itemId !== child.data.itemId) {
- const item = await single<
- "item",
- Tables["item"]["Row"] & {
- itemCost: Tables["itemCost"]["Row"][];
- }
- >(
- trx,
- "item",
- { id: itemId, companyId },
- {
- embed: { itemCost: { table: "itemCost", on: "itemId" } }
+ await trx
+ .insertInto("quoteOperationParameter")
+ .values(parameters)
+ .execute();
}
- );
- if (item.data) {
- itemType = item.data.type;
- unitCost =
- item.data.itemCost[0]?.unitCost ?? child.data.unitCost;
- if (description === child.data.description) {
- description = item.data.name;
+
+ if (
+ (!node.data.isRoot || parts.steps) &&
+ Array.isArray(methodOperationStep) &&
+ methodOperationStep.length > 0
+ ) {
+ const attributes = await Promise.all(
+ methodOperationStep.map(
+ async ({
+ id,
+ // quoteOperationStep has no provenance marker
+ assemblyInstructionStepId:
+ _assemblyInstructionStepId,
+ ...attribute
+ }) => ({
+ ...attribute,
+ description: toTiptapDoc(attribute.description),
+ operationId,
+ minValue: await getConfiguredValue({
+ id: operation.id,
+ field: `attribute:${id}:minValue`,
+ defaultValue: attribute.minValue
+ }),
+ maxValue: await getConfiguredValue({
+ id: operation.id,
+ field: `attribute:${id}:maxValue`,
+ defaultValue: attribute.maxValue
+ }),
+ companyId,
+ createdBy: userId
+ })
+ )
+ );
+
+ const insertedSteps = await trx
+ .insertInto("quoteOperationStep")
+ .values(attributes)
+ .returning(["id"])
+ .execute();
+
+ await copyStepSlides(
+ trx,
+ methodOperationStep,
+ insertedSteps,
+ "methodOperationStepSlide",
+ "quoteOperationStepSlide",
+ companyId,
+ userId
+ );
}
- } else {
- itemId = child.data.itemId;
}
}
+ }
- return {
- quoteId,
- quoteLineId,
- quoteMakeMethodId: parentQuoteMakeMethodId!,
- quoteOperationId:
- methodOperationsToQuoteOperations[child.data.operationId],
- order: child.data.order,
- itemId,
- itemType,
- kit: child.data.kit,
- methodType,
- description,
- quantity,
- storageUnitId: quoteLocationId
- ? // @ts-ignore: storageUnitIds is a dynamic object with location keys
- (child.data.storageUnitIds?.[
- quoteLocationId
- ] as string) || null
- : null,
- unitOfMeasureCode,
- unitCost: unitCost ?? 0,
- companyId,
- createdBy: userId,
- customFields: {}
- };
- };
-
- const quoteMaterialResults = await Promise.all(
- node.children.map(mapMethodMaterialToQuoteMaterial)
- );
- const validQuoteMaterialIndices = quoteMaterialResults.reduce<
- number[]
- >((acc, m, i) => {
- if (m !== null) acc.push(i);
+ methodOperationsToQuoteOperations = sourceOperations.reduce<
+ Record<string, string>
+ >((acc, op, index) => {
+ const operationId = operationIds[index]?.id;
+ if (operationId) {
+ acc[op.id!] = operationId;
+ }
return acc;
- }, []);
- let materialsWithConfiguredFields = quoteMaterialResults.filter(
- (m): m is NonNullable<typeof m> => m !== null
- );
- const configuredChildren = validQuoteMaterialIndices.map(
- (i) => node.children[i]!
- );
+ }, {});
+ }
+ } // end if (parts.billOfProcess)
- const bomConfigurationKey = `billOfMaterial:${nodeLevelConfigurationKey}`;
- let bomConfiguration: string[] | null = null;
+ if (parts.billOfMaterial) {
+ const mapMethodMaterialToQuoteMaterial = async (
+ child: MethodTreeItem
+ ) => {
+ let [
+ itemId,
+ description,
+ quantity,
+ methodType,
+ unitOfMeasureCode
+ ] = await Promise.all([
+ getConfiguredValue({
+ id: child.data.methodMaterialId,
+ field: "itemId",
+ defaultValue: child.data.itemId
+ }),
+ getConfiguredValue({
+ id: child.data.methodMaterialId,
+ field: "description",
+ defaultValue: child.data.description
+ }),
+ getConfiguredValue({
+ id: child.data.methodMaterialId,
+ field: "quantity",
+ defaultValue: child.data.quantity
+ }),
+ getConfiguredValue({
+ id: child.data.methodMaterialId,
+ field: "methodType",
+ defaultValue: child.data.methodType
+ }),
+ getConfiguredValue({
+ id: child.data.methodMaterialId,
+ field: "unitOfMeasureCode",
+ defaultValue: child.data.unitOfMeasureCode
+ })
+ ]);
+
+ if (itemId === "") return null;
+ // A configured (or authored) quantity of 0 removes the line from
+ // the BOM (and its sub-tree, via configuredChildren below).
+ if (isZeroQuantity(quantity)) return null;
+
+ let itemType = child.data.itemType;
+ let unitCost = child.data.unitCost;
+
+ // TODO: if the methodType is Make and the default value is not Make, we need to do itemToQuoteMakeMethod for that material
- if (configurationCodeByField?.[bomConfigurationKey]) {
- const mod = await importTypeScript(
- configurationCodeByField[bomConfigurationKey]
+ if (itemId !== child.data.itemId) {
+ const item = await single<
+ "item",
+ Tables["item"]["Row"] & {
+ itemCost: Tables["itemCost"]["Row"][];
+ }
+ >(
+ trx,
+ "item",
+ { id: itemId, companyId },
+ {
+ embed: { itemCost: { table: "itemCost", on: "itemId" } }
+ }
);
- bomConfiguration = await mod.configure(hydratedConfiguration);
+ if (item.data) {
+ itemType = item.data.type;
+ unitCost =
+ item.data.itemCost[0]?.unitCost ?? child.data.unitCost;
+ if (description === child.data.description) {
+ description = item.data.name;
+ }
+ } else {
+ itemId = child.data.itemId;
+ }
}
- if (bomConfiguration) {
- // @ts-expect-error - we can't assign undefined to materialsWithConfiguredFields but we filter them in the next step
- materialsWithConfiguredFields = bomConfiguration
- .map((readableIdWithRevision, index) => {
- const material = materialsWithConfiguredFields.find(
- (material) => material.itemId === itemId
- );
- if (material) {
- return {
- ...material,
- order: index + 1
- };
- }
- })
- .filter(Boolean);
- }
+ return {
+ quoteId,
+ quoteLineId,
+ quoteMakeMethodId: parentQuoteMakeMethodId!,
+ quoteOperationId:
+ methodOperationsToQuoteOperations[child.data.operationId],
+ order: child.data.order,
+ itemId,
+ itemType,
+ kit: child.data.kit,
+ methodType,
+ description,
+ quantity,
+ storageUnitId: quoteLocationId
+ ? // @ts-ignore: storageUnitIds is a dynamic object with location keys
+ (child.data.storageUnitIds?.[quoteLocationId] as string) ||
+ null
+ : null,
+ unitOfMeasureCode,
+ unitCost: unitCost ?? 0,
+ companyId,
+ createdBy: userId,
+ customFields: {}
+ };
+ };
- const madeMaterials = materialsWithConfiguredFields.filter(
- (material) => material.methodType === "Make to Order"
+ const quoteMaterialResults = await Promise.all(
+ node.children.map(mapMethodMaterialToQuoteMaterial)
+ );
+ const validQuoteMaterialIndices = quoteMaterialResults.reduce<
+ number[]
+ >((acc, m, i) => {
+ if (m !== null) acc.push(i);
+ return acc;
+ }, []);
+ let materialsWithConfiguredFields = quoteMaterialResults.filter(
+ (m): m is NonNullable<typeof m> => m !== null
+ );
+ const configuredChildren = validQuoteMaterialIndices.map(
+ (i) => node.children[i]!
+ );
+
+ const bomConfigurationKey = `billOfMaterial:${nodeLevelConfigurationKey}`;
+ let bomConfiguration: string[] | null = null;
+
+ if (configurationCodeByField?.[bomConfigurationKey]) {
+ const mod = await importTypeScript(
+ configurationCodeByField[bomConfigurationKey]
);
+ bomConfiguration = await mod.configure(hydratedConfiguration);
+ }
- const pickedOrBoughtMaterials =
- materialsWithConfiguredFields.filter(
- (material) => material.methodType !== "Make to Order"
- );
+ if (bomConfiguration) {
+ // @ts-expect-error - we can't assign undefined to materialsWithConfiguredFields but we filter them in the next step
+ materialsWithConfiguredFields = bomConfiguration
+ .map((readableIdWithRevision, index) => {
+ const material = materialsWithConfiguredFields.find(
+ (material) => material.itemId === itemId
+ );
+ if (material) {
+ return {
+ ...material,
+ order: index + 1
+ };
+ }
+ })
+ .filter(Boolean);
+ }
- const madeChildren = configuredChildren.filter(
- (child) => child!.data.methodType === "Make to Order"
+ const madeMaterials = materialsWithConfiguredFields.filter(
+ (material) => material.methodType === "Make to Order"
+ );
+
+ const pickedOrBoughtMaterials =
+ materialsWithConfiguredFields.filter(
+ (material) => material.methodType !== "Make to Order"
);
- getMethodLogger.debug("[traverseMethod] materials", {
- totalChildren: materialsWithConfiguredFields.length,
- madeMaterialsCount: madeMaterials.length,
- madeChildrenCount: madeChildren.length,
- pickedOrBoughtCount: pickedOrBoughtMaterials.length
- });
+ const madeChildren = configuredChildren.filter(
+ (child) => child!.data.methodType === "Make to Order"
+ );
- if (madeMaterials.length > 0) {
- const madeMaterialsWithIds = madeMaterials.map((m) => ({
- ...m,
- id: nanoid()
- }));
+ getMethodLogger.debug("[traverseMethod] materials", {
+ totalChildren: materialsWithConfiguredFields.length,
+ madeMaterialsCount: madeMaterials.length,
+ madeChildrenCount: madeChildren.length,
+ pickedOrBoughtCount: pickedOrBoughtMaterials.length
+ });
- await trx
- .insertInto("quoteMaterial")
- .values(madeMaterialsWithIds)
- .execute();
+ if (madeMaterials.length > 0) {
+ const madeMaterialsWithIds = madeMaterials.map((m) => ({
+ ...m,
+ id: nanoid()
+ }));
- const newMakeMethodIds = madeChildren.map(() => nanoid());
- await renameMakeMethods(trx, {
- table: "quoteMakeMethod",
- companyId,
- rows: madeChildren.map((_, index) => ({
- parentMaterialId: madeMaterialsWithIds[index]!.id,
- id: newMakeMethodIds[index]!
- }))
- });
+ await trx
+ .insertInto("quoteMaterial")
+ .values(madeMaterialsWithIds)
+ .execute();
- for (const [index, child] of madeChildren.entries()) {
- const materialId = madeMaterialsWithIds[index]!.id;
- const newMakeMethodId = newMakeMethodIds[index]!;
+ const newMakeMethodIds = madeChildren.map(() => nanoid());
+ await renameMakeMethods(trx, {
+ table: "quoteMakeMethod",
+ companyId,
+ rows: madeChildren.map((_, index) => ({
+ parentMaterialId: madeMaterialsWithIds[index]!.id,
+ id: newMakeMethodIds[index]!
+ }))
+ });
- getMethodLogger.debug(
- "[traverseMethod] processing made child",
- {
- index,
- materialId,
- newMakeMethodId,
- childItemId: child!.data.itemId,
- parentItemId: itemId,
- willRecurse: child!.data.itemId !== itemId
- }
- );
+ for (const [index, child] of madeChildren.entries()) {
+ const materialId = madeMaterialsWithIds[index]!.id;
+ const newMakeMethodId = newMakeMethodIds[index]!;
- // A configuration rule may have moved this line onto another
- // made item; the sub-assembly under it is then that item's.
- const made = await configuredMadeChild(
- trx,
- companyId,
- child!,
- madeMaterialsWithIds[index]!.itemId
- );
- if (!made) continue;
- if (made !== child) {
- for (const [id, ops] of await readOperationsForTree(
- trx,
- made
- ))
- treeOperations.set(id, ops);
+ getMethodLogger.debug(
+ "[traverseMethod] processing made child",
+ {
+ index,
+ materialId,
+ newMakeMethodId,
+ childItemId: child!.data.itemId,
+ parentItemId: itemId,
+ willRecurse: child!.data.itemId !== itemId
}
+ );
- // prevent an infinite loop
- if (made.data.itemId !== itemId) {
- await traverseMethod(made, newMakeMethodId);
- }
+ // A configuration rule may have moved this line onto another
+ // made item; the sub-assembly under it is then that item's.
+ const made = await configuredMadeChild(
+ trx,
+ companyId,
+ child!,
+ madeMaterialsWithIds[index]!.itemId
+ );
+ if (!made) continue;
+ if (made !== child) {
+ for (const [id, ops] of await readOperationsForTree(
+ trx,
+ made
+ ))
+ treeOperations.set(id, ops);
+ }
+
+ // prevent an infinite loop
+ if (made.data.itemId !== itemId) {
+ await traverseMethod(made, newMakeMethodId);
}
}
+ }
- deferredQuoteMaterials.push(...pickedOrBoughtMaterials);
- } // end if (parts.billOfMaterial)
- }
+ deferredQuoteMaterials.push(...pickedOrBoughtMaterials);
+ } // end if (parts.billOfMaterial)
+ }
- function logTree(node: MethodTreeItem, depth = 0) {
- getMethodLogger.debug(
- " ".repeat(depth) +
- `[tree] ${node.data.itemId} (${node.data.methodType}, isRoot=${node.data.isRoot}, children=${node.children.length})`
- );
- for (const child of node.children) {
- logTree(child, depth + 1);
- }
+ function logTree(node: MethodTreeItem, depth = 0) {
+ getMethodLogger.debug(
+ " ".repeat(depth) +
+ `[tree] ${node.data.itemId} (${node.data.methodType}, isRoot=${node.data.isRoot}, children=${node.children.length})`
+ );
+ for (const child of node.children) {
+ logTree(child, depth + 1);
}
- logTree(methodTree);
+ }
+ logTree(methodTree);
- const treeOperations = await readOperationsForTree(trx, methodTree);
- const deferredQuoteMaterials: Database["public"]["Tables"]["quoteMaterial"]["Insert"][] =
- [];
- await traverseMethod(methodTree, quoteMakeMethod.data!.id);
- for (const chunk of chunked(deferredQuoteMaterials)) {
- await trx.insertInto("quoteMaterial").values(chunk).execute();
- }
- });
+ const treeOperations = await readOperationsForTree(trx, methodTree);
+ const deferredQuoteMaterials: Database["public"]["Tables"]["quoteMaterial"]["Insert"][] =
+ [];
+ await traverseMethod(methodTree, quoteMakeMethod.data!.id);
+ for (const chunk of chunked(deferredQuoteMaterials)) {
+ await trx.insertInto("quoteMaterial").values(chunk).execute();
+ }
+ });
await calculateQuoteLinePrices(
db,
@@ -16263,7 +16264,7 @@ export async function getMethod(
return acc;
}, {});
- await db.transaction().execute(async (trx) => {
+ await withTransaction(db, async (trx) => {
// Delete existing quoteMakeMethodOperation, quoteMakeMethodMaterial
await Promise.all([
parts.billOfMaterial
@@ -16712,7 +16713,7 @@ export async function getMethod(
makeMethodByItemId[m.itemId] = m.id;
});
- await db.transaction().execute(async (trx) => {
+ await withTransaction(db, async (trx) => {
let makeMethodsToDelete: string[] = [];
const materialInserts: Database["public"]["Tables"]["methodMaterial"]["Insert"][] =
[];
@@ -17041,7 +17042,7 @@ export async function getMethod(
}
});
- await db.transaction().execute(async (trx) => {
+ await withTransaction(db, async (trx) => {
let makeMethodsToDelete: string[] = [];
const materialInserts: Database["public"]["Tables"]["methodMaterial"]["Insert"][] =
[];
@@ -17476,7 +17477,7 @@ export async function getMethod(
const sourceStepsToJobSteps: Record<string, string> = {};
const sourceOperationIdToJobOperationId: Record<string, string> = {};
- await db.transaction().execute(async (trx) => {
+ await withTransaction(db, async (trx) => {
await itemDefaults.load(
trx,
treeItemIds(jobMethodTree, supersessionRedirect)
@@ -18100,7 +18101,9 @@ export async function getMethod(
throw new Error("Failed to get source materials or operations");
}
- await db.transaction().execute(async (trx) => {
+ // A new version inserts its header in a transaction and copies inside
+ // it, so a failed copy leaves no empty version behind.
+ await withTransaction(db, async (trx) => {
// The lines about to be replaced, whose configuration rules go with them.
const [targetMaterialIds, targetOperationIds] = await Promise.all([
trx
@@ -18378,7 +18381,7 @@ export async function getMethod(
const existingSteps = operation.data?.jobOperationStep ?? [];
- await db.transaction().execute(async (trx) => {
+ await withTransaction(db, async (trx) => {
// Update or delete existing attributes
for (const existingStep of existingSteps) {
const matchingProcedureStep = procedure.data.procedureStep.find(
@@ -18582,7 +18585,7 @@ export async function getMethod(
}
});
- await db.transaction().execute(async (trx) => {
+ await withTransaction(db, async (trx) => {
let makeMethodsToDelete: string[] = [];
const materialInserts: Database["public"]["Tables"]["methodMaterial"]["Insert"][] =
[];
@@ -18924,7 +18927,7 @@ export async function getMethod(
}
});
- await db.transaction().execute(async (trx) => {
+ await withTransaction(db, async (trx) => {
let makeMethodsToDelete: string[] = [];
const materialInserts: Database["public"]["Tables"]["methodMaterial"]["Insert"][] =
[];
@@ -19254,7 +19257,7 @@ export async function getMethod(
}
> = {};
- await db.transaction().execute(async (trx) => {
+ await withTransaction(db, async (trx) => {
await itemDefaults.load(
trx,
treeItemIds(quoteMethodTree, supersessionRedirect)
@@ -19811,7 +19814,7 @@ export async function getMethod(
const quoteMaterialIdToQuoteMaterialId: Record<string, string> = {};
const quoteMakeMethodIdToQuoteMakeMethodId: Record<string, string> = {};
- await db.transaction().execute(async (trx) => {
+ await withTransaction(db, async (trx) => {
// Delete existing quoteMakeMethods, quoteMaterials, and quoteOperations for this quote line
await Promise.all([
parts.billOfMaterial
@@ -20120,7 +20123,7 @@ export async function getMethod(
throw new Error("Failed to get source quote line pricing");
}
- await db.transaction().execute(async (trx) => {
+ await withTransaction(db, async (trx) => {
let quoteId: string;
let revisionId = 0;
if (asRevision) {
@@ -20307,7 +20310,7 @@ export async function getMethod(
}
});
- await db.transaction().execute(async (trx) => {
+ await withTransaction(db, async (trx) => {
for await (const [oldLineId, newLineId] of Object.entries(
oldLineToNewLineMap
)) {
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index 6f0ad7e8c4..0a59edd1cf 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -23,7 +23,12 @@ import { consumeOAuthState } from "@carbon/auth/oauth-state.server";
import type { Database, Json } from "@carbon/database";
import { activeJobStatuses, getCompanyTimeZone } from "@carbon/database";
import { ACCOUNT_DEFAULT_COLUMNS } from "@carbon/database/account-import";
-import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import {
+ type Kysely,
+ type KyselyDatabase,
+ type KyselyTx,
+ withTransaction
+} from "@carbon/database/client";
import { single, updateRows } from "@carbon/database/rows";
import {
accountDefaults,
@@ -233,7 +238,7 @@ import {
import { canEditChangeNoticeEngineering } from "~/modules/items/items.models";
import {
cascadeItemTrackingType,
- copyMakeMethod,
+ createMakeMethodVersion,
createRevision,
deleteChangeNotice,
deleteItem,
@@ -244,7 +249,6 @@ import {
requireChangeNoticeEditable,
updateDefaultRevision,
updateItemMethodAndSourcing,
- upsertMakeMethodVersion,
upsertPart
} from "~/modules/items/items.service";
import { insertEmployeeJob } from "~/modules/people/people.service";
@@ -4171,8 +4175,8 @@ export async function loadMethodWriteRefusals(
/**
* The Draft a push writes into when the item's method is Active: the one this
- * integration made from that method (`pickReusableDraft`), else a new copy. The
- * reusable marker is written last; a failure before it deletes the new Draft.
+ * integration made from that method (`pickReusableDraft`), else a new copy. A
+ * new copy, its line ownership and its reusable marker are one transaction.
*/
export async function ensureDraftMakeMethod(
client: Client,
@@ -4232,187 +4236,128 @@ export async function ensureDraftMakeMethod(
}
const version = (highest.data?.version ?? 0) + 1;
- const draft = await upsertMakeMethodVersion(client, {
- copyFromId: activeMethodId,
- // No `activeVersionId`: it sets a version Active, and the push leaves live methods alone.
- version,
- companyId,
- createdBy: userId
- });
- if (draft.error || !draft.data?.id) {
- return {
- ok: false,
- error: draft.error?.message ?? "could not create a draft version"
- };
- }
- const draftId = draft.data.id;
-
- // `upsertMakeMethodVersion` copies only the method row; the BOM and routing come here.
- const copied = await copyMakeMethod(client, db, {
- sourceId: activeMethodId,
- targetId: draftId,
- companyId,
- userId,
- billOfMaterial: true,
- billOfProcess: true,
- parameters: true,
- tools: true,
- steps: true,
- workInstructions: true
- });
- const failure = copied.error
- ? `its method could not be copied (${copied.error.message})`
- : await carryLineOwnership(client, serviceRole, {
- sourceMethodId: activeMethodId,
- targetMethodId: draftId,
+ // The Draft, its copied BOM and routing, the line ownership and the marker
+ // are one transaction: a failure in any of them leaves no Draft behind.
+ try {
+ const draftId = await withTransaction(db, async (trx) => {
+ const draft = await createMakeMethodVersion(client, trx, {
+ copyFromId: activeMethodId,
+ // No `activate`: the push leaves live methods alone.
+ version,
companyId,
- userId
+ createdBy: userId
});
- const marked = failure
- ? null
- : await client.from("externalIntegrationMapping").insert({
- entityType: DRAFT_MARKER_ENTITY_TYPE,
- entityId: draftId,
- integration: ONSHAPE_V2_INTEGRATION_ID,
- // Not the source id: two Drafts of one method would collide on the unique index.
- externalId: draftId,
- metadata: { sourceMethodId: activeMethodId, itemId } as Json,
- lastSyncedAt: datetime.timestamp(),
+ if (draft.error) {
+ throw new Error(
+ draft.error.message || "could not create a draft version"
+ );
+ }
+ await carryLineOwnership(trx, {
+ sourceMethodId: activeMethodId,
+ targetMethodId: draft.data.id,
companyId,
- createdBy: userId
+ userId
});
- const problem =
- failure ??
- (marked?.error
- ? `it could not be marked as Onshape's (${marked.error.message})`
- : null);
- if (!problem) {
+ await trx
+ .insertInto("externalIntegrationMapping")
+ .values({
+ entityType: DRAFT_MARKER_ENTITY_TYPE,
+ entityId: draft.data.id,
+ integration: ONSHAPE_V2_INTEGRATION_ID,
+ // Not the source id: two Drafts of one method would collide on the unique index.
+ externalId: draft.data.id,
+ metadata: { sourceMethodId: activeMethodId, itemId } as Json,
+ lastSyncedAt: datetime.timestamp(),
+ companyId,
+ createdBy: userId
+ })
+ .execute();
+ return draft.data.id;
+ });
return { ok: true, id: draftId, created: true, version };
+ } catch (error) {
+ onshapeDraftMethodLogger.error("Failed to create an Onshape Draft", {
+ companyId,
+ activeMethodId,
+ version,
+ error
+ });
+ return {
+ ok: false,
+ error:
+ error instanceof Error && error.message
+ ? error.message
+ : "could not create a draft version"
+ };
}
-
- // A half-built Draft, released, would ship without what failed to copy. Service
- // role: line mappings have no user DELETE policy. The lines cascade.
- const discarded = await discardDraft(serviceRole, {
- draftId,
- companyId
- });
- return {
- ok: false,
- error: discarded
- ? `a draft version was created but ${problem}, so it was removed; push again`
- : `a draft version was created but ${problem}, and it could not be removed — delete version ${version} before pushing again`
- };
-}
-
-async function discardDraft(
- serviceRole: Client,
- args: { draftId: string; companyId: string }
-): Promise<boolean> {
- const { draftId, companyId } = args;
- const mappings = await serviceRole
- .from("externalIntegrationMapping")
- .delete()
- .eq("companyId", companyId)
- .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
- .eq("entityType", "methodMaterial")
- .eq("metadata->>makeMethodId", draftId);
- const removed = await serviceRole
- .from("makeMethod")
- .delete()
- .eq("id", draftId)
- .eq("companyId", companyId);
- const error = mappings.error ?? removed.error;
- if (error) {
- onshapeDraftMethodLogger.error(
- "Failed to discard a half-built Onshape Draft",
- {
- companyId,
- draftId,
- error
- }
- );
- return false;
- }
- return true;
}
/**
* Copy this integration's line mappings onto the copied lines: ownership is
* keyed on line id, and unmapped copies would read as manual and be duplicated.
+ * Runs in the transaction that copied the lines, so it reads them there.
*/
async function carryLineOwnership(
- client: Client,
- serviceRole: Client,
+ trx: KyselyTx,
args: {
sourceMethodId: string;
targetMethodId: string;
companyId: string;
userId: string;
}
-): Promise<string | null> {
+): Promise<void> {
const { sourceMethodId, targetMethodId, companyId, userId } = args;
- const mappings = await serviceRole
- .from("externalIntegrationMapping")
- .select("entityId, externalId, metadata, lastSyncedAt")
- .eq("companyId", companyId)
- .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
- .eq("entityType", "methodMaterial")
- .eq("metadata->>makeMethodId", sourceMethodId);
- if (mappings.error) return mappings.error.message;
- if ((mappings.data ?? []).length === 0) return null;
-
- const [sourceLines, targetLines] = await Promise.all([
- client
- .from("methodMaterial")
- .select("id, itemId, order, quantity")
- .eq("makeMethodId", sourceMethodId)
- .eq("companyId", companyId),
- client
- .from("methodMaterial")
- .select("id, itemId, order")
- .eq("makeMethodId", targetMethodId)
- .eq("companyId", companyId)
- ]);
- if (sourceLines.error) return sourceLines.error.message;
- if (targetLines.error) return targetLines.error.message;
+ const mappings = await trx
+ .selectFrom("externalIntegrationMapping")
+ .select(["entityId", "externalId", "metadata", "lastSyncedAt"])
+ .where("companyId", "=", companyId)
+ .where("integration", "=", ONSHAPE_V2_INTEGRATION_ID)
+ .where("entityType", "=", "methodMaterial")
+ .where(sql<string>`"metadata"->>'makeMethodId'`, "=", sourceMethodId)
+ .execute();
+ if (mappings.length === 0) return;
+
+ const lines = (makeMethodId: string) =>
+ trx
+ .selectFrom("methodMaterial")
+ .select(["id", "itemId", "order", "quantity"])
+ .where("makeMethodId", "=", makeMethodId)
+ .where("companyId", "=", companyId)
+ .execute();
+ const [sourceLines, targetLines] = [
+ await lines(sourceMethodId),
+ await lines(targetMethodId)
+ ];
- const owned = new Set((mappings.data ?? []).map((row) => row.entityId));
const paired = pairOwnedCopiedLines(
- sourceLines.data ?? [],
- targetLines.data ?? [],
- owned
+ sourceLines,
+ targetLines,
+ new Set(mappings.map((row) => row.entityId))
);
const inserts = [];
- for (const mapping of mappings.data ?? []) {
+ for (const mapping of mappings) {
const targetLineId = paired.get(mapping.entityId);
// Unpaired: left unmapped, so it reads as manual and is kept, not duplicated.
if (!targetLineId) continue;
- const metadata = {
- ...((mapping.metadata as Record<string, unknown> | null) ?? {}),
- makeMethodId: targetMethodId
- };
inserts.push({
entityType: "methodMaterial",
entityId: targetLineId,
integration: ONSHAPE_V2_INTEGRATION_ID,
externalId: mapping.externalId,
- metadata: metadata as Json,
+ metadata: {
+ ...((mapping.metadata as Record<string, unknown> | null) ?? {}),
+ makeMethodId: targetMethodId
+ } as Json,
lastSyncedAt: mapping.lastSyncedAt,
companyId,
createdBy: userId
});
}
- if (inserts.length === 0) return null;
+ if (inserts.length === 0) return;
- const written = await client
- .from("externalIntegrationMapping")
- .insert(inserts);
- if (written.error) {
- return `${inserts.length} of its lines could not be linked to Onshape (${written.error.message})`;
- }
- return null;
+ await trx.insertInto("externalIntegrationMapping").values(inserts).execute();
}
type MethodMaterialInsert =
diff --git a/apps/erp/test/database/fixtures/local-supabase.ts b/apps/erp/test/database/fixtures/local-supabase.ts
index f60e4affd9..8b49863959 100644
--- a/apps/erp/test/database/fixtures/local-supabase.ts
+++ b/apps/erp/test/database/fixtures/local-supabase.ts
@@ -32,9 +32,20 @@ export function localServiceRoleKey(): string | null {
* when there is no local stack: the tests that need it skip.
*/
export function localServiceRoleClient(): SupabaseClient<Database> | null {
+ return localClient("SUPABASE_SERVICE_ROLE_KEY");
+}
+
+/** The same PostgREST with the anonymous key: a caller with no permissions. */
+export function localAnonClient(): SupabaseClient<Database> | null {
+ return localClient("SUPABASE_ANON_KEY");
+}
+
+function localClient(
+ keyName: "SUPABASE_SERVICE_ROLE_KEY" | "SUPABASE_ANON_KEY"
+): SupabaseClient<Database> | null {
const env = localEnv();
const port = env?.PORT_API;
- const key = env?.SUPABASE_SERVICE_ROLE_KEY;
+ const key = env?.[keyName];
if (!port || !key) return null;
return createClient<Database>(`http://localhost:${port}`, key, {
auth: { autoRefreshToken: false, persistSession: false }
diff --git a/apps/erp/test/database/make-method-version.test.ts b/apps/erp/test/database/make-method-version.test.ts
new file mode 100644
index 0000000000..0c3126ff53
--- /dev/null
+++ b/apps/erp/test/database/make-method-version.test.ts
@@ -0,0 +1,567 @@
+// 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.
+
+// Runs against the local database and PostgREST; skipped without them. The
+// copy runs as the system through the database, so a copy failure is made
+// real with a trigger that refuses the step slide insert.
+
+import { createServiceContext } from "@carbon/api/service-fn.server";
+import { sql } from "kysely";
+import { expect, it } from "vitest";
+import { createMethodVersion } from "../../app/modules/items/items.server";
+import {
+ createChangeNoticeDraftMethod,
+ createMakeMethodVersion
+} from "../../app/modules/items/items.service";
+import { ensureDraftMakeMethod } from "../../app/modules/settings/settings.service";
+import {
+ alwaysPostFixture,
+ type Fixture,
+ seed,
+ USER
+} from "./fixtures/always-post";
+import { hasLocalDatabase } from "./fixtures/local-database";
+import {
+ localAnonClient,
+ localServiceRoleClient
+} from "./fixtures/local-supabase";
+
+const system = hasLocalDatabase ? localServiceRoleClient() : null;
+const refused = hasLocalDatabase ? localAnonClient() : null;
+
+const PINS = [
+ { id: "pin-1", x: 0.25, y: 0.5, color: "#ef4444" },
+ { id: "pin-2", x: 0.7, y: 0.75, color: "#ef4444", label: "Torque" }
+];
+
+const versionTest = (name: string, fn: (f: Fixture) => Promise<void>) =>
+ it.skipIf(!system || !refused)(
+ name,
+ async () => {
+ const f = await alwaysPostFixture();
+ try {
+ await fn(f);
+ } finally {
+ await f.cleanup();
+ }
+ },
+ 60_000
+ );
+
+async function sourceMethod(f: Fixture, status: "Draft" | "Active") {
+ const method = await f.db
+ .selectFrom("makeMethod")
+ .select("id")
+ .where("itemId", "=", f.assemblyId)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+ const processId = `${f.prefix}-process`;
+ await seed(f, async (trx) => {
+ await trx
+ .updateTable("makeMethod")
+ .set({ status })
+ .where("id", "=", method.id)
+ .where("companyId", "=", f.companyId)
+ .execute();
+ await trx
+ .insertInto("process")
+ .values({
+ id: processId,
+ name: "Assemble",
+ defaultStandardFactor: "Hours/Piece",
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .execute();
+ const operation = await trx
+ .insertInto("methodOperation")
+ .values({
+ makeMethodId: method.id,
+ processId,
+ description: "Assemble",
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ const step = await trx
+ .insertInto("methodOperationStep")
+ .values({
+ operationId: operation.id,
+ name: "Check the bracket",
+ type: "Task",
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ await trx
+ .insertInto("methodOperationStepSlide")
+ .values({
+ stepId: step.id,
+ imagePath: `${f.companyId}/step.png`,
+ annotations: JSON.stringify(PINS),
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .execute();
+ await trx
+ .insertInto("methodMaterial")
+ .values({
+ makeMethodId: method.id,
+ itemId: f.partId,
+ itemType: "Part",
+ quantity: 2,
+ unitOfMeasureCode: "EA",
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .execute();
+ });
+ return method.id;
+}
+
+async function versions(f: Fixture) {
+ return f.db
+ .selectFrom("makeMethod")
+ .select(["id", "version", "status"])
+ .where("itemId", "=", f.assemblyId)
+ .where("companyId", "=", f.companyId)
+ .orderBy("version")
+ .execute();
+}
+
+async function copied(f: Fixture, makeMethodId: string) {
+ const materials = await f.db
+ .selectFrom("methodMaterial")
+ .select("id")
+ .where("makeMethodId", "=", makeMethodId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+ const slides = await f.db
+ .selectFrom("methodOperationStepSlide as slide")
+ .innerJoin("methodOperationStep as step", "step.id", "slide.stepId")
+ .innerJoin("methodOperation as operation", "operation.id", "step.operationId")
+ .select("slide.annotations")
+ .where("operation.makeMethodId", "=", makeMethodId)
+ .where("slide.companyId", "=", f.companyId)
+ .execute();
+ return {
+ materials: materials.length,
+ annotations: slides.map((slide) => slide.annotations)
+ };
+}
+
+// Every line in the company, on any method: rolled-back copies leave none.
+async function companyLines(f: Fixture) {
+ const count = async (
+ table: "methodMaterial" | "methodOperation" | "methodOperationStep"
+ ) =>
+ (
+ await f.db
+ .selectFrom(table)
+ .select((eb) => eb.fn.countAll<number>().as("count"))
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow()
+ ).count;
+ return {
+ materials: Number(await count("methodMaterial")),
+ operations: Number(await count("methodOperation")),
+ steps: Number(await count("methodOperationStep"))
+ };
+}
+
+// The operation and its step are copied before the slide, so a refused slide
+// insert fails the copy after it has written rows into the new version.
+async function withFailingSlideCopy(f: Fixture, fn: () => Promise<void>) {
+ const name = `fail_slide_copy_${f.prefix.replace(/[^a-z0-9]/gi, "_")}`;
+ await sql
+ .raw(
+ `CREATE FUNCTION "${name}"() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'slide copy refused'; END $$`
+ )
+ .execute(f.db);
+ await sql
+ .raw(
+ `CREATE TRIGGER "${name}" BEFORE INSERT ON "methodOperationStepSlide" FOR EACH ROW WHEN (NEW."companyId" = '${f.companyId}') EXECUTE FUNCTION "${name}"()`
+ )
+ .execute(f.db);
+ try {
+ await fn();
+ } finally {
+ await sql
+ .raw(`DROP TRIGGER "${name}" ON "methodOperationStepSlide"`)
+ .execute(f.db);
+ await sql.raw(`DROP FUNCTION "${name}"()`).execute(f.db);
+ }
+}
+
+const version = (
+ f: Fixture,
+ copyFromId: string,
+ options: { activate?: boolean; changeOrderId?: string } = {}
+) => ({
+ copyFromId,
+ version: 2,
+ ...options,
+ companyId: f.companyId,
+ createdBy: USER
+});
+
+versionTest("copies the source and sets a Draft source Active", async (f) => {
+ const source = await sourceMethod(f, "Draft");
+
+ const result = await createMakeMethodVersion(
+ system!,
+ f.db,
+ version(f, source, { activate: true })
+ );
+
+ expect(result.error).toBeNull();
+ const draftId = result.data!.id;
+ expect(result.data).toMatchObject({ itemId: f.assemblyId, type: "Part" });
+ expect(await versions(f)).toEqual([
+ { id: source, version: 1, status: "Active" },
+ { id: draftId, version: 2, status: "Draft" }
+ ]);
+ expect(await copied(f, draftId)).toEqual({
+ materials: 1,
+ annotations: [PINS]
+ });
+});
+
+versionTest("rolls back the version, the activation and the copied lines when the copy fails", async (f) => {
+ const source = await sourceMethod(f, "Draft");
+ const before = await companyLines(f);
+
+ await withFailingSlideCopy(f, async () => {
+ const result = await createMakeMethodVersion(
+ system!,
+ f.db,
+ version(f, source, { activate: true })
+ );
+ expect(result.error).not.toBeNull();
+ });
+
+ expect(await versions(f)).toEqual([
+ { id: source, version: 1, status: "Draft" }
+ ]);
+ expect(await companyLines(f)).toEqual(before);
+});
+
+versionTest("leaves an Active source Active when the copy fails", async (f) => {
+ const source = await sourceMethod(f, "Active");
+
+ await withFailingSlideCopy(f, async () => {
+ const result = await createMakeMethodVersion(
+ system!,
+ f.db,
+ version(f, source, { activate: true })
+ );
+ expect(result.error).not.toBeNull();
+ });
+
+ expect(await versions(f)).toEqual([
+ { id: source, version: 1, status: "Active" }
+ ]);
+});
+
+versionTest("writes the change notice on the new Draft in the same insert", async (f) => {
+ const source = await sourceMethod(f, "Active");
+ const changeNotice = await f.db
+ .insertInto("changeOrder")
+ .values({
+ changeOrderId: `${f.prefix}-CN`,
+ name: "Swap the bracket",
+ openDate: "2026-10-22",
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+
+ const result = await createMakeMethodVersion(
+ system!,
+ f.db,
+ version(f, source, { changeOrderId: changeNotice.id })
+ );
+
+ expect(result.error).toBeNull();
+ const draft = await f.db
+ .selectFrom("makeMethod")
+ .select(["status", "changeOrderId"])
+ .where("id", "=", result.data!.id)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+ expect(draft).toEqual({ status: "Draft", changeOrderId: changeNotice.id });
+});
+
+versionTest("joins a transaction it is handed, and rolls back with it", async (f) => {
+ const source = await sourceMethod(f, "Draft");
+ const before = await companyLines(f);
+
+ await expect(
+ f.db.transaction().execute(async (trx) => {
+ const result = await createMakeMethodVersion(
+ system!,
+ trx,
+ version(f, source, { activate: true })
+ );
+ expect(result.error).toBeNull();
+ throw new Error("the caller's later write failed");
+ })
+ ).rejects.toThrow("the caller's later write failed");
+
+ expect(await versions(f)).toEqual([
+ { id: source, version: 1, status: "Draft" }
+ ]);
+ expect(await companyLines(f)).toEqual(before);
+});
+
+versionTest("writes nothing for a caller who cannot read the version", async (f) => {
+ const source = await sourceMethod(f, "Draft");
+
+ const result = await createMakeMethodVersion(
+ refused!,
+ f.db,
+ version(f, source, { activate: true })
+ );
+
+ expect(result.error).not.toBeNull();
+ expect(await versions(f)).toEqual([
+ { id: source, version: 1, status: "Draft" }
+ ]);
+});
+
+/** The operation's context, as the system on behalf of the test user. */
+function contextOf(f: Fixture) {
+ return createServiceContext({
+ actor: { type: "system", onBehalfOf: USER },
+ company: { id: f.companyId, groupId: f.groupId },
+ caller: system!,
+ system: () => system!,
+ pg: () => f.db,
+ kv: () => {
+ throw new Error("Creating a version reads no cache");
+ }
+ });
+}
+
+versionTest("refuses to set Active a version other than the one copied", async (f) => {
+ const source = await sourceMethod(f, "Draft");
+
+ const result = await createMethodVersion(contextOf(f), {
+ copyFromId: source,
+ activeVersionId: `${f.prefix}-other`,
+ version: 2
+ });
+
+ expect(result.error?.category).toBe("rule");
+ expect(await versions(f)).toEqual([
+ { id: source, version: 1, status: "Draft" }
+ ]);
+});
+
+versionTest("reports a failed copy as internal", async (f) => {
+ const source = await sourceMethod(f, "Draft");
+
+ await withFailingSlideCopy(f, async () => {
+ const result = await createMethodVersion(contextOf(f), {
+ copyFromId: source,
+ activeVersionId: source,
+ version: 2
+ });
+ expect(result.error).toMatchObject({
+ category: "internal",
+ message: "Failed to create new version"
+ });
+ });
+
+ expect(await versions(f)).toEqual([
+ { id: source, version: 1, status: "Draft" }
+ ]);
+});
+
+async function changeNotice(f: Fixture) {
+ return f.db
+ .insertInto("changeOrder")
+ .values({
+ changeOrderId: `${f.prefix}-CN-${crypto.randomUUID().slice(0, 8)}`,
+ name: "Swap the bracket",
+ openDate: "2026-10-22",
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+}
+
+versionTest("a Version change notice activates a Draft base and owns its new Draft", async (f) => {
+ const source = await sourceMethod(f, "Draft");
+ const notice = await changeNotice(f);
+
+ const result = await createChangeNoticeDraftMethod(system!, f.db, {
+ changeNoticeId: notice.id,
+ itemId: f.assemblyId,
+ changeType: "Version",
+ companyId: f.companyId,
+ userId: USER
+ });
+
+ expect(result.error).toBeNull();
+ const draftId = result.data!.draftMakeMethodId!;
+ expect(result.data).toMatchObject({ baseMakeMethodId: source });
+ expect(await versions(f)).toEqual([
+ { id: source, version: 1, status: "Active" },
+ { id: draftId, version: 2, status: "Draft" }
+ ]);
+ const draft = await f.db
+ .selectFrom("makeMethod")
+ .select("changeOrderId")
+ .where("id", "=", draftId)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+ expect(draft.changeOrderId).toBe(notice.id);
+ expect(await copied(f, draftId)).toEqual({
+ materials: 1,
+ annotations: [PINS]
+ });
+});
+
+versionTest("a failed copy leaves a Version change notice no Draft and the base a Draft", async (f) => {
+ const source = await sourceMethod(f, "Draft");
+ const notice = await changeNotice(f);
+
+ await withFailingSlideCopy(f, async () => {
+ const result = await createChangeNoticeDraftMethod(system!, f.db, {
+ changeNoticeId: notice.id,
+ itemId: f.assemblyId,
+ changeType: "Version",
+ companyId: f.companyId,
+ userId: USER
+ });
+ expect(result.error).not.toBeNull();
+ });
+
+ expect(await versions(f)).toEqual([
+ { id: source, version: 1, status: "Draft" }
+ ]);
+});
+
+// The source's one line, owned by an earlier Onshape push. Line ownership rows
+// carry no externalId, as `insertOwnedMethodLines` writes them.
+async function ownSourceLine(f: Fixture, sourceId: string) {
+ const line = await f.db
+ .selectFrom("methodMaterial")
+ .select("id")
+ .where("makeMethodId", "=", sourceId)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+ await f.db
+ .insertInto("externalIntegrationMapping")
+ .values({
+ entityType: "methodMaterial",
+ entityId: line.id,
+ integration: ONSHAPE_V2,
+ metadata: JSON.stringify({ makeMethodId: sourceId }),
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .execute();
+}
+
+const ONSHAPE_V2 = "onshape-v2";
+
+async function onshapeMappings(f: Fixture) {
+ return f.db
+ .selectFrom("externalIntegrationMapping")
+ .select(["entityType", "entityId", "metadata"])
+ .where("companyId", "=", f.companyId)
+ .where("integration", "=", ONSHAPE_V2)
+ .orderBy("entityType")
+ .orderBy("createdAt")
+ .execute();
+}
+
+versionTest("the Onshape Draft carries line ownership and its marker with the copy", async (f) => {
+ const source = await sourceMethod(f, "Active");
+ await ownSourceLine(f, source);
+
+ const result = await ensureDraftMakeMethod(system!, f.db, {
+ itemId: f.assemblyId,
+ activeMethodId: source,
+ companyId: f.companyId,
+ userId: USER,
+ reusableDraft: null
+ });
+
+ expect(result).toMatchObject({ ok: true, created: true, version: 2 });
+ const draftId = (result as { id: string }).id;
+ expect(await versions(f)).toEqual([
+ { id: source, version: 1, status: "Active" },
+ { id: draftId, version: 2, status: "Draft" }
+ ]);
+ const copiedLine = await f.db
+ .selectFrom("methodMaterial")
+ .select("id")
+ .where("makeMethodId", "=", draftId)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+ const mappings = await onshapeMappings(f);
+ expect(mappings).toHaveLength(3);
+ expect(mappings).toEqual(
+ expect.arrayContaining([
+ {
+ entityType: "makeMethod",
+ entityId: draftId,
+ metadata: { sourceMethodId: source, itemId: f.assemblyId }
+ },
+ {
+ entityType: "methodMaterial",
+ entityId: copiedLine.id,
+ metadata: { makeMethodId: draftId }
+ }
+ ])
+ );
+});
+
+versionTest("the Onshape Draft leaves nothing behind when its marker cannot be written", async (f) => {
+ const source = await sourceMethod(f, "Active");
+ await ownSourceLine(f, source);
+ const before = { lines: await companyLines(f), mappings: await onshapeMappings(f) };
+
+ const name = `fail_marker_${f.prefix.replace(/[^a-z0-9]/gi, "_")}`;
+ await sql
+ .raw(
+ `CREATE FUNCTION "${name}"() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'marker refused'; END $$`
+ )
+ .execute(f.db);
+ await sql
+ .raw(
+ `CREATE TRIGGER "${name}" BEFORE INSERT ON "externalIntegrationMapping" FOR EACH ROW WHEN (NEW."companyId" = '${f.companyId}' AND NEW."entityType" = 'makeMethod') EXECUTE FUNCTION "${name}"()`
+ )
+ .execute(f.db);
+ try {
+ const result = await ensureDraftMakeMethod(system!, f.db, {
+ itemId: f.assemblyId,
+ activeMethodId: source,
+ companyId: f.companyId,
+ userId: USER,
+ reusableDraft: null
+ });
+ expect(result).toMatchObject({ ok: false });
+ } finally {
+ await sql
+ .raw(`DROP TRIGGER "${name}" ON "externalIntegrationMapping"`)
+ .execute(f.db);
+ await sql.raw(`DROP FUNCTION "${name}"()`).execute(f.db);
+ }
+
+ expect(await versions(f)).toEqual([
+ { id: source, version: 1, status: "Active" }
+ ]);
+ expect({
+ lines: await companyLines(f),
+ mappings: await onshapeMappings(f)
+ }).toEqual(before);
+});
diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.md
index 8f21976696..ab7bad8cbb 100644
--- a/packages/database/AGENTS.md
+++ b/packages/database/AGENTS.md
@@ -8,7 +8,7 @@ DB types, Supabase/Kysely clients, audit config, event system types, rate limiti
- Tables: composite PK `("id", "companyId")`, `id` default `id()` or `id('prefix')` — never raw UUID. Audit columns (`createdBy`/`createdAt`/`updatedBy`/`updatedAt`) with inline `REFERENCES "user"("id")`.
- RLS: every public table's policies are a rule in `src/authz/manifest.ts` (usually `company("<module>")` — the four standard policies) and the RLS helpers are `src/authz/helpers/<name>.sql`. `pnpm db:migrate` syncs them locally; `pnpm --filter @carbon/database authz migration <name>` ships them to production (`migration.test.ts` fails until it does). See `.claude/rules/authz-manifest.md`.
- Event-system functions (dispatch, subscriptions, queue wake-up, audit log, search index, embeddings) are one file each in `src/event-system/functions/` (`<name>.sql`, `util.<name>.sql` for the `util` schema), synced and shipped by the same `authz sync` / `authz migration` commands. Edit the file; never redefine one in a migration.
-- Import `Database` type from `@carbon/database`; `KyselyDatabase` / `Kysely` from `@carbon/database/client`. Never hand-edit `src/types.ts` — it's generated.
+- Import `Database` type from `@carbon/database`; `KyselyDatabase` / `Kysely` from `@carbon/database/client`. A function that may be handed a transaction runs its writes through `withTransaction(db, fn)` from the same file: it joins the transaction `db` already is, else opens one (Kysely refuses `transaction()` on a `Transaction`). Never hand-edit `src/types.ts` — it's generated.
- `scriptRun` is a deliberate exception to the table conventions above: no `companyId`, no
composite PK, SELECT-only RLS. It is the per-database ledger of one-off scripts that
`ci/src/migrations.ts` runs after `supabase db push` — see `scripts/one-off/README.md`.
diff --git a/packages/database/src/accounting-cutover/fixed-assets.ts b/packages/database/src/accounting-cutover/fixed-assets.ts
index 0c442c38e7..790e4c1fe0 100644
--- a/packages/database/src/accounting-cutover/fixed-assets.ts
+++ b/packages/database/src/accounting-cutover/fixed-assets.ts
@@ -7,14 +7,10 @@
// and the accumulated depreciation the wizard edits before the enable.
import { sql } from "kysely";
+import { withTransaction } from "../client";
import { assetsLeavingWithoutJournal } from "../legacy-documents";
import { EPSILON, round } from "../precision";
-import {
- type CutoverArgs,
- type CutoverDb,
- refuseAfterCutover,
- withTransaction
-} from "./shared";
+import { type CutoverArgs, type CutoverDb, refuseAfterCutover } from "./shared";
export type CutoverFixedAsset = {
id: string;
diff --git a/packages/database/src/accounting-cutover/shared.ts b/packages/database/src/accounting-cutover/shared.ts
index 21fd910fb7..d5a7185171 100644
--- a/packages/database/src/accounting-cutover/shared.ts
+++ b/packages/database/src/accounting-cutover/shared.ts
@@ -20,14 +20,6 @@ export const ACCOUNTING_ALREADY_SET_UP = "Accounting is already set up.";
export const OPENING_BALANCE_SOURCE = "Opening Balance" as const;
-export async function withTransaction<T>(
- db: CutoverDb,
- fn: (trx: Transaction<KyselyDatabase>) => Promise<T>
-): Promise<T> {
- if (db.isTransaction) return fn(db as Transaction<KyselyDatabase>);
- return db.transaction().execute(fn);
-}
-
export async function getCompany(db: CutoverDb, companyId: string) {
const company = await db
.selectFrom("company")
diff --git a/packages/database/src/accounting-cutover/trial-balance.ts b/packages/database/src/accounting-cutover/trial-balance.ts
index cbf0d8664a..fb671dd032 100644
--- a/packages/database/src/accounting-cutover/trial-balance.ts
+++ b/packages/database/src/accounting-cutover/trial-balance.ts
@@ -19,6 +19,7 @@ import {
type OpenItem,
type TrialBalanceLine
} from "../accounting-cutover";
+import { withTransaction } from "../client";
import { configuredDefaultAccount } from "../journal-posting-status";
import { debitSigned, isAccountClass } from "../ledger";
import { round } from "../precision";
@@ -36,8 +37,7 @@ import {
loadCutoverContext,
OPENING_BALANCE_SOURCE,
refuseAfterCutover,
- requireClass,
- withTransaction
+ requireClass
} from "./shared";
const OPENING_TRIAL_BALANCE_DESCRIPTION = "Opening trial balance";
diff --git a/packages/database/src/client.ts b/packages/database/src/client.ts
index b610c26e01..c412be8187 100644
--- a/packages/database/src/client.ts
+++ b/packages/database/src/client.ts
@@ -23,6 +23,19 @@ export type KyselyDbTx = KyselyDatabase | KyselyTx;
export type { ExpressionBuilder, Kysely } from "kysely";
+/**
+ * Runs `fn` in a transaction: the one `db` already is, else a new one. Kysely
+ * refuses `transaction()` on a `Transaction`, so a function that may be handed
+ * either joins through this rather than opening its own.
+ */
+export function withTransaction<T>(
+ db: Kysely<KyselyDatabase>,
+ fn: (trx: Transaction<KyselyDatabase>) => Promise<T>
+): Promise<T> {
+ if (db.isTransaction) return fn(db as Transaction<KyselyDatabase>);
+ return db.transaction().execute(fn);
+}
+
/** NUMERIC. node-postgres hands it over as text by default, so a scale-5 price
* would arrive as a string where the generated types promise a number. */
const NUMERIC_OID = 1700;