Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
Engineering change orders (#1150)
Anshul sharmac1bed1fc52dd
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex b02d729f4d..66123ada61 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -438,3 +438,13 @@ Format: `Context → Problem → Rule → Applies to`**Rule:** When spreading validated/optional data into a supabase-js `.insert(...)`, a NOT-NULL column with a DB default will still fail if the key is present-but-`undefined`. Either (a) supply the value explicitly at the insert site next to the other defaults (`methodType: x.methodType ?? "Pull from Inventory"`), (b) `sanitize(...)` the insert object so undefined keys are dropped (matches the update path), or (c) pass `{ defaultToNull: false }` to `.insert(...)` (sends `Prefer: missing=default`). Prefer (a) for a single column, (b) for consistency with an existing update path. Don't assume the DB `DEFAULT` will apply — it only does for keys entirely absent from the object.**Applies to:** `upsertSalesOrderLine` (`apps/erp/app/modules/sales/sales.service.ts`); any `upsert*` whose insert branch spreads optional/validated fields into a table with NOT-NULL-DEFAULT columns (sales/purchase/quote/invoice line inserts especially, which all carry a NOT NULL `methodType`).++## Twin `ValidatedForm`s at the same JSX slot share one RVF store — controlled-field defaults seed only for whichever branch mounts first++**Context:** The Add Affected Item modal (`AffectedItemForm`) renders `isNewPart ? <ValidatedForm A/> : <ValidatedForm B/>`. Branch A (New Part) has `replenishmentSystem`/`itemTrackingType` Selects with `defaultValues` `"Make"`/`"Inventory"`; branch B (existing item) has an item picker. After switching to New Part the two Selects rendered blank and submit failed with `Invalid enum value … received ''`.++**Problem:** Both branches render a `<ValidatedForm>` (same element type) at the **same JSX position**, so React reconciles them as **one component instance** and just swaps props — no unmount/remount. `@carbon/form`'s RVF store seeds `controlledFields.values` from `defaultValues` **only on first hydration** (`syncFormProps`: `if (!state.isHydrated) { … }`). The instance hydrates on the initial branch (B, `changeType` default `Version`), so when the user switches to A, A's Select defaults are **never** seeded — `useControlledFieldValue` returns the store value (`undefined`) once `isHydrated`, not the `defaultValue`. Uncontrolled fields (`InputControlled`) were unaffected because they write their own value via effect. `defaultValues` object identity was a red herring: `ValidatedForm` already `useDeepEqualsMemo`s it, and `syncFormProps` ignores later `defaultValues` changes post-hydration.++**Rule:** When two `ValidatedForm`s occupy the same conditional slot (`cond ? <VF/> : <VF/>`), give each a distinct, stable `key` (`key="new-part"` / `key="existing-item"`) so switching forces a fresh mount + fresh store that hydrates with the correct branch's `defaultValues`. Consequence: the fresh mount also needs any Select value the branch relies on seeded in its own `defaultValues` (e.g. `changeType: "New Part"`, added to `changeOrderNewPartValidator`) — a value the shared store previously carried over from the user's click is gone after remount. Symptom to watch for: a controlled Select rendering blank / submitting `""` right after a branch switch.++**Applies to:** `apps/erp/app/modules/items/ui/ChangeOrder/AffectedItemForm.tsx`; any conditional twin-`ValidatedForm` pattern; `@carbon/form` controlled fields (`Select`/`Combobox`/anything on `useControlField`) that rely on `defaultValues` seeding.diff --git a/.ai/plans/2026-07-19-change-order-new-part-and-consolidation-test-plan.md b/.ai/plans/2026-07-19-change-order-new-part-and-consolidation-test-plan.mdnew file mode 100644index 0000000000..3349bff63c--- /dev/null+++ b/.ai/plans/2026-07-19-change-order-new-part-and-consolidation-test-plan.md@@ -0,0 +1,191 @@+# Test Plan — Change Orders: Replacement Part, net-new New Part, N→1 consolidation++**Feature:** `.ai/specs/2026-07-19-change-order-new-part-and-consolidation.md`+**Impl plan:** `.ai/plans/2026-07-19-change-order-new-part-and-consolidation.md`+**Branch:** `feat/change-orders-top-to-bottom`+**Type:** manual / e2e verification (basis for a `/test` playbook)++## What changed (under test)++1. The change type formerly called **New Part** is renamed **Replacement Part** (1:1 supersession — new part number that supersedes the affected part).+2. A new **New Part** change type: genuinely net-new part, **no predecessor, no supersession**, minted + released under the CO (Make or Buy).+3. **N→1 consolidation**: introduce a New Part and, on a parent assembly (Version/Revision change), remove the old component lines and add the New Part — a BOM change, not a supersession.+4. The **Add Affected Item** modal now leads with a **change-type Select** that drives the body (existing-part picker vs. create-new-part mini-form).++Taxonomy under test (`changeOrderChangeType`): `Version | Revision | Replacement Part | New Part`.++---++## 0. Environment & setup++**Stack:** local dev running (`crbn up`); ERP at the value of `ERP_URL` in `.env.local` (currently `https://erp.change-orders-top-to-bottom.dev`). Log in via the `DEV_BYPASS_EMAIL` bypass (`[email protected]`). Company: **Carbon Development**.++**DB access (for the verification queries below):**+```bash+DB_URL=$(grep -E "^SUPABASE_DB_URL=" .env.local | cut -d= -f2-)+psql "$DB_URL" -c "<query>"+```++**Migration must be applied** (it is, on this branch's local DB). Confirm:+```sql+SELECT string_agg(enumlabel, ',' ORDER BY enumsortorder)+FROM pg_enum e JOIN pg_type t ON t.oid = e.enumtypid+WHERE t.typname = 'changeOrderChangeType';+-- Expect: Version,Revision,Replacement Part,New Part+```++### Test data to create (once)++| Fixture | How | Purpose |+|---|---|---|+| **ASM-A** — a Make (manufactured) part with a BOM of **3 purchased components** C1, C2, C3 | `/x/part/new` (Make) then add 3 BOM lines on its method | The consolidation target |+| **ASM-B** — a second Make part whose BOM **also uses C1** | `/x/part/new` (Make) + add C1 to its BOM | Proves a "removed" component is untouched elsewhere |+| (optional) an **existing CO** with a pre-migration "New Part" affected item | already-seeded rows, if any (`seed-change-orders.ts`) | Rename regression (§A) |++> If no pre-migration CO exists locally, §A3 is covered by §F (create a Replacement Part CO fresh and confirm it supersedes).++---++## A. Rename / migration regression — "Replacement Part"++| ID | Steps | Expected |+|---|---|---|+| A1 | Query existing affected items | Any row that was `New Part` before the migration now reads `Replacement Part`. `SELECT DISTINCT "changeType" FROM "changeOrderAffectedItem";` → only values from the 4-type set; **no bare `New Part` row that has a `baseMakeMethodId`** (those are replacements). |+| A2 | Enum check (§0) | `Version,Revision,Replacement Part,New Part` |+| A3 | Open any pre-existing CO that had a "New Part" affected item | The affected-item badge shows **Replacement**; the cutover/Part Supersession card is present; releasing it still writes an `itemSupersession` (see F2). |++---++## B. Add Affected Item modal — change-type Select++Open a CO (Draft), click **Add Affected Item**.++| ID | Steps | Expected |+|---|---|---|+| B1 | Observe the modal | First control is a **Change type** Select with options: Version, Revision, Replacement Part, New Part. Default **Version**. |+| B2 | Select Version / Revision / Replacement Part in turn | Body shows the **existing Part or Tool** picker (`<Item>`), not the new-part form. |+| B3 | Select **New Part** | Body swaps to the mini-form: **Part Number** (auto-populated), **Name**, **Type** (Part/Tool), **Replenishment System** (Buy/Make/Buy and Make). The `<Item>` picker is gone. |+| B4 | In New Part mode, switch **Type** Part → Tool | The auto-minted **Part Number** re-mints for the new type (e.g. a tool sequence). |+| B5a | New Part mode, clear Name, submit | Validation error "Name is required"; nothing created. |+| B5b | Existing mode (Version), submit with no item picked | Validation error "Item is required". |++---++## C. New Part — net-new creation & authoring++| ID | Steps | Expected |+|---|---|---|+| C1 | Add affected item → New Part, **Make**, keep auto number, Name "Consolidated Bracket", Add | A new **explorer row** appears reading `NEW → {minted number}`; the app navigates to its detail. |+| C2 | On the New Part detail | Shows **Properties** (attributes) + **Bill of Material** + **Bill of Process** editors (empty), a **Changes** card, and **NO** cutover / Part Supersession card. Badge = **New** (green). |+| C3 | DB: the minted item | `SELECT active, "revisionStatus", "changeOrderId" FROM item WHERE "readableId" = '{number}';` → `active = f`, `revisionStatus = Design`, `changeOrderId` = the CO id. Its make method: `SELECT status, "changeOrderId" FROM "makeMethod" mm JOIN item i ON i.id = mm."itemId" WHERE i."readableId" = '{number}';` → `status = Draft`, `changeOrderId` = the CO. |+| C4 | On the New Part detail, look for the change-type switcher | **Absent** — a New Part cannot be switched to another type. |+| C5 | Add affected item → New Part, open the **Type** select | Only **Part** and **Tool** offered (no Material/Consumable/Service). |+| C6 | Author the New Part's BOM: add 2 components; author a BOP operation | Edits persist (reload the line — they remain); the **Changes** card lists the added materials/operation as additions. |+| C7 | Add a **New Part, Buy** | Detail shows **Properties** + **Supplier Parts** grid; **no** BOM/BOP editor (Buy has no method). |++---++## D. Consolidation (N→1) authoring++Precondition: ASM-A (3 components C1/C2/C3) + a New Part created in C1.++| ID | Steps | Expected |+|---|---|---|+| D1 | In the same CO, Add Affected Item → **Version**, pick **ASM-A** | ASM-A added as a Version affected item; its draft BOM editor shows C1, C2, C3. |+| D2 | On ASM-A's draft BOM, delete C1, C2, C3; **Add material** and open the item picker | The **New Part draft** (inactive) is **selectable** in the picker (it appears because the picker is `includeInactive`). Select it, set quantity 1. |+| D3 | Open ASM-A's **Changes** card | Shows **3 removed** (C1/C2/C3) and **1 added** (the New Part). No "modified". |+| D4 | Open the CO overview **Changes rollup** | Shows both the New Part's own additions (its BOM) and ASM-A's remove/add. |+| D5 | (edge) Try to add ASM-A's own BOM line referencing a Material | Allowed only per the picker's `validItemTypes` (Consumable/Material/Part) — Tools excluded as components, as before. (Regression, not new behavior.) |++---++## E. Release — supersession semantics & ordering++Advance the CO: Draft → Start → Engineering Complete → Implementation, then **Release** (Implementation → Done).++| ID | Steps | Expected |+|---|---|---|+| E1 | Release the CO | CO status = **Done**; no error. |+| E2 | DB: the New Part after release | `active = t`, `changeOrderId` = CO (stamped). **No supersession**: `SELECT count(*) FROM "itemSupersession" WHERE "successorItemId" = '{newPartItemId}';` → **0**. |+| E3 | Open ASM-A's item master (Manufacturing) | Its **active** method now has the new BOM: New Part present, C1/C2/C3 gone. |+| E4 | DB: the removed components are untouched | C1/C2/C3 still `active = t`; **no** `itemSupersession` was written for them by this CO. ASM-B's BOM still references C1. |+| E5 | Regression of the redirect map | Create a job from **ASM-B** (which still uses C1) → its job BOM still pulls **C1** (no redirect to the New Part — the consolidation was local to ASM-A). |+| E6 | Ordering sanity | ASM-A's released method references the New Part as an **active** item (the New Part was revealed active before ASM-A's method flipped — no dangling/inactive component reference). |++---++## F. Replacement Part (renamed) — still supersedes++| ID | Steps | Expected |+|---|---|---|+| F1 | New CO; Add Affected Item → **Replacement Part**, pick an existing manufactured part P | New affected item; badge **Replacement**; detail shows Properties + BOM/BOP editors + **cutover / Part Supersession** card; the minted new item has a new part number derived from P's (e.g. `…0029` → `…0030`). |+| F2 | Author a change, release | DB: an `itemSupersession` **is** written, predecessor = P's item, successor = the new part. `active = t` on the new part. |+| F3 | Badge everywhere (explorer + card) | Reads **Replacement** (orange), distinct from **New** (green). |++---++## G. Negative / guard cases++| ID | Steps | Expected |+|---|---|---|+| G1 | On an existing (Version/Revision/Replacement) affected item, open the change-type switcher | Options are **Version / Revision / Replacement Part** — **New Part is not offered**. (Buy items also hide Version.) |+| G2 | POST a change-type switch to `New Part` directly (e.g. via a crafted request) | Rejected — flash "New Part change type cannot be switched" (route guard + `updateChangeOrderAffectedItemChangeType` guard). |+| G3 | Attempt a New Part with a non Part/Tool type (not possible via UI; test the service guard) | Rejected — "New Part is only supported for Parts and Tools". |+| G4 | Remove a New Part affected item from the CO | Its draft (and the minted item, if the discard path deletes it) is discarded; the explorer row disappears; no orphaned active item. |++---++## H. Regression — existing CO behaviors preserved++| ID | Steps | Expected |+|---|---|---|+| H1 | Add a **Version** affected item, author a BOM change, release | New Active method version on the same item, prior Active → Archived; **no** new item, **no** supersession. |+| H2 | Add a **Revision** affected item, release | New revision item revealed active; **oldRev→newRev** `itemSupersession` written; cutover card was present. |+| H3 | Badges | Version = `Version N`; Revision = **New Revision**. |+| H4 | Add a **Buy** item as **Version** | Coerced to **Revision** on add (Buy has no BoM/BoP). |+| H5 | (prior work) Open an item that's a Revision/New Part draft under an open CO on its item master | Its CO-owned draft BOM/BOP renders and is editable, in sync with the CO. |+| H6 | (prior work) Parts table | Surfaces the **active** revision, not an inactive CO draft revision. |++---++## I. Data-integrity queries (reference)++```sql+-- Affected items of a CO with their change types + draft refs+SELECT "changeType", "itemId", "newItemId", "baseMakeMethodId", "draftMakeMethodId"+FROM "changeOrderAffectedItem" WHERE "changeOrderId" = '<coId>';++-- Supersession written by a release+SELECT "itemId" AS predecessor, "successorItemId" AS successor, "supersessionMode"+FROM "itemSupersession" WHERE "companyId" = '<companyId>' ORDER BY "createdAt" DESC LIMIT 10;++-- New Part must have NONE of the above as successor:+SELECT count(*) FROM "itemSupersession" WHERE "successorItemId" = '<newPartItemId>'; -- expect 0++-- A CO-owned draft method is cleared at release (idempotency marker)+SELECT id, status, "changeOrderId" FROM "makeMethod" WHERE "changeOrderId" = '<coId>'; -- empty after release+```++---++## J. Automated coverage (already green — re-run before merge)++```bash+pnpm --filter erp exec vitest run app/modules/items/items.service.test.ts # 15 tests, incl. N→1 consolidation diff+pnpm exec turbo run typecheck --filter=erp # scoped typecheck+pnpm exec turbo run typecheck --filter=@carbon/database # seed+```++---++## Pass criteria++- All of A–H pass in the browser + the DB checks match.+- No supersession is ever written for a **New Part** (E2, I).+- Removed consolidation components are untouched globally (E4, E5).+- Existing "New Part" COs behave exactly as before under the **Replacement Part** label (A3, F2).+- Automated coverage (J) is green.++## Known risk to watch (from the impl checkpoint)++- **New Part draft visibility in the assembly BOM picker (D2):** the minted inactive part must be present in the client `useItems` store for the `includeInactive` picker to show it. If it doesn't appear immediately after minting, reload the CO page (store re-sync) and retry; if it still doesn't appear, that's a real bug (store not carrying the just-minted inactive item) — capture it.diff --git a/.ai/plans/2026-07-19-change-orders-remaining-work.md b/.ai/plans/2026-07-19-change-orders-remaining-work.mdnew file mode 100644index 0000000000..84e262d183--- /dev/null+++ b/.ai/plans/2026-07-19-change-orders-remaining-work.md@@ -0,0 +1,72 @@+# Change Orders (ECO) — Remaining Work++**Status:** The change-orders feature shipped on `feat/change-orders-top-to-bottom`.+The current, accurate design is the source of truth in+`apps/erp/app/modules/items/AGENTS.md` → "Change Orders (sub-area)". This plan+captures ONLY the work still open after that; it deliberately does not+re-describe shipped behavior.++This consolidates six earlier change-order plans (v1 top-to-bottom, v2+reuse-method-tables, conflict-resolver, supplier-parts + changes-rollup,+new-part + consolidation, and its test plan). The superseded/shipped design docs+were removed after their still-open items were folded in below.++## Do NOT resurrect (dead approaches, intentionally removed)++Designed in earlier plans and deliberately dropped — don't rebuild them:++- Staged mirror tables (`changeOrderStaged*`) — replaced by a real CO-owned+ Draft `makeMethod` (`makeMethod.changeOrderId`).+- The 2-way merge / conflict resolver at release (`ChangeOrderConflictResolver`,+ `getChangeOrderReleaseDiff`, `reconcileDraftWithLive`, `applyTheirs`,+ `buildReleaseConflictEntries`) — release is a plain review-then-confirm dialog+ now; releasing a Version just appends a new Active version.+- The one-open-CO-per-part guard — same-part parallel COs are allowed+ (`findOtherOpenChangeOrdersForItem` is advisory only).+- `getChangeOrderImpact` PO-lines table — replaced by the where-used+ `ImpactPanel`.+- `mintPlaceholderPart` exists but is unwired; `plmReleaseControl` /+ `item.releaseStatus` enforcement was not adopted.++## Open / deferred work++### 1. Tool affected items + Tool attribute editing under a CO+The service layer accepts Tools, but there is no UI path to add a **Tool** as an+affected item, and embedded attribute editing (`PartProperties` `embedded`+variant) is wired for **Parts only**. Add the Tool add-path and a+`ToolProperties`-embedded editor so a Tool Revision / Replacement Part / New Part+can edit attributes on the CO line.+_Sources: AGENTS.md "Deferred (not yet built)"; v2 plan Task 11 (`PartProperties`+deferral, now Parts-only); new-part plan Task 5 ("Tool attribute editing remains+a follow-up")._++### 2. "Used in N other assemblies" indicator on removed diff lines+On the Changes diff, a removed BOM component line should show a where-used count+("used in N other assemblies") so the author sees the blast radius inline. Needs+a loader decision — a per-removed-component `getPartUsedIn` is a heavier query,+hence deferred. Where-used is currently only reachable via each part's detail+page and the CO `ImpactPanel`.+_Source: new-part plan Task 7 step 2 (marked `[~]`/PENDING)._++### 3. (Backlog) NCR-style templated / gating action tasks+V1 ships only freeform, non-gating `changeOrderActionTask`. The+templated/gating action-task machinery (the Q7 fast-follow) was explicitly+deferred and never built.+_Source: v2 plan out-of-scope ("NCR-style action templates (Q7 fast-follow, not+this version)")._++## Verification++End-to-end browser verification of the shipped feature is not yet recorded as+run. The full manual/e2e matrix is the verification gate:+`.ai/plans/2026-07-19-change-order-new-part-and-consolidation-test-plan.md`+(sections A–J: rename regression, net-new New Part, N→1 consolidation, release+supersession semantics, guard/negative cases, regression matrix). A cached+playbook also exists at+`.ai/playbooks/change-order-new-part-consolidation.md`.++**Known risk to watch (D2):** a minted inactive New Part must be present in the+client `useItems` store for the `includeInactive` assembly-BOM picker to show it.+If it doesn't appear immediately after minting, reload the CO page (store+re-sync) and retry; if it still doesn't appear, that's a real bug (store not+carrying the just-minted inactive item) — capture it.diff --git a/.ai/playbooks/change-order-new-part-consolidation.md b/.ai/playbooks/change-order-new-part-consolidation.mdnew file mode 100644index 0000000000..5cabf05b68--- /dev/null+++ b/.ai/playbooks/change-order-new-part-consolidation.md@@ -0,0 +1,74 @@+# Change Order — New Part / Replacement Part / Consolidation++Last tested: 2026-07-19+Routes: /x/change-order/new · /x/items/change-order/{coId}/details++## Prerequisites+- A Draft change order (create via `/x/change-order/new` — fill Name, Save).+- For consolidation: an active Make part with an **Active** (non-CO-owned) make method+ and ≥2 BOM components. (M000000001 works locally; parts with only Draft/CO-owned+ methods can't be added as **Version** — the draft-create needs an Active method.)++## Steps++### 1. Create the CO+Navigate `/x/change-order/new` → fill the first textbox (Name) → `requestSubmit` the+form (button "Save"). Redirects to `/x/items/change-order/{coId}/details`.++### 2. Add a net-new New Part (§C)+- Click **Add Affected Item** (explorer bottom button).+- Modal: first control is a **Change type** Select (Version / Revision / Replacement+ Part / New Part). Selecting **New Part** swaps the body to a mini-form: Part Number,+ Name, Type (Part/Tool), Replenishment System.+- **KNOWN BUG:** the Part Number does NOT auto-populate — type one manually+ (e.g. `PBRKT001`). Fill Name; open the Type combobox → pick Part; open Replenishment+ combobox → pick Make.+- `requestSubmit` the modal form (button "Add"). Navigates to the new affected item.+- Verify detail: badge **NEW**; Properties + Bill of Material + Bill of Process (empty);+ **NO** cutover/Part Supersession card.++### 3. Add an assembly as Version (§D)+- Add Affected Item → keep **Version** → open the item picker (2nd combobox) → pick a+ Make part with an Active method. `requestSubmit` "Add".+- Open the assembly's affected-item detail → **Add Item** (BOM) → the item picker+ (`includeInactive`) lists the inactive New Part draft too (it may be past the+ dropdown's first virtualized page — filter/scroll to it).++### 4. Release (§E)+- Advance the CO: click **Advance to Start** → **Advance to Engineering Complete** →+ **Advance to Implementation** → **Release**.+- (Browser refs drift on the release dialog; a reliable fallback is to POST the status+ route directly — see Selector Notes.)++## Selector Notes+- **Submit** Carbon forms with `requestSubmit(button)`, never a click.+- The Add-item modal has **two** ValidatedForms (existing-item vs new-part) toggled by+ the change-type Select; `requestSubmit` the form of the mode you're in.+- **Reliable release** (bypasses the drifty dialog): POST the status route with `id`,+ `fromStatus`, `status`:+ ```js+ fetch(`/x/items/change-order/${coId}/status`, {method:'POST',+ body:(()=>{const f=new FormData();f.append('id',coId);f.append('fromStatus','Implementation');f.append('status','Done');return f})(), redirect:'manual'})+ ```+ (302/opaqueredirect = applied; a 422 means a missing field — `id` is required.)+- **Reliable add** (bypasses the picker): POST `/x/items/change-order/${coId}/affected`+ with `changeOrderId`, `itemId`, `changeType` (existing) or `changeType=New Part` ++ `readableId,name,itemType,replenishmentSystem` (net-new).++## DB verification (the real proof)+```sql+-- Net-new New Part after release: active, and ZERO supersession as successor+SELECT active FROM item WHERE "readableId"='PBRKT001'; -- t+SELECT count(*) FROM "itemSupersession" s JOIN item i ON i.id=s."successorItemId"+ WHERE i."readableId"='PBRKT001'; -- 0+-- Minted New Part is inactive + CO-owned Draft method before release+SELECT active,"revisionStatus","changeOrderId" FROM item WHERE "readableId"='PBRKT001';+```++## Common Failures+- **Version add "silently fails"** — usually the picked part has no **Active** make+ method (only Draft / CO-owned drafts). `createChangeOrderDraftMethod` Version branch+ needs an Active method to version; otherwise it rolls the affected item back.+- **Part Number empty** in the New Part mini-form — `useNextItemId` isn't auto-minting+ in this modal (bug); type a number manually.+- Release dialog confirm button hard to hit via agent-browser — use the direct POST.diff --git a/.ai/research/2026-07-19-co-part-consolidation.md b/.ai/research/2026-07-19-co-part-consolidation.mdnew file mode 100644index 0000000000..35bdfffe42--- /dev/null+++ b/.ai/research/2026-07-19-co-part-consolidation.md@@ -0,0 +1,525 @@+# ECO Modeling in PLM/ERP: Change Types, New Parts, BOM Consolidation & Supersession++Research date: 2026-07-19+Purpose: ground a Carbon change-order (ECO) spec — specifically (a) renaming the+1:1-supersession change type from **"New Part"** to **"Replacement Part"**,+(b) adding a net-new **"New Part"** with no predecessor, and (c) modeling an+N→1 consolidation as a **parent-assembly BOM change** rather than a supersession.++Systems surveyed: Arena PLM, PTC Windchill, Siemens Teamcenter, Oracle Agile PLM,+Oracle Fusion Cloud PLM, SAP Engineering Change Management (LO-ECH), NetSuite,+Odoo PLM, Fishbowl, Duro, OpenBOM.++Carbon-today baseline (from `apps/erp/app/modules/items/items.models.ts`+`changeOrderChangeTypes`): the per-affected-item change type is+`Version | Revision | New Part`, where **"New Part"** today already means a **new+P/N derived from + auto-superseding the affected part** (a 1:1 supersession), and+there is currently **no** net-new-with-no-predecessor path. That is the naming+collision this research is meant to resolve.++---++## Q1. Change scope / disposition types — how systems categorize what an ECO does to an item++**The dominant industry pattern is a "before → after" split on the change object,+plus a distinction between "revise in place" (same number, new rev) and "replace+with a different number."**++- **PTC Windchill** — separate **Affected Objects** (the existing "before" items)+ and **Resulting Objects** (the "changed or new objects to be released") tables on+ the Change Task. Revise-in-place vs replace is an *action* on the affected object:+ **Revise** (same part, new revision) vs **Supersede** / **Save As** / **New** (a+ different part number). Inventory **Disposition** (On Order / WIP / Finished) is a+ separate axis about existing stock, not part identity.+ [Affected/Resulting Objects](https://support.ptc.com/help/windchill/r13.1.2.0/en/Windchill_Help_Center/changemanagement/ChgMgmtAffectedAffectedObjResulting.html),+ [Superseding Parts](https://support.ptc.com/help/windchill/r12.1.2.0/en/Windchill_Help_Center/parts/PMPartSupersedeOview.html)+- **Siemens Teamcenter** — relation folders **Impacted Items** (before) →+ **Solution Items** (after), plus **Problem/Reference Items**; a **Change lineage**+ relation ties impacted→solution. Revise = new Item Revision under the **same Item+ ID**; a new **Item ID** is created only when the part number changes.+ Teamcenter explicitly notes supersedure "**cannot track a pure revision change**"+ — that is the dividing line between a revise and a replacement.+ [Change relation folders](https://www.linkedin.com/pulse/what-change-manager-teamcenter-active-workspace-anant-bramhankar-im4ff),+ [Supersedure](https://tcplmbasics.com/2018/06/07/supersedure-in-teamcenter/)+- **Oracle Agile PLM** — change *classes* carry the semantics: **ECR** (request),+ **ECO** (creates a new revision — same item number), **MCO** (mfg data change, no+ rev bump), **SCO** (site-only), **Deviation**, **Stop Ship**. **Affected Items**+ rows carry Old Rev → New Rev. A different part number = a new item redlined into+ consuming BOMs (no built-in supersede-by-renumber operation).+ [PC User Guide Ch.7 Changes](https://docs.oracle.com/cd/E50306_29/otn/pdf/user/html_agaad/output/chapter_7.htm),+ [Ch.8 Affected Items](https://docs.oracle.com/cd/E50306_29/otn/pdf/user/html_agaad/output/chapter_8.htm)+- **Oracle Fusion Cloud PLM** — predefined change types (**Engineering Change+ Order**, **Change Order without revision control**, **Change Request**,+ **Deviation**, **Commercialization Change Order**, plus Problem Report / Corrective+ Action). Objects changed = **affected objects**; markup = **redlines** with record+ types **ADD / DELETE / CHANGE**. Revise-in-place is primary; new-part replacement+ is a separate **Replace** action + **Obsolete** lifecycle phase.+ [Understand Change Types](https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/26a/faipr/understand-change-types.html)+- **SAP ECM (LO-ECH)** — a **Change Master + Change Number** (CC01) time-slices an+ object's state via **valid-from date**; **ECR vs ECO** is a status-managed change+ master (CC31/CC32) that **must be approved and converted ECR→ECO** before any+ object can change. SAP does **not** model revise-vs-new as distinct disposition+ types — both just reference the same change number (changed state vs created state).+ [LO-ECH overview](https://help.sap.com/doc/saphelp_me151/15.1.3VERSIONFORSAPME/en-US/da/6cb953495bb44ce10000000a174cb4/content.htm?no_cache=true),+ [ECR/ECO](https://help.sap.com/doc/saphelp_me151/15.1.3VERSIONFORSAPME/en-US/75/25bd534f22b44ce10000000a174cb4/content.htm?no_cache=true)+- **Arena PLM** — **revision-centric, not renumber-centric**: the Change Affected+ Item object has `newRevisionNumber` / `newLifecyclePhase` but **no "new part+ number" field**. "SUPERSEDED" is a *revision status*, not a part-to-part link.+ Categories: ECR → ECO → ECN, plus **Deviation** (temporary effectivity).+ [create change](https://raw.githubusercontent.com/ptc-arena/arena-restapi-doc/main/Arena%20REST%20API/Endpoints/Change/endpoint_create_change.md),+ [modified item object](https://raw.githubusercontent.com/ptc-arena/arena-restapi-doc/main/Arena%20REST%20API/Objects/object_change_modified_item.md)+- **Duro** — supersession expressed via **Effectivity**: "the old is superseded by+ either a new **CPN** or a new **revision** of an existing CPN" — so a *replacement*+ (new CPN) and a *revision* (same CPN) are explicitly the two supersession flavors.+ [Effectivity](https://duro.zendesk.com/hc/en-us/articles/10159748251924-Effectivity)+- **OpenBOM** — **CR → CO → Revision** (a Revision = immutable copy, same part+ number). **No supersession/replacement disposition** in the change model;+ interchangeability handled separately via Alternates/Substitutes.+ [Change management](https://www.openbom.com/blog/change-management-in-openbom-revision-change-request-and-change-orders)+- **NetSuite / Odoo / Fishbowl (mid-market)** — NetSuite's native ECO acts on+ assembly items + BOM revisions via **Add / Remove / Replace** actions; no+ item-revision disposition type. Odoo ECOs version a **BoM** (V2, V3…) with a+ color-coded diff; it never "creates a new product" from a BoM change. Fishbowl has+ **no ECO/change-control object at all** (just a free-text Revision label).+ [NetSuite ECO](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/chapter_1531288763.html),+ [Odoo ECO](https://www.odoo.com/documentation/19.0/applications/inventory_and_mrp/plm/manage_changes/engineering_change_orders.html)++**Consensus:** "revise in place" = **same part/item number, new revision**;+"replace" = **a different part number** — this line is universal, and Teamcenter+even codifies it ("supersedure cannot track a pure revision change"). The+before/after split (Affected→Resulting, Impacted→Solution, Old Rev→New Rev) is the+near-universal representation.++**Divergence:** terminology for "replace with a new number" varies widely —+**Supersede** (Windchill, Teamcenter, Duro), **Replace a Component** (Fusion,+NetSuite), redline-in-a-new-item (Agile). Arena and OpenBOM have **no first-class+renumber/supersede disposition** at all (pure revision models). "Disposition" is+overloaded: in Windchill/Agile/Arena it means **existing-inventory handling** (On+Order / WIP / Stock / Field), *not* part identity.++---++## Q2. Introducing a brand-new part under an ECO (no predecessor)++**The enterprise PLM/PLM-grade systems all let a genuinely new part be created and+released *by* the change; the mid-market ERPs generally do not.**++- **Windchill** — a **New** object (no predecessor) is added to the **Resulting+ Objects** table; the Change Notice workflow "sets all Resulting Objects to+ **Released**," promoting the new **In Work** part.+ [Adding objects to Change Task](https://support.ptc.com/help/windchill/plus/r12.0.2.0/en/Windchill_Help_Center/CADxFileMenuAddToChangeTask.html)+- **Teamcenter** — a new Item (no predecessor) is attached as a **Solution Item**;+ new revisions are "working" (no Release Status) until a workflow action handler+ applies release status.+ [What's new 2312](https://blogs.sw.siemens.com/teamcenter/whats-new-in-teamcenter-2312/)+- **Agile PLM** — "Items are not released to production directly. Rather, a change+ (an ECO) is created against the item, and that change is released." A new item+ starts at the **Introductory** rev / **Preliminary** phase; releasing the ECO+ assigns rev **A**.+ [PC User Guide 9.3.4 Ch.2 Items](https://docs.oracle.com/cd/E60149_28/otn/pdf/user/html_agaad/output/chapter_2.htm)+- **Oracle Fusion** — a new item is **added as an affected object** and released+ through the change; lifecycle phases Design → Preproduction → Production → Obsolete.+ A separate **New Item Request (NIR)** workflow also exists.+ [Create a Change Order](https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/26b/faupd/create-a-change-order-and-submit-it-for-approval.html)+- **SAP** — a genuinely new material (no predecessor) can be created under a change+ number by entering it on **MM01**; the initial state is stamped with the change+ master's valid-from (future-dating allowed for series start).+ [MM01 change number](https://community.sap.com/t5/enterprise-resource-planning-q-a/mm01-change-number/qaq-p/7815278)+- **Arena** — **yes**: add the new item's working revision to the change and set+ `newLifecyclePhase`; on approval it transitions PRELIMINARY → DESIGN → PRODUCTION.+ [release item revision](https://raw.githubusercontent.com/ptc-arena/arena-restapi-doc/main/Arena%20REST%20API/Endpoints/Item%20Lifecycle%20Phase%20Change/endpoint_release_item_revision.md)+- **Duro** — new components start in **Design** (edits don't need a CO); promotion+ to Prototype/Production "**creates a change order and attaches all components**…+ must be approved before the part is released." So new parts are *born* outside+ change control but *released* through it.+ [Lifecycle Status](https://duro.zendesk.com/hc/en-us/articles/360029931491-Lifecycle-Status)+- **NetSuite / Odoo / Fishbowl** — **NO.** NetSuite ECO Add/Replace requires an+ *existing* item (create in item master first). Odoo: "A Product must be selected+ before Bill of Materials options is available" — the new part is created as a+ normal product record *outside* the ECO, then referenced. Fishbowl has no ECO.+ [NetSuite creating ECOs](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/bridgehead_1531291168.html),+ [Odoo forum (Ray Carnes)](https://www.odoo.com/forum/help-1/using-engineering-change-orders-when-does-odoo-rev-the-version-of-a-product-and-when-does-it-rev-the-version-of-a-bill-of-materials-253157)++**Consensus:** All the *PLM-grade* systems (Windchill, Teamcenter, Agile, Fusion,+Arena, Duro, and SAP via a change number) support a **brand-new part reviewed and+released as part of the change** — typically the new part is added to the "resulting/+solution/affected" set, starts in an unreleased lifecycle state (In Work / Working /+Preliminary / Introductory / Design), and the change's completion promotes it to+Released/Production. This validates adding a net-new "New Part" disposition in Carbon.++**Divergence:** The mid-market ERPs (NetSuite, Odoo, Fishbowl) **cannot mint a new+part inside the ECO** — the part must pre-exist and is merely referenced. So a+new-part-that-a-parent-consumes is inherently a two-step, ordering-dependent flow+there. Carbon's ability to mint a placeholder/new item *inside* the CO puts it in+the PLM-grade camp, not the mid-market camp.++---++## Q3. BOM redlines / restructuring — add/remove/replace lines, and the N→1 consolidation++**Unanimous: a consolidation ("3 parts become 1") is modeled as a change to the+PARENT assembly's BOM (remove 3 child lines, add 1 child line), NOT as part-level+supersessions.** Every system with a BOM diff renders it as line-level add/remove/+change on the parent.++- **Windchill** — explicit **BOM Redline** (Structure Redlining): a redline+ structure browser with a **Change Indicator** column; add / remove / **Replace** /+ quantity-change of part-usage links, with **Revert**. Merges into the parent's next+ revision on completion. 3→1 = redline the **parent** (remove 3 usages, add 1).+ [Redline Process](https://support.ptc.com/help/windchill/plus/r12.0.2.0/en/Windchill_Help_Center/ChgMgmtRedlineProcess.html)+- **Teamcenter** — **BOM markup/redlining** (old rev red strikeout, new rev green);+ restructure via the **Supersedure** environment's **Adds folder** / **Cancels+ folder** on the parent. 3→1 = cancel three child occurrences + add one, on the+ parent — multiple Solution Items against the single Impacted (parent) Item.+ [Design BOM tracking](https://blogs.sw.siemens.com/teamcenter/design-bom-tracking-use-active-change/)+- **Agile PLM** — **Redline BOM** on the ECO's affected item: **Add / Remove / Undo+ Redlines** (no single-row Replace — a swap is remove-old + add-new). 3→1 = on the+ **parent's** Redline BOM, remove 3 rows and add 1. (All redlines render red in+ 9.3.x — no green-for-add.)+ [Ch.5 Bills of Material](https://docs.oracle.com/cd/E50306_29/otn/pdf/user/html_agaad/output/chapter_5.htm)+- **Oracle Fusion** — structure redlines on the parent's Structure tab: **ADD**+ (green), **DELETE** (red), **CHANGE/qty** (yellow); plus a first-class **Replace a+ Component** action (original shown in a **Replaces** column). 3→1 = one redline set+ on the parent (3 DELETE + 1 ADD).+ [24D What's New](https://docs.oracle.com/en/cloud/saas/readiness/scm/24d/plm24d/24D-plm-wn-f34326.htm),+ [Replace a Component](https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/25d/faupd/replace-a-component.html)+- **SAP** — BOM change under a change number (CS02): removing a component sets an+ **item deletion indicator** at the valid-from (row persists in STPO for history);+ add the new component with the same valid-from. 3→1 = **one change header on the+ parent material's BOM** (3 deletions + 1 addition, same valid-from).+ [BOM item deletion indicator](https://community.sap.com/t5/enterprise-resource-planning-q-a/how-to-use-deletion-indicator-of-bom-item/qaq-p/8642915)+- **Arena** — line-level Create / Update / Delete BOM Line on the parent's working+ rev; on approval "its release automatically incorporates all BOM redlines." 3→1 =+ parent BOM change (delete 3, add 1) + add the new part as its own affected item.+ [Manufacturing ECO guide](https://www.arenasolutions.com/resources/articles/guide-manufacturing-engineering-change-orders/)+- **Duro** — **Compare Revisions** (green = new, red = old): "components added to+ production, components removed from production, alterations to the BOM assembly."+ 3→1 = edit the **parent's Assembly** tab (add new child / remove old).+ [Compare Revisions](https://duro.zendesk.com/hc/en-us/articles/360050079871-Compare-Revisions)+- **OpenBOM** — **BOM Compare** (added / removed components, qty/property diffs).+ 3→1 = edit the **parent** in Latest State (remove 3, add 1).+ [BOM Compare](https://help.openbom.com/my-openbom/bom-compare/)+- **NetSuite** — ECO change lines on the **Product Changes** subtab, each an+ **Action = Add / Remove / Replace** against a named Assembly Item + BOM + Revision.+ [NetSuite creating ECOs](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/bridgehead_1531291168.html)+- **Odoo** — **BoM Changes** tab is a color-coded diff: **blue = added, black =+ shared/updated, red = removed** components. 3→1 = three red lines + one blue line+ on the **parent BoM**, in one ECO. Not part-level supersession.+ [Odoo ECO](https://www.odoo.com/documentation/19.0/applications/inventory_and_mrp/plm/manage_changes/engineering_change_orders.html)+- **Fishbowl** — direct BOM edit, no diff/redline. Add/remove lines and save.+ [Fishbowl BOM](https://www.fishbowlinventory.com/manufacturing/bill-of-materials)++**Consensus:** N→1 consolidation is **always a parent-BOM restructure** (add/remove+component lines on the parent), never modeled as N part-level supersessions. Diff+UIs are near-universal (green/red add/remove) and are the natural place to surface+it. Windchill / Fusion / SAP / NetSuite additionally offer a **single-line Replace**+primitive; Agile / Arena / Odoo / Duro / OpenBOM express a swap as remove-old ++add-new (no dedicated Replace primitive).++**Divergence:** only whether "Replace one component" is a first-class BOM operation+(Windchill/Fusion/SAP/NetSuite) or expressed as delete+add (the rest). Either way,+consolidation lives on the parent's BOM, not on a part-to-part relationship.++---++## Q4. Replace vs. supersession — GLOBAL (everywhere) vs LOCAL (one BOM)++**Two distinct scopes exist and are named differently. The clean split: a+LOCAL swap changes one parent's component reference; a GLOBAL supersession/where-used+replace changes the successor everywhere the predecessor is used.**++- **Windchill** —+ - LOCAL: **Replace** action swaps a single part usage in one structure; **Substitutes**+ are also local ("a substitute can replace the part only in a specific part structure").+ - GLOBAL: **Mass Change Operations** under a Change Notice — **Replace Existing Part**+ replaces a part across all where-used BOMs matching the **Current Part Number**+ ("10's, 100's, or even 1000's of BOMs").+ - Interchangeability: **Alternates** = global ("applies globally, to all assemblies+ that use the part"); **Substitutes** = local. **Supersede / Superseded By** = a+ global successor/obsolescence link (1:1, 1:many, many:1), typically driving the old+ part to **Obsolete**.+ [Mass Change Replace](https://support.ptc.com/help/windchill/r12.1.2.0/en//Windchill_Help_Center/changemanagement/ChgMgmtMassChangeReplace.html),+ [Superseding Parts](https://support.ptc.com/help/windchill/r12.1.2.0/en/Windchill_Help_Center/parts/PMPartSupersedeOview.html)+- **Teamcenter** —+ - LOCAL: **Replace** one occurrence in one assembly (absolute-occurrence edit).+ - GLOBAL: **mass update / mass-replace** "across multiple impacted assemblies at once,"+ driven off where-used (2312 adds single-action mass-replace across all impacted BOMs).+ - Interchangeability: occurrence-level **Substitutes** (local) vs item-level **Global+ Alternates** (interchangeable "regardless of where used"). **Supersedure** (Adds/Cancels+ relation) documents part-number/qty changes; **Transfer Supersedure** for a component+ moving between assemblies.+ [What's new 2312](https://blogs.sw.siemens.com/teamcenter/whats-new-in-teamcenter-2312/),+ [Alternates vs substitutes](https://teamcenter-open-gate.blogspot.com/2016/11/teamcenter-unified-architecture-manage.html)+- **Agile PLM** — default is **per-parent, local** redlines. The closest to global is+ the **BOM Bulk Change wizard** (ECO-only): "Add an item to multiple assemblies,"+ "Replace an item in **all/some assemblies** that use the item, and automatically+ redline the BOM." But there is **no global successor object** — the wizard fans out+ a per-parent redline (each parent gets its own new rev). Candidates come from **Where+ Used**.+ [Ch.8 Affected Items](https://docs.oracle.com/cd/E50306_29/otn/pdf/user/html_agaad/output/chapter_8.htm)+- **Oracle Fusion** — **Replace a Component** is deliberately **single-structure**+ ("a single component replacement action, not a global mass-change"). There is **no+ native cross-BOM where-used replace** ECO primitive (Cloud Customer Connect threads+ confirm the gap); item-level **Mass Changes** are attribute-only.+ [Replace a Component](https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/25d/faupd/replace-a-component.html),+ [community: mass replace gap](https://community.oracle.com/customerconnect/discussion/565406/mass-update-or-replacement-of-component-on-bill-of-material)+- **SAP** —+ - LOCAL: delete/expire old + add new in CS02 under a change number (one BOM).+ - GLOBAL: **CS20 "Mass Change: BOMs"** replaces a component across all where-used+ BOMs in one run (also CEWB / Fiori "Replace material"). Driven off where-used (CS15).+ SAP has **no formal "supersession" object** for BOM structure — the native concept+ is CS20 mass change + where-used.+ [CS20 mass change](https://community.sap.com/t5/enterprise-resource-planning-q-a/how-to-change-bom-components-in-mass/qaq-p/10006909)+- **Arena** — **no global supersede relationship**; replacement is a **local per-BOM+ edit** (delete A, add B on each parent). Where-Used scoping *notifies* you of other+ assemblies and offers to pull them onto the ECO, but each is still a local edit.+ [Where used in BOMs](https://www.arenasolutions.com/blog/where-used-in-boms-arena-excel/)+- **Duro** — supersession = **Effectivity** date ranges (old CPN+rev → new CPN/rev).+ Physical BOM changes are **local** per-assembly edits; **no one-click replace-in-all-+ where-used**.+ [Effectivity](https://duro.zendesk.com/hc/en-us/articles/10159748251924-Effectivity)+- **OpenBOM** — **Alternates** (item-level = "replacement in all situations" → global+ data) vs **Substitutes** (BOM-line level = "for a specific bill of material" → local+ data). These are *acceptable-replacement definitions*, **not** automated supersession.+ [Alternates & substitutes](https://www.openbom.com/blog/how-to-model-alternate-and-substitute-bom-components-in-openbom)+- **NetSuite / Odoo / Fishbowl** — **LOCAL only.** NetSuite Replace is per-assembly/+ per-BOM/per-revision (no global switch, no where-used mass-replace). Odoo scopes each+ ECO to one BoM. Fishbowl has neither.+ [NetSuite Component Where Used](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_1511882961.html)++**Consensus on terminology:** the LOCAL scope is called **"Replace (component)"** or+a **Substitute**; the GLOBAL scope is a **where-used / mass replace** and/or a+**Supersede / Supersedure** relationship (and **Alternates** for global+interchangeability). The two are genuinely distinct concepts everywhere.++**Divergence:** only the *high-end* PLM/ERPs (Windchill, Teamcenter, SAP) ship a true+**global where-used mass replace**. Agile fakes it with a wizard that fans out+per-parent redlines. **Fusion, Arena, Duro, OpenBOM, NetSuite, Odoo, Fishbowl have no+one-click global replace** — replacement is per-BOM. Where a global part-to-part+successor relationship exists, it's called **Supersede/Supersedure** (Windchill,+Teamcenter) or **Effectivity** (Duro); SAP has no supersession object, only mass+change; OpenBOM's "Alternates" is interchangeability data, not a supersession event.++---++## Q5. Effectivity & where-used impact++**Where-used is the universal impact tool; effectivity (usually date-based) sequences+when a change takes effect. "Obsolete only if now unused" is nowhere automatic — it's+a manual, where-used-guided decision.**++- **Windchill** — impact via **Affected End Items** + where-used/Mass Change+ enumeration. Effectivity types **Date / Lot / Block / Unit(Serial)**, set as+ *pending* effectivities on the Change Notice and copied to *actual* on approval.+ [About Effectivity](https://support.ptc.com/help/windchill/plus/r12.0.2.0/en/Windchill_Help_Center/ChgMgmtEffectivityAbout.html)+- **Teamcenter** — **Where Used** report (vs Where Referenced for datasets); change+ impact analysis viewable per problem item. Effectivity object supports **Date** and+ **Unit-number (serial/lot)** cut-in/cut-out; **Incremental Change (IC)** collects+ add/cancel structure changes. States **Obsolete** / **Released_Superseded**.+ [Occurrence effectivity](https://tcplmbasics.com/2018/03/14/teamcenter-occurrence-effectivity/)+- **Agile PLM** — **Where Used** tab auto-lists all consuming assemblies. Effectivity+ is **date-based only** (Effective Date / Obsolete Date, site-specific); serial/unit+ effectivity lives in the separate EBS product. Obsolescence via **Inactive** /+ **Obsolete** phases.+ [Ch.2 Items](https://docs.oracle.com/cd/E60149_28/otn/pdf/user/html_agaad/output/chapter_2.htm)+- **Oracle Fusion** — **Where-used** is first-class (uses a reference date; excludes+ future-effective parents; can view obsoleted components); related **Impact Analysis**+ checks on-hand/POs/work orders. Date effectivity with **Start/End Date**; on Replace,+ the original's end date becomes the replacement's start date; **Use-Up Date** from+ Supply Planning. **Obsolete** is a manual lifecycle transition — **no auto+ obsolete-if-unused**.+ [Effective Date and Revision](https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/26a/faupd/effective-date-and-revision-for-affected-objects.html)+- **SAP** — where-used via **CS15** (single/multi-level) / **CS15M** (many materials).+ Effectivity by change-number **valid-from date**, or **parameter effectivity**+ (DATE / SERNR serial / MATNR). Obsolescence = **deletion indicator**; physical+ removal only via archiving (SARA / PP_BOM).+ [parameter effectivity](https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-members/engineering-change-management-parameter-effectivity/ba-p/13419368)+- **Arena** — **Where Used** lists all assemblies including the part. Three change+ effectivity types (on-approval / on-date / temporary) + per-item material effectivity+ datetime. **No auto obsolete-if-unused** — Where-Used is the manual guard.+ [Where used in BOMs](https://www.arenasolutions.com/blog/where-used-in-boms-arena-excel/)+- **Duro** — dedicated **Where Used Tool / Table** (every occurrence + direct parent,+ rolled-up qty). **Has Effectivity** (start/end dates on the CO). A single Obsolete+ child **invalidates** the whole assembly (surfaces a validation error up the tree) —+ flags, doesn't auto-clean.+ [Where Used Tool](https://duro.zendesk.com/hc/en-us/articles/10034398880276-Where-Used-Tool)+- **OpenBOM** — **Where Used** (graph nav) "shows every BOM affected when a part needs+ to be replaced." Effectivity via user-defined properties/configurations (not enforced+ date-effective lines). No auto obsolete-if-unused.+ [Where Used graph](https://help.openbom.com/get-started/where-used-graph-navigation/)+- **NetSuite** — **Component Where Used Inquiry** (multi-level, qty per assembly,+ effective/obsolete dates). Two effectivity models: **Revision Control BOM** (rev+ effective start/end) and **Effective Date BOM** (per-component dates). No auto-obsolete.+ [Component Where Used](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_1511882961.html)+- **Odoo** — **date-based** effectivity per ECO ("As soon as possible" / "At Date");+ a BoM's ECO smart button lists done ECOs. **No where-used view** (ECO scope is+ per-BoM). Obsoleting = **archiving** (not delete).+ [Version control](https://www.odoo.com/documentation/19.0/applications/inventory_and_mrp/plm/manage_changes/version_control.html)+- **Fishbowl** — **no effectivity dates, no native where-used**; obsolete = uncheck the+ **Active** flag.+ [Fishbowl BOM CSV spec](https://fishbowlhelp.com/files/csv/exportBOM.html)++**Consensus:** Where-used is the standard way to surface broader impact before a "local"+change; date effectivity is the baseline sequencing mechanism (higher-end systems add+serial/unit/lot/parameter). **No system auto-obsoletes a removed part "only if now+unused"** — it is always a manual decision informed by where-used (Duro even blocks the+parent if any child is Obsolete). This means Carbon should treat "obsolete the removed+part" as an explicit, where-used-guided user action, not an automatic side effect of a+consolidation.++---++## Q6. Release ordering — new part must exist/release before the parent references it++**Every system's practical answer is the same: put the new part and the parent+restructure on the SAME change so they release together at one effectivity. Hard+dependency validation ("child released before parent") ranges from enforced (Duro,+SAP existence check) to workflow/rule-driven (Windchill, Teamcenter) to absent (Agile,+Arena, OpenBOM, NetSuite, Odoo).**++- **SAP** — a **hard existence constraint**: a component **must exist and be extended+ to the plant** before it can go on a BOM (CS01/CS02 error "Material not maintained in+ plant"), so MM01 the new material first. Beyond existence, no separate "release child+ then parent" gate — both carry the same change-number valid-from and go effective+ together.+ [material must exist in plant](https://community.sap.com/t5/enterprise-resource-planning-q-a/error-material-doesn-t-exist-in-plant/qaq-p/2803881)+- **Duro** — an **enforced validated rule**: "for a parent assembly to be at+ Prototype/Production, all child components must be at the same status level or+ higher," checked via a **Validate** button (blocking errors vs warnings). New child ++ parent are rolled into one atomic CO and validated together.+ [Lifecycle Validations](https://duro.zendesk.com/hc/en-us/articles/360044348651-Lifecycle-Validations-and-Updates)+- **Windchill** — new child + revised parent are both **Resulting Objects** released+ atomically ("sets all Resulting Objects to Released"); dependency ordering is+ delivered via configurable **Business Rules** ("validate that the children… are at an+ appropriate state to release the parent"). No single hard built-in child-before-parent+ lock beyond atomic release + rules.+ [Business Rules](https://support.ptc.com/help/windchill/cloud/r12.0.2.0/en/Windchill_Help_Center/BusRules.html)+- **Teamcenter** — workflow/EPM handlers (`EPM-attach-assembly-components`) release an+ assembly with its components, but only *skip* components already in-workflow — correct+ child-first ordering is a **workflow-design responsibility**, not an OOTB guarantee.+ [Workflow handlers](https://globalplm.com/teamcenter-workflow-handlers/)+- **Agile / Arena** — release all affected items on **one change simultaneously**;+ neither documents an explicit child-before-parent validation. Ordering is achieved by+ bundling child + parent onto one ECO. (Arena tracks cross-ECO pending work via+ `futurechanges`.)+ [Agile Ch.8](https://docs.oracle.com/cd/E50306_29/otn/pdf/user/html_agaad/output/chapter_8.htm)+- **Oracle Fusion** — status pipeline **Open → Approval → Scheduled → Completed**; a+ future-effective rev from a Scheduled change can be selected as a source on a later+ change. No explicit child-before-parent rule documented; bundling + effective dates+ drive ordering.+ [Change Order Statuses](https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/24a/faipr/understand-change-order-statuses.html)+- **OpenBOM** — **flat/batch**: "once all CRs are approved, a revision for all items is+ created" — all affected items revise together, no enforced child-before-parent order.+ [Change management](https://www.openbom.com/blog/change-management-in-openbom-revision-change-request-and-change-orders)+- **NetSuite / Odoo** — **no dependency sequencer**; ordering is governed by **date+ effectivity** (NetSuite) and by the part existing first + per-ECO Effective Date+ (Odoo, since each ECO targets one BoM — new-part-plus-parent is inherently two ECOs).+ [NetSuite implementing ECOs](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/bridgehead_1531291499.html)++**Consensus:** The universal pattern is **one change, atomic release, single+effectivity** — the new part and the parent that consumes it ride the same CO and go+live together. This is exactly what a good "new part + parent consolidation on one CO"+flow should do.++**Divergence:** enforcement strength — **Duro strictly validates** parent-status ≤+child-status; **SAP enforces existence-in-plant**; **Windchill/Teamcenter rely on+configurable rules/workflow**; **Agile/Arena/Fusion/OpenBOM/NetSuite/Odoo enforce+nothing beyond bundling + effectivity**. A minimal-but-correct Carbon rule is: within+one CO, if a new part is consumed by a restructured parent, release the new part's+draft *before* activating the parent's method (or activate both atomically).++---++## Implications for Carbon++Carbon today (`changeOrderChangeTypes = Version | Revision | New Part`) uses **"New+Part"** to mean a *new P/N that supersedes the affected part 1:1* — which industry+practice would call a **replacement/supersession**, not a net-new part. That naming+should change. The three proposed model choices are each well-supported:++**(a) Rename the 1:1-supersession change type from "New Part" → "Replacement Part".**+STRONGLY SUPPORTED. Across the industry, "new part with a predecessor that it takes+over from" is universally a **replace / supersede / supersession**, never "new part":+Windchill/Teamcenter **Supersede/Supersedure**, Fusion/NetSuite **Replace a+Component**, Duro **Effectivity supersession**, Agile redline-into-consuming-BOMs. The+word **"New Part"** everywhere means a part with **no predecessor** (Q2) — so Carbon's+current usage is actively misleading. **"Replacement Part"** is a clear, industry-legible+name for the 1:1 predecessor→successor semantics Carbon already implements+(affectedPart → newPart `itemSupersession` at release). (If a shorter label is wanted,+**"Replacement"** or **"Supersession"** are the other industry-standard options;+"Replacement Part" reads best as a per-item disposition.)++**(b) Add a net-new "New Part" (no predecessor) released with the CO.** SUPPORTED and+squarely in the PLM-grade camp. Windchill (Resulting Object = New), Teamcenter (Solution+Item), Agile (Introductory→A on ECO release), Fusion (affected object / NIR), Arena+(PRELIMINARY→PRODUCTION on approval), Duro (promotion creates the CO), and SAP (MM01+under a change number) all let a **predecessor-less** part be reviewed and released+through the change — the part is born in an unreleased lifecycle state and the CO's+completion promotes it. This is *distinct* from the renamed "Replacement Part" precisely+by having **no supersession** written at release (it just reveals/activates the new item,+like Carbon's Revision/New-Part release path minus the `itemSupersession` write). The+mid-market ERPs (NetSuite/Odoo/Fishbowl) can't do this at all, so shipping it puts Carbon+ahead of that tier. Recommended lifecycle: mint the item inactive (Carbon already does+this via `mintPlaceholderPart` / `copyItem`), reveal + activate at release, but write+**no** `itemSupersession`.++**(c) Model N→1 consolidation as a parent-assembly BOM change, not a supersession.**+STRONGLY SUPPORTED — this is unanimous across all 11 systems (Q3). "3 parts become 1" is+always a **restructure of the PARENT's BOM** (remove 3 component lines, add 1), surfaced+in a green/red add-remove **BOM diff**, and released with the parent's new+method/revision. It is **never** modeled as N part-to-part supersessions. Concretely for+Carbon: the consolidation is authored on the **parent** affected item's draft+`makeMethod` (remove the 3 `methodMaterial` rows, add the 1 new component) — which+Carbon's existing per-affected-item draft-method + `diffMethod` engine already+represents. The new consolidated component, if net-new, is a separate **"New Part"**+affected item on the **same CO** (Q6: one CO, atomic release). Do **not** auto-create+supersessions for the 3 removed parts; removal from a BOM ≠ obsolescence. If the removed+parts should be retired, that is a **separate, explicit, where-used-guided** decision+(Q5: no system auto-obsoletes-if-unused) — Carbon's **Impact panel / where-used** is the+right place to surface "these removed parts are still used in N other assemblies" before+anyone obsoletes them.++**Cross-cutting terminology recommendation for the spec.** Adopt the industry-consensus+vocabulary Carbon is already partway to:+- **Revision** — same part number, new rev (matches everyone). Keep.+- **Version** — Carbon-specific (new make-method version, same item, no supersession);+ no industry analog, but harmless and internally clear. Keep.+- **Replacement Part** — new P/N that **supersedes** a predecessor 1:1 (the renamed type).+- **New Part** — new P/N with **no predecessor**, released with the CO (the new type).+- **Consolidation / BOM restructure** — a parent-BOM change (add/remove components),+ expressed through the parent affected item's diff, *not* a change type of its own.+- Reserve **Supersession** for the predecessor→successor *relationship* Carbon writes at+ release (`itemSupersession`), which "Replacement Part" produces and "New Part" does not.++### Consensus vs. divergence at a glance++| Question | Consensus | Divergence |+|---|---|---|+| Q1 disposition | revise-in-place (same #) vs replace (new #); before→after split | names for "replace"; Arena/OpenBOM have no renumber disposition |+| Q2 new part in ECO | PLM-grade systems release a predecessor-less part via the change | mid-market ERPs (NetSuite/Odoo/Fishbowl) can't mint a part in the ECO |+| Q3 N→1 consolidation | always a **parent-BOM** add/remove; green/red diff | only whether single-line "Replace" is a primitive |+| Q4 replace scope | LOCAL swap vs GLOBAL where-used/supersede are distinct concepts | true global mass-replace only in Windchill/Teamcenter/SAP |+| Q5 effectivity/where-used | where-used surfaces impact; date effectivity; **no auto obsolete-if-unused** | serial/unit/lot/parameter effectivity only in high-end systems |+| Q6 release ordering | one CO, atomic release, one effectivity | enforcement: Duro/SAP enforce, others rely on bundling |++---++## Sources (primary references)++- PTC Windchill Help — [Change Mgmt](https://support.ptc.com/help/wnc/r12.0.0.0/en/Windchill_Help_Center/ChgMgmtAbout.html), [Redline Process](https://support.ptc.com/help/windchill/plus/r12.0.2.0/en/Windchill_Help_Center/ChgMgmtRedlineProcess.html), [Mass Change Replace](https://support.ptc.com/help/windchill/r12.1.2.0/en//Windchill_Help_Center/changemanagement/ChgMgmtMassChangeReplace.html), [Superseding Parts](https://support.ptc.com/help/windchill/r12.1.2.0/en/Windchill_Help_Center/parts/PMPartSupersedeOview.html)+- Siemens Teamcenter — [Supersedure](https://tcplmbasics.com/2018/06/07/supersedure-in-teamcenter/), [Design BOM tracking / Active Change](https://blogs.sw.siemens.com/teamcenter/design-bom-tracking-use-active-change/), [What's new 2312](https://blogs.sw.siemens.com/teamcenter/whats-new-in-teamcenter-2312/)+- Oracle Agile PLM 9.3.x — [Ch.7 Changes](https://docs.oracle.com/cd/E50306_29/otn/pdf/user/html_agaad/output/chapter_7.htm), [Ch.8 Affected Items](https://docs.oracle.com/cd/E50306_29/otn/pdf/user/html_agaad/output/chapter_8.htm), [Ch.5 BOM](https://docs.oracle.com/cd/E50306_29/otn/pdf/user/html_agaad/output/chapter_5.htm), [Ch.2 Items](https://docs.oracle.com/cd/E60149_28/otn/pdf/user/html_agaad/output/chapter_2.htm)+- Oracle Fusion Cloud PLM — [Change Types](https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/26a/faipr/understand-change-types.html), [Replace a Component](https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/25d/faupd/replace-a-component.html), [Effective Date & Revision](https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/26a/faupd/effective-date-and-revision-for-affected-objects.html)+- SAP LO-ECH — [ECM overview](https://help.sap.com/doc/saphelp_me151/15.1.3VERSIONFORSAPME/en-US/da/6cb953495bb44ce10000000a174cb4/content.htm?no_cache=true), [ECR/ECO](https://help.sap.com/doc/saphelp_me151/15.1.3VERSIONFORSAPME/en-US/75/25bd534f22b44ce10000000a174cb4/content.htm?no_cache=true), [CS20 mass change](https://community.sap.com/t5/enterprise-resource-planning-q-a/how-to-change-bom-components-in-mass/qaq-p/10006909)+- Arena PLM — [ECN article](https://www.arenasolutions.com/resources/articles/engineering-change-notice/), [REST API create change](https://raw.githubusercontent.com/ptc-arena/arena-restapi-doc/main/Arena%20REST%20API/Endpoints/Change/endpoint_create_change.md), [Where used in BOMs](https://www.arenasolutions.com/blog/where-used-in-boms-arena-excel/)+- Duro — [Change Orders](https://duro.zendesk.com/hc/en-us/articles/360029600032-Change-Orders), [Effectivity](https://duro.zendesk.com/hc/en-us/articles/10159748251924-Effectivity), [Lifecycle Validations](https://duro.zendesk.com/hc/en-us/articles/360044348651-Lifecycle-Validations-and-Updates), [Compare Revisions](https://duro.zendesk.com/hc/en-us/articles/360050079871-Compare-Revisions)+- OpenBOM — [Change management](https://www.openbom.com/blog/change-management-in-openbom-revision-change-request-and-change-orders), [Alternates & substitutes](https://www.openbom.com/blog/how-to-model-alternate-and-substitute-bom-components-in-openbom), [BOM Compare](https://help.openbom.com/my-openbom/bom-compare/)+- NetSuite — [ECO](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/chapter_1531288763.html), [Creating ECOs](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/bridgehead_1531291168.html), [Component Where Used](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_1511882961.html)+- Odoo — [Engineering Change Orders](https://www.odoo.com/documentation/19.0/applications/inventory_and_mrp/plm/manage_changes/engineering_change_orders.html), [Version control](https://www.odoo.com/documentation/19.0/applications/inventory_and_mrp/plm/manage_changes/version_control.html)+- Fishbowl — [Bill of Materials](https://www.fishbowlinventory.com/manufacturing/bill-of-materials), [BOM CSV spec](https://fishbowlhelp.com/files/csv/exportBOM.html)++*Sourcing caveats carried from research: Duro/Fishbowl help portals block automated+fetch (claims grounded in official articles surfaced via search); a few Teamcenter+effectivity/field names are corroborated via partner/community sources; Agile PLM PC is+date-effectivity-only (serial/unit effectivity is the separate EBS product); "disposition"+in Windchill/Agile/Arena means inventory handling, not part identity.*diff --git a/.ai/specs/2026-07-19-change-order-new-part-and-consolidation.md b/.ai/specs/2026-07-19-change-order-new-part-and-consolidation.mdnew file mode 100644index 0000000000..2b974d187d--- /dev/null+++ b/.ai/specs/2026-07-19-change-order-new-part-and-consolidation.md@@ -0,0 +1,281 @@+# Change Orders — Replacement Part rename, net-new New Part, and BOM consolidation++> Status: draft+> Author: Brad Barbin (with Claude)+> Date: 2026-07-19++## TLDR++The change-order (ECO) module's `New Part` change type is misnamed: it always+mints a new part number **derived from** the affected part and auto-writes a 1:1+`affectedPart → newPart` `itemSupersession` at release — i.e. it is a+*replacement*, not a new part. This spec (1) **renames `New Part` → `Replacement+Part`**, (2) adds a genuinely net-new **`New Part`** change type — a brand-new+part with **no predecessor and no supersession**, minted and released under the+change order (Make or Buy), and (3) enables **N→1 consolidation** ("3 parts+become 1") as a change to the **parent assembly's** make-method BOM (remove the+old component lines, add the new one) that consumes a `New Part` — expressed+entirely through the existing `diffMethod` engine, with **no supersession**. No+new tables; the work is one enum migration plus additive service/UI paths.+Grounded in `.ai/research/2026-07-19-co-part-consolidation.md` (11 PLM/ERP+systems surveyed).++## Problem Statement++Two related gaps, both discovered while modeling a real ECO: *"I'm not replacing a+part on a BOM — I'm introducing a new way of doing things: 3 parts become 1."*++1. **`New Part` is a misnomer and blocks a genuine new-part use case.** Today the+ change types are `Version` (new make-method version, same item, no+ supersession), `Revision` (new revision item, same readableId, `oldRev →+ newRev` supersession), and `New Part` (new part **number** derived from the+ affected part, `affectedPart → newPart` supersession). All three are anchored+ to an **existing** affected part, and `New Part` **always** writes a 1:1+ supersession (`createChangeOrderDraftMethod` New Part branch,+ `items.service.ts`; the reveal+supersession in `releaseAffectedItem`,+ `items.server.ts:407`). There is **no way to introduce a brand-new part with+ no predecessor** under a change order. `mintPlaceholderPart` exists in+ `items.service.ts` but is wired to nothing (the AGENTS "G3 forward-reference"+ claim is stale).++2. **Consolidation has no home.** A change that removes several components from an+ assembly's BOM and adds one new component is *not* a part-to-part supersession+ — the removed parts are not being replaced everywhere they are used, only+ dropped from **this** assembly. Using `New Part`/`Revision` (which write a+ global-redirect `itemSupersession`, consumed by the supersession redirect map+ in `get-method`/MRP) would wrongly redirect those components in **every other**+ assembly that uses them. There is no supported way to say "restructure this+ assembly's BOM and introduce the consolidated part as part of the same+ controlled change."++Industry practice is unambiguous (research): a new part number that supersedes a+predecessor is universally **Replace/Supersede** (Windchill/Teamcenter+"Supersede", Fusion/NetSuite "Replace a Component", Duro "supersession"); **"New+Part" everywhere means no predecessor**; and **N→1 consolidation is always a+parent-BOM add/remove**, never N supersessions.++## Proposed Solution++### Change-type taxonomy (after this spec)++Two axes — *is there a predecessor?* and *same part number or new one?*:++| Change type | Predecessor | Part number | Supersession at release | Draft |+|---|---|---|---|---|+| **Version** | same part | same # | none | new make-method version on the same item |+| **Revision** | same part | same #, new rev string | `oldRev → newRev` | new inactive revision item |+| **Replacement Part** *(renamed from `New Part`)* | same part | **new #** derived from source | `affectedPart → newPart` | new inactive part, method copied from source |+| **New Part** *(net-new)* | **none** | **new #** from the type sequence | **none** | new inactive part, **empty** draft method (Make) or attrs-only (Buy) |++**Consolidation is not a change type.** It is the combination, in one CO, of:+(a) a **New Part** affected item (the consolidated "1"), and (b) the **assembly**+as a **Version** (or **Revision**) affected item whose draft BOM removes the old+component lines and adds a line referencing the New Part. The `diffMethod` engine+already classifies `added`/`removed` materials (`items.service.ts:6624/6643`), so+the CO renders `− P1 − P2 − P3 + P_new` with no new machinery.++### How a New Part flows++- **Add** — a new "**Create new part**" mode in the add-affected-item flow (a+ minimal new-part form: auto-minted `readableId` with override, name, type+ Part/Tool, replenishment Make/Buy). On submit: mint an **inactive** item ++ (for Make) an **empty** CO-owned draft `makeMethod`, then insert a+ `changeOrderAffectedItem` with `changeType = 'New Part'`.+- **Author** — the New Part's affected-item detail reuses the embedded+ `PartProperties` (attributes) and, for Make, `BillOfMaterial`/`BillOfProcess`+ editors — identical to a Replacement/Revision draft, but starting empty and+ with **no cutover/supersession card** (there is no predecessor).+- **Consume** — the assembly's draft BOM editor can add a line referencing the+ New Part's (inactive) draft item; inactive items are legal BOM components.+- **Release** — `releaseAffectedItem` reveals the New Part active+ (`item.active = true`, stamp `item.changeOrderId`) and activates its draft+ method, but **skips the supersession** (only Revision + Replacement Part write+ one). The assembly's new method version activates in the same run, ordered so+ the New Part is revealed first.++### Design Decisions++| Decision | Choice | Rationale |+|----------|--------|-----------|+| Rename the 1:1-supersession type | `New Part` → **`Replacement Part`** | It always writes `affectedPart → newPart` supersession; "New Part" everywhere in industry means *no predecessor* (research consensus, all 11 systems). User-selected. |+| Add a net-new change type | **`New Part`** (no predecessor, no supersession) | Standard PLM behavior (Windchill/Teamcenter/Agile/Fusion/Arena/Duro); unblocks introducing a part under change control. User-selected. |+| New Part item scope | **Make + Buy** | Reuses the existing draft-method + embedded `BillOfMaterial`/`BillOfProcess` editors; the consolidated "1" may itself be a make sub-assembly. Delta vs today = start from an empty draft method instead of copying a source. User-selected. |+| New Part is a first-class **affected item** | Own explorer row + own draft, not an inline BOM-line side effect | Matches Carbon's affected-item-centric model; lets the new part be governed, authored, and released with the CO. Settled by model + research. |+| Standalone New Part | **Allowed** — no assembly change required in the same CO | Supports "introduce a new part under an ECO" on its own; consolidation is just New Part + an assembly Version change bundled. User-selected. |+| Consolidation modeling | **Parent-assembly BOM change** (Version/Revision) via `diffMethod` add/remove — **no** change type of its own, **no** supersession | Unanimous across all 11 systems; N→1 as supersession would wrongly redirect the removed parts everywhere they are used. User-selected framing. |+| Removed components | Surface **where-used** on removed diff lines; **no auto-obsolete** | No surveyed system auto-obsoletes; obsolescence stays a manual, where-used-guided action. Reuses `getPartUsedIn`. User-selected. |+| New Part number assignment | **Auto-mint from the type sequence, user override** | Mirrors `/x/part/new` (`useNextItemId`); Replacement Part keeps its derive-from-source minting (`getNextItemIdFromSource`). |+| Release supersession gating | Supersession only for **Revision** and **Replacement Part**; **New Part** and **Version** write none | New Part has no predecessor; Version edits the same item. One-line change to the `releaseAffectedItem` guard. |+| Change-type switcher | `updateChangeOrderAffectedItemChangeType` offers only {Version, Revision, Replacement Part} for an existing affected item; **cannot switch to/from `New Part`** | A New Part is intrinsically net-new; converting an existing-part change into a no-predecessor part (or vice-versa) is contradictory. |+| New Part item types | **Parts + Tools only** (Materials/Consumables/Services rejected) | Mirrors Replacement Part + the affected-item scope. |+| Data model | **No new tables/columns** | Reuse `changeOrderAffectedItem` (its `itemId`/`newItemId`/`draftMakeMethodId` already carry everything); the change is an enum rename + add and additive logic. |++## Data Model Changes++**No new tables or columns.** One enum migration on `changeOrderChangeType`+(created in `20260716101500_change-orders.sql`):++```sql+-- Rename the 1:1-supersession type. Existing changeOrderAffectedItem rows with+-- changeType = 'New Part' become 'Replacement Part' for free — they all already+-- carry an affected → new itemSupersession, so the relabel is semantically exact.+ALTER TYPE "changeOrderChangeType" RENAME VALUE 'New Part' TO 'Replacement Part';++-- Add the net-new type. NOTE: Postgres cannot use a newly ADDed enum value in the+-- same transaction that adds it, so this ADD VALUE must land (and commit) before+-- any migration/statement references 'New Part'. Keep it in its own migration+-- step; no data backfill (no existing rows are net-new).+ALTER TYPE "changeOrderChangeType" ADD VALUE 'New Part';+```++`changeOrderAffectedItem` field usage per change type (unchanged columns, new+interpretation for `New Part`):++| Field | Version | Revision | Replacement Part | **New Part** |+|---|---|---|---|---|+| `itemId` | the affected item | the affected item | the affected (source) item | **the minted new item** |+| `baseMakeMethodId` | source Active method | source Active method | source Active method | **null** (nothing copied) |+| `draftMakeMethodId` | new draft version | new revision's draft | new part's draft (copied) | **new part's empty draft** (Make) / null (Buy) |+| `newItemId` | null | new revision item | new part item | **the minted new item** (drives reveal) |+| cutover (`supersessionMode`, dates) | n/a | set | set | **n/a** (no predecessor) |++After the migration, run `pnpm run generate:types`; regenerate the+`changeOrderChangeTypes` const array + `ChangeOrderChangeType` type in+`items.models.ts` to match (`Version`, `Revision`, `Replacement Part`, `New Part`).++## API / Service Changes++All in the Items module's canonical files (per the one-service/models/server+convention — no `changeOrder.*` files).++- **`items.models.ts`** — `changeOrderChangeTypes` becomes `["Version",+ "Revision", "Replacement Part", "New Part"]`. Add a validator for the new-part+ add form (`changeOrderNewPartValidator`: `readableId?`, `name`, `type`+ ∈ {Part, Tool}, `replenishmentSystem` ∈ {Buy, Make, Buy and Make}).+- **`items.service.ts`**+ - `createChangeOrderDraftMethod` — the existing `changeType === "New Part"`+ branch (copy-from-source + mint derived number) is **renamed** to+ `"Replacement Part"` (logic unchanged, incl. `getNextItemIdFromSource` and+ the Parts/Tools guard). Add a **new** `"New Part"` branch: mint an inactive+ item (auto number from the type sequence or the supplied override), create an+ **empty** CO-owned draft `makeMethod` when Make (none for Buy), stamp+ `changeOrderId`, write draft refs (`newItemId = itemId = minted id`,+ `baseMakeMethodId = null`).+ - `addChangeOrderAffectedItem` — accept a `newPart?: {...}` payload; when+ present, mint the item first (via `createChangeOrderDraftMethod`'s New Part+ path) and insert the affected-item row with `changeType = 'New Part'`. The+ existing "must be an existing itemId" path is unchanged for the other types.+ - `updateChangeOrderAffectedItemChangeType` — reject transitions into or out of+ `New Part`; the picker only exposes {Version, Revision, Replacement Part}.+ - Every `=== "New Part"` string branch (currently meaning *replacement*) is+ audited and updated to `"Replacement Part"`; genuinely-net-new logic lives in+ the new `"New Part"` branches. (`grep -rn '"New Part"'` before/after.)+- **`items.server.ts`** — `releaseAffectedItem`:+ - Change the supersession guard from `if (changeType !== "Version" &&+ newItemId)` to only Revision + Replacement Part; `New Part` reveals its item+ (active + `changeOrderId` stamp) and activates its draft **without**+ supersession.+ - `applyChangeOrder` orders releases so a New Part affected item is revealed+ before any assembly (Version/Revision) affected item whose BOM references it;+ keep the per-item idempotency (a released draft has `changeOrderId` cleared).+- **Where-used** — reuse `getPartUsedIn` to compute, for each **removed** BOM line+ on an assembly draft, whether the component is still used by *other* parents+ (count excluding the assembly being edited). No new service; a thin wrapper /+ the existing `impactUsedIn` loader data on the CO `$id` route.++## UI Changes++- **Add-affected-item flow** (`AffectedItemForm.tsx`) — add a **change-type+ `Select`** at the top of the modal (Version / Revision / Replacement Part /+ New Part) as the single control that drives the form: Version/Revision/+ Replacement Part reveal today's `<Item>` picker over existing Parts/Tools;+ **New Part** reveals a minimal new-part mini-form (auto-minted readableId with+ override via `useNextItemId`, name, type Part/Tool, replenishment Buy/Make).+ Posts to `path.to.changeOrderAffected`; the action branches on `changeType`+ (New Part → `changeOrderNewPartValidator` + mint; others → existing path).+ This replaces the old add-then-switch-type default and makes the change type+ explicit at add time.+- **Change-type picker** (`AffectedItemDetail.tsx`) — rename the `New Part`+ option label to **Replacement Part**; the picker for an existing affected item+ offers {Version, Revision, Replacement Part} only. A `New Part` line shows its+ type as a read-only "New Part" (no switcher).+- **Affected-item detail for New Part** — reuse `PartProperties` (attributes) and,+ for Make, `BillOfMaterial`/`BillOfProcess`; **hide** the cutover/Part+ Supersession card (extend `showCutover` to also exclude `New Part`), since there+ is no predecessor. Part number editable (fresh number), like today's New Part.+- **Badge** (`ChangeTypeBadge.tsx`) — labels: `Version N`, `New Revision`+ (existing), **`Replacement`** for Replacement Part, **`New`** for New Part+ (green). Reserve the plain "New" for the genuinely-new type.+- **Assembly BOM editor within a CO** (`BillOfMaterial.tsx`) — the add-material+ `<Item>` picker must be able to reference the current CO's **New Part** draft+ items (inactive). Include the CO's New Part drafts in the pickable set for an+ affected-assembly draft BOM.+- **Removed-component where-used** — on the assembly's authoring diff+ (`ChangeOrderDiffViewer` removed rows / the affected-item `AffectedItemDetail`),+ show a small "used in N other assemblies" indicator per removed component,+ linking to that part's where-used. No obsolete action in v1.+- **Explorer** (`ChangeOrderExplorer.tsx`) — a New Part row shows "NEW → {minted+ number}" (no "OLD →"), consistent with the existing OLD→NEW rows.++## Acceptance Criteria++- [ ] The change-type enum reads `Version, Revision, Replacement Part, New Part`;+ an existing CO whose affected item was `New Part` now displays+ **Replacement Part** with its `affectedPart → newPart` supersession intact+ after release (behavior unchanged, label changed).+- [ ] From a change order, "Create new part" mints an inactive Part with an+ auto-minted number (overridable), adds it as a **New Part** affected item+ with its own explorer row and draft; the affected-item detail shows+ attributes and (for Make) empty BOM/BOP editors and **no** cutover card.+- [ ] Releasing a CO with a **New Part** activates the new item (`active = true`,+ `changeOrderId` stamped) and its draft method, and writes **no**+ `itemSupersession` for it; the item appears as a normal active part.+- [ ] Consolidation end-to-end: on an assembly, a Version change removes 3+ component lines and adds a line referencing a New Part (added in the same+ CO); the CO's Changes diff shows `−`×3 and `+`×1; after release the+ assembly's active method has the new BOM and the 3 removed parts are+ untouched everywhere else (no supersession redirect fires for them in+ `get-method`/MRP).+- [ ] The change-type switcher on an existing affected item cannot select+ `New Part`; a `New Part` affected item cannot be switched to another type.+- [ ] Each removed component on the assembly diff shows how many other assemblies+ still use it (where-used), with no auto-obsolete action taken.+- [ ] `New Part` is rejected for Materials/Consumables/Services.+- [ ] Typecheck, biome, and the items unit tests pass; `diffMethod` add/remove+ classification is covered by a test for the consolidation case.++## Risks++| Risk | Severity | Mitigation |+|------|----------|------------|+| The string `'New Part'` currently means *replacement*; after migration it means *net-new*. Missed branches silently change behavior. | High | Enumerate every `=== "New Part"` / `"New Part"` literal (grep) and re-point to `"Replacement Part"`; add the net-new branches separately. Cover with the acceptance test that an old New Part still supersedes as "Replacement Part". |+| Postgres `ADD VALUE` can't be used in the same txn that references it. | Med | Land RENAME + ADD in a migration that does not itself reference the new value; regenerate types after apply. |+| Assembly BOM editor can't pick an inactive New Part draft, breaking consolidation. | Med | Explicitly include the CO's New Part drafts in the affected-assembly BOM item picker; inactive items are already legal BOM components. |+| Release ordering: assembly method activates while its New Part is still inactive. | Med | `applyChangeOrder` reveals New Part affected items before assembly affected items; idempotent per item on retry. |+| Scope creep into global mass-replace / auto-obsolete. | Low | Explicitly out of scope for v1 (research: local per-BOM replace + manual obsolete is the norm). |+| Renaming a live enum value touches the `changeOrders` view / generated types. | Low | Enum value rename does not change columns; `CREATE OR REPLACE`/regen only if a view string-matches the value (none do); run `generate:types`. |++## Open Questions++> Resolved with the user before writing (Step 5). Audit trail — all answered.++- [x] **New Part item scope: Make + Buy, or Buy-only for v1?** — **Answer:**+ **Make + Buy.** Reuses the existing embedded BOM/BOP editors; the delta is+ an empty draft method vs a copied one. Lets the consolidated "1" be a make+ sub-assembly.+- [x] **Can a CO add a New Part standalone (no assembly change)?** — **Answer:**+ **Yes.** A New Part can be introduced on its own; consolidation is New Part+ + an assembly Version change bundled. Also supports plain "new part under an+ ECO".+- [x] **Name for the renamed 1:1-supersession type?** — **Answer:**+ **Replacement Part.** Industry-legible (Replace/Supersede vocabulary);+ reads clearly beside Version/Revision/New Part.+- [x] **What does v1 do about components removed from the assembly's BOM?** —+ **Answer:** **Show where-used, manual obsolete.** Surface where the removed+ parts are used elsewhere (reuse `getPartUsedIn`); never auto-obsolete —+ matches every surveyed system.++## Changelog++- 2026-07-19: Created. Research (`.ai/research/2026-07-19-co-part-consolidation.md`,+ 11 PLM/ERP systems) + 4 open questions resolved with the user before writing.diff --git a/apps/erp/app/components/ActionTasks/ActionTaskAddModal.tsx b/apps/erp/app/components/ActionTasks/ActionTaskAddModal.tsxnew file mode 100644index 0000000000..635d0b65b4--- /dev/null+++ b/apps/erp/app/components/ActionTasks/ActionTaskAddModal.tsx@@ -0,0 +1,126 @@+import {+ Button,+ Checkbox,+ Modal,+ ModalBody,+ ModalContent,+ ModalFooter,+ ModalHeader,+ ModalOverlay,+ ModalTitle,+ VStack+} from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import { useCallback, useEffect, useRef, useState } from "react";+import { LuCirclePlus } from "react-icons/lu";+import type { ListItem } from "~/types";++// The shared "Add Actions" affordance used by Quality issues and Change Orders:+// a dashed button opening a modal that picks from the entity's required-action+// templates. Submission is delegated to `onAdd` (each caller wires its route);+// `isSubmitting` drives the button state and closing on success is the caller's+// job (re-render with the new tasks removes the modal via `isSubmitting` reset).+export function ActionTaskAddModal({+ templates,+ onAdd,+ isSubmitting = false,+ isDisabled = false,+ emptyMessage+}: {+ templates: ListItem[];+ onAdd: (selectedIds: string[]) => void;+ isSubmitting?: boolean;+ isDisabled?: boolean;+ emptyMessage?: string;+}) {+ const [isOpen, setIsOpen] = useState(false);+ const [selectedIds, setSelectedIds] = useState<string[]>([]);++ const close = useCallback(() => {+ setIsOpen(false);+ setSelectedIds([]);+ }, []);++ const onToggle = useCallback((id: string, checked: boolean) => {+ setSelectedIds((prev) =>+ checked ? [...prev, id] : prev.filter((x) => x !== id)+ );+ }, []);++ // Close once a submit resolves (isSubmitting true → false). The caller owns+ // the fetcher; an error surfaces via flash, so closing on resolve is fine.+ const wasSubmitting = useRef(false);+ useEffect(() => {+ if (wasSubmitting.current && !isSubmitting) close();+ wasSubmitting.current = isSubmitting;+ }, [isSubmitting, close]);++ return (+ <>+ <button+ type="button"+ className="flex items-center justify-start bg-card border-2 border-dashed border-background w-full hover:bg-background/80 rounded-lg px-10 py-6 text-muted-foreground hover:text-foreground gap-2 transition-colors duration-200 text-sm cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"+ onClick={() => setIsOpen(true)}+ disabled={isDisabled}+ >+ <LuCirclePlus size={16} />+ <span>+ <Trans>Add Actions</Trans>+ </span>+ </button>++ <Modal+ open={isOpen}+ onOpenChange={(open) => {+ if (!open) close();+ }}+ >+ <ModalOverlay />+ <ModalContent>+ <ModalHeader>+ <ModalTitle>+ <Trans>Add Actions</Trans>+ </ModalTitle>+ </ModalHeader>+ <ModalBody>+ <VStack spacing={2}>+ {templates.length === 0 && emptyMessage && (+ <span className="text-sm text-muted-foreground">+ {emptyMessage}+ </span>+ )}+ {templates.map((template) => (+ <label+ key={template.id}+ htmlFor={template.id}+ className="flex items-center gap-2 w-full px-4 py-3 rounded-lg hover:bg-accent hover:text-accent-foreground border border-border cursor-pointer"+ >+ <Checkbox+ id={template.id}+ isChecked={selectedIds.includes(template.id)}+ onCheckedChange={(checked) =>+ onToggle(template.id, !!checked)+ }+ />+ <span className="text-sm font-medium">{template.name}</span>+ </label>+ ))}+ </VStack>+ </ModalBody>+ <ModalFooter>+ <Button variant="secondary" onClick={close}>+ <Trans>Cancel</Trans>+ </Button>+ <Button+ onClick={() => onAdd(selectedIds)}+ isDisabled={selectedIds.length === 0 || isSubmitting}+ isLoading={isSubmitting}+ >+ <Trans>Add Actions</Trans>+ </Button>+ </ModalFooter>+ </ModalContent>+ </Modal>+ </>+ );+}diff --git a/apps/erp/app/components/ActionTasks/ActionTaskCard.tsx b/apps/erp/app/components/ActionTasks/ActionTaskCard.tsxnew file mode 100644index 0000000000..2db41f8295--- /dev/null+++ b/apps/erp/app/components/ActionTasks/ActionTaskCard.tsx@@ -0,0 +1,170 @@+import {+ Button,+ cn,+ generateHTML,+ HStack,+ IconButton,+ type JSONContent,+ useDisclosure+} from "@carbon/react";+import { Editor } from "@carbon/react/Editor";+import { useLingui } from "@lingui/react/macro";+import type { DragControls } from "framer-motion";+import type { ReactElement, ReactNode } from "react";+import {+ LuChevronRight,+ LuCircleCheck,+ LuCirclePlay,+ LuGripVertical,+ LuLoaderCircle+} from "react-icons/lu";+import Assignee from "~/components/Assignee";++export type ActionTaskStatus =+ | "Pending"+ | "In Progress"+ | "Completed"+ | "Skipped";++// The Start/Complete/Reopen transition, shared by every action-task surface+// (Quality issues + Change Orders).+export const actionTaskStatusActions: Record<+ ActionTaskStatus,+ { action: string; icon: ReactElement; next: ActionTaskStatus }+> = {+ Pending: { action: "Start", icon: <LuCirclePlay />, next: "In Progress" },+ "In Progress": {+ action: "Complete",+ icon: <LuCircleCheck />,+ next: "Completed"+ },+ Completed: { action: "Reopen", icon: <LuLoaderCircle />, next: "Pending" },+ Skipped: { action: "Reopen", icon: <LuLoaderCircle />, next: "Pending" }+};++// The single, shared presentational card for an action task — used by both the+// Quality issue actions and the Change Order actions so the two look identical.+// Purely presentational: persistence (notes save, status route, integrations)+// lives in the calling wrapper and is threaded in via callbacks + slots.+export function ActionTaskCard({+ title,+ status,+ notes,+ canEditNotes,+ onNotesChange,+ onUploadImage,+ onStatusChange,+ assigneeTable,+ assigneeId,+ assignee,+ statusBadge,+ headerExtras,+ footerExtras,+ isDisabled = false,+ showDragHandle = false,+ dragControls+}: {+ title: string;+ status: ActionTaskStatus;+ notes: JSONContent;+ canEditNotes: boolean;+ onNotesChange?: (value: JSONContent) => void;+ onUploadImage?: (file: File) => Promise<string>;+ onStatusChange: (next: ActionTaskStatus) => void;+ assigneeTable: string;+ assigneeId: string;+ assignee?: string;+ // Slots for entity-specific bits: statusBadge (left of assignee), headerExtras+ // (left of the collapse chevron — e.g. Linear/Jira or a delete button), and+ // footerExtras (right of the assignee — e.g. due date / processes / supplier).+ statusBadge?: ReactNode;+ headerExtras?: ReactNode;+ footerExtras?: ReactNode;+ isDisabled?: boolean;+ showDragHandle?: boolean;+ dragControls?: DragControls;+}) {+ const { t } = useLingui();+ const disclosure = useDisclosure({ defaultIsOpen: true });+ const statusAction = actionTaskStatusActions[status];+ const isComplete = status === "Completed" || status === "Skipped";++ return (+ <div className="rounded-lg border w-full flex flex-col bg-card">+ <div className="flex w-full justify-between px-4 py-2 items-center">+ <div className="flex flex-col flex-1">+ <span+ className={cn(+ "text-base font-semibold tracking-tight",+ isComplete && "line-through text-muted-foreground"+ )}+ >+ {title}+ </span>+ </div>+ <div className="flex items-center gap-1">+ {showDragHandle && !isDisabled && dragControls && (+ <button+ type="button"+ className="cursor-grab active:cursor-grabbing text-muted-foreground hover:text-foreground transition-colors p-1"+ onPointerDown={(e) => dragControls.start(e)}+ >+ <LuGripVertical size={16} />+ </button>+ )}+ {headerExtras}+ <IconButton+ icon={<LuChevronRight />}+ variant="ghost"+ onClick={disclosure.onToggle}+ aria-label={t`Open task details`}+ className={cn(disclosure.isOpen && "rotate-90")}+ />+ </div>+ </div>++ {disclosure.isOpen && (+ <div className="px-4 py-2 rounded">+ {canEditNotes ? (+ <Editor+ className="w-full min-h-[100px]"+ initialValue={notes}+ onUpload={onUploadImage}+ onChange={(value) => onNotesChange?.(value)}+ />+ ) : (+ <div+ className="prose dark:prose-invert"+ dangerouslySetInnerHTML={{ __html: generateHTML(notes) }}+ />+ )}+ </div>+ )}++ <div className="bg-muted/30 border-t px-4 py-2 flex justify-between w-full">+ <HStack>+ {statusBadge}+ <Assignee+ table={assigneeTable}+ id={assigneeId}+ size="sm"+ value={assignee}+ disabled={isDisabled}+ />+ {footerExtras}+ </HStack>+ <HStack>+ <Button+ isDisabled={isDisabled}+ leftIcon={statusAction.icon}+ variant="secondary"+ size="sm"+ onClick={() => onStatusChange(statusAction.next)}+ >+ {statusAction.action}+ </Button>+ </HStack>+ </div>+ </div>+ );+}diff --git a/apps/erp/app/components/ActionTasks/ActionTaskList.tsx b/apps/erp/app/components/ActionTasks/ActionTaskList.tsxnew file mode 100644index 0000000000..3eb31e614c--- /dev/null+++ b/apps/erp/app/components/ActionTasks/ActionTaskList.tsx@@ -0,0 +1,152 @@+import {+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ HStack,+ useDebounce,+ VStack+} from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import type { DragControls } from "framer-motion";+import { Reorder, useDragControls } from "framer-motion";+import { type ReactNode, useEffect, useState } from "react";+import { useFetcher } from "react-router";+import type { ListItem } from "~/types";+import { ActionTaskAddModal } from "./ActionTaskAddModal";+import type { ActionTaskStatus } from "./ActionTaskCard";+import { ActionTaskProgress } from "./ActionTaskProgress";++type ActionTaskRow = {+ id: string;+ sortOrder: number | null;+ status: ActionTaskStatus;+};++// The shared action-task list shell used by Quality issues and Change Orders:+// a collapsible card with a progress header, a drag-to-reorder list, and the+// "Add Actions" template picker. Entity specifics — how a row renders and where+// reorder/add post — are injected, so both surfaces share one implementation.+export function ActionTaskList<T extends ActionTaskRow>({+ tasks,+ renderItem,+ reorderAction,+ templates,+ onAdd,+ isAddSubmitting = false,+ addEmptyMessage,+ isDisabled = false,+ title+}: {+ tasks: T[];+ renderItem: (task: T, dragControls: DragControls) => ReactNode;+ reorderAction: string;+ // Add-from-template is opt-in: pass `onAdd` (and its templates) to show the+ // "Add Actions" picker. Omit it — as Change Orders do — and there's no add+ // affordance at all; the list is seeded elsewhere.+ templates?: ListItem[];+ onAdd?: (selectedIds: string[]) => void;+ isAddSubmitting?: boolean;+ addEmptyMessage?: string;+ isDisabled?: boolean;+ title?: ReactNode;+}) {+ const orderFetcher = useFetcher<{ success: boolean }>();++ const [sortOrder, setSortOrder] = useState<string[]>(() =>+ [...tasks]+ .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))+ .map((t) => t.id)+ );++ useEffect(() => {+ setSortOrder(+ [...tasks]+ .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))+ .map((t) => t.id)+ );+ }, [tasks]);++ const updateSortOrder = useDebounce(+ (updates: Record<string, number>) => {+ const formData = new FormData();+ formData.append("updates", JSON.stringify(updates));+ orderFetcher.submit(formData, { method: "post", action: reorderAction });+ },+ 1000,+ true+ );++ const onReorder = (newOrder: string[]) => {+ if (isDisabled) return;+ const updates: Record<string, number> = {};+ newOrder.forEach((id, index) => {+ updates[id] = index + 1;+ });+ setSortOrder(newOrder);+ updateSortOrder(updates);+ };++ return (+ <Card className="w-full" isCollapsible>+ <HStack className="justify-between w-full">+ <CardHeader>+ <CardTitle>{title ?? <Trans>Actions</Trans>}</CardTitle>+ </CardHeader>+ {tasks.length > 0 && <ActionTaskProgress tasks={tasks} />}+ </HStack>+ <CardContent>+ <VStack spacing={3}>+ {tasks.length > 0 && (+ <Reorder.Group+ axis="y"+ values={sortOrder}+ onReorder={onReorder}+ className="w-full space-y-3"+ >+ {sortOrder.map((id) => {+ const task = tasks.find((t) => t.id === id);+ if (!task) return null;+ return (+ <ReorderableItem+ key={id}+ task={task}+ renderItem={renderItem}+ />+ );+ })}+ </Reorder.Group>+ )}++ {!isDisabled && onAdd && (+ <ActionTaskAddModal+ templates={templates ?? []}+ onAdd={onAdd}+ isSubmitting={isAddSubmitting}+ emptyMessage={addEmptyMessage}+ />+ )}+ </VStack>+ </CardContent>+ </Card>+ );+}++function ReorderableItem<T extends ActionTaskRow>({+ task,+ renderItem+}: {+ task: T;+ renderItem: (task: T, dragControls: DragControls) => ReactNode;+}) {+ const dragControls = useDragControls();+ return (+ <Reorder.Item+ value={task.id}+ dragListener={false}+ dragControls={dragControls}+ >+ {renderItem(task, dragControls)}+ </Reorder.Item>+ );+}diff --git a/apps/erp/app/components/ActionTasks/ActionTaskProgress.tsx b/apps/erp/app/components/ActionTasks/ActionTaskProgress.tsxnew file mode 100644index 0000000000..465a0b1758--- /dev/null+++ b/apps/erp/app/components/ActionTasks/ActionTaskProgress.tsx@@ -0,0 +1,32 @@+import { BarProgress, cn } from "@carbon/react";+import type { ActionTaskStatus } from "./ActionTaskCard";++// Completed/skipped progress bar for an action-task list — shared by Quality+// issues and Change Orders.+export function ActionTaskProgress({+ tasks,+ className+}: {+ tasks: { status: ActionTaskStatus }[];+ className?: string;+}) {+ const done = tasks.filter(+ (task) => task.status === "Completed" || task.status === "Skipped"+ ).length;+ const progress = tasks.length > 0 ? (done / tasks.length) * 100 : 0;++ return (+ <div+ className={cn(+ "flex flex-col items-end gap-2 py-3 pr-14 w-[120px]",+ className+ )}+ >+ <BarProgress+ gradient+ progress={progress}+ value={`${done}/${tasks.length}`}+ />+ </div>+ );+}diff --git a/apps/erp/app/components/ActionTasks/ActionTaskStatusButton.tsx b/apps/erp/app/components/ActionTasks/ActionTaskStatusButton.tsxnew file mode 100644index 0000000000..870be48afc--- /dev/null+++ b/apps/erp/app/components/ActionTasks/ActionTaskStatusButton.tsx@@ -0,0 +1,65 @@+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuIcon,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuTrigger,+ IconButton+} from "@carbon/react";+import { useLingui } from "@lingui/react/macro";+import { IssueTaskStatusIcon } from "~/components/Icons";+import {+ type ActionTaskStatus,+ actionTaskStatusActions+} from "./ActionTaskCard";++const statuses = Object.keys(actionTaskStatusActions) as ActionTaskStatus[];++// Icon-only status control for an action-task card: the current status as an+// icon (with tooltip), opening a dropdown to jump to any status. Shared by+// Quality issues and Change Orders so both read identically — and it renders an+// icon, not the status word, so there's no text to truncate in the card footer.+export function ActionTaskStatusButton({+ status,+ onChange,+ isDisabled,+ className+}: {+ status: ActionTaskStatus;+ onChange: (next: ActionTaskStatus) => void;+ isDisabled?: boolean;+ className?: string;+}) {+ const { t } = useLingui();++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ size="sm"+ variant="ghost"+ className={className}+ aria-label={t`Change status`}+ icon={<IssueTaskStatusIcon status={status} />}+ isDisabled={isDisabled}+ />+ </DropdownMenuTrigger>+ {!isDisabled && (+ <DropdownMenuContent align="start">+ <DropdownMenuRadioGroup+ value={status}+ onValueChange={(next) => onChange(next as ActionTaskStatus)}+ >+ {statuses.map((s) => (+ <DropdownMenuRadioItem key={s} value={s}>+ <DropdownMenuIcon icon={<IssueTaskStatusIcon status={s} />} />+ <span>{s}</span>+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ )}+ </DropdownMenu>+ );+}diff --git a/apps/erp/app/components/Form/Item.tsx b/apps/erp/app/components/Form/Item.tsxindex fa4a71c324..1055dc096f 100644--- a/apps/erp/app/components/Form/Item.tsx+++ b/apps/erp/app/components/Form/Item.tsx@@ -38,6 +38,7 @@ import ToolForm from "~/modules/items/ui/Tools/ToolForm";import type { ItemType, MethodItemType } from "~/modules/shared";import { itemType, methodItemType } from "~/modules/shared";import { useItems } from "~/stores";+import { latestRevisionByReadableId } from "~/stores/items";import { path } from "~/utils/path";import { MethodItemTypeIcon } from "../Icons";import { ItemLifecycleBadge } from "../ItemLifecycleBadge";@@ -48,6 +49,10 @@ type ItemSelectProps = Omit<ComboboxProps, "options" | "type" | "inline"> & {isReadOnly?: boolean;blacklist?: string[];includeInactive?: boolean;+ // Collapse options to a single row per part (the latest revision), matching the+ // parts/materials list views. Off by default so pickers that legitimately need a+ // specific revision (BOM, sales/job lines) keep every revision.+ latestRevisionOnly?: boolean;inline?: boolean;isConfigured?: boolean;locationId?: string;@@ -114,51 +119,55 @@ const Item = ({const [items] = useItems();const options = useMemo(() => {- let results = items- .filter((item) => {- // Filter by type- // @ts-expect-error- if (validItemTypes && !validItemTypes.includes(item.type)) return false;+ let filtered = items.filter((item) => {+ // Filter by type+ // @ts-expect-error+ if (validItemTypes && !validItemTypes.includes(item.type)) return false;- if (type !== "Item" && type !== item.type) return false;+ if (type !== "Item" && type !== item.type) return false;- // Filter by active status- // Filter by active status- if (!props.includeInactive && !item.active) return false;+ // Filter by active status+ if (!props.includeInactive && !item.active) return false;- // Filter by replenishment system- if (props.replenishmentSystem) {- const systemMatches =- item.replenishmentSystem === props.replenishmentSystem ||- item.replenishmentSystem === "Buy and Make" ||- props.replenishmentSystem === item.replenishmentSystem;+ // Filter by replenishment system+ if (props.replenishmentSystem) {+ const systemMatches =+ item.replenishmentSystem === props.replenishmentSystem ||+ item.replenishmentSystem === "Buy and Make" ||+ props.replenishmentSystem === item.replenishmentSystem;- if (!systemMatches) return false;- }+ if (!systemMatches) return false;+ }++ return true;+ });- return true;- })- .map((item) => {- const scopedQuantity = props.locationId- ? item.quantityByLocation?.[props.locationId]- : item.quantityOnHand;- return {- value: item.id,- label: item.supersessionMode ? (- <span className="flex items-center gap-1.5">- {item.readableIdWithRevision}- <ItemLifecycleBadge mode={item.supersessionMode} />- </span>- ) : (- item.readableIdWithRevision- ),- helper: item.name,- helperRight:- scopedQuantity !== undefined- ? `${scopedQuantity} ${item.unitOfMeasureCode}`- : undefined- };- });+ // Collapse to a single current revision per part.+ if (props.latestRevisionOnly) {+ filtered = latestRevisionByReadableId(filtered);+ }++ let results = filtered.map((item) => {+ const scopedQuantity = props.locationId+ ? item.quantityByLocation?.[props.locationId]+ : item.quantityOnHand;+ return {+ value: item.id,+ label: item.supersessionMode ? (+ <span className="flex items-center gap-1.5">+ {item.readableIdWithRevision}+ <ItemLifecycleBadge mode={item.supersessionMode} />+ </span>+ ) : (+ item.readableIdWithRevision+ ),+ helper: item.name,+ helperRight:+ scopedQuantity !== undefined+ ? `${scopedQuantity} ${item.unitOfMeasureCode}`+ : undefined+ };+ });if (props.whitelist) {results = results.filter((item) => props.whitelist?.includes(item.value));@@ -173,6 +182,7 @@ const Item = ({items,props?.includeInactive,props.blacklist,+ props.latestRevisionOnly,props.locationId,props.replenishmentSystem,props.whitelist,diff --git a/apps/erp/app/components/Form/Users.tsx b/apps/erp/app/components/Form/Users.tsxindex 39ea5b55fe..b37adf1bc5 100644--- a/apps/erp/app/components/Form/Users.tsx+++ b/apps/erp/app/components/Form/Users.tsx@@ -44,7 +44,11 @@ const Users = ({setSelections(verbose? items.map((item) =>- "users" in item ? `group_${item.id}` : `user_${item.id}`+ // Groups load without members, so the object has no `users` key at+ // runtime — discriminate on a field only groups carry.+ "isEmployeeTypeGroup" in item+ ? `group_${item.id}`+ : `user_${item.id}`): items.map((item) => item.id));diff --git a/apps/erp/app/components/Hyperlink.tsx b/apps/erp/app/components/Hyperlink.tsxindex 6dbbf375ec..44b3507467 100644--- a/apps/erp/app/components/Hyperlink.tsx+++ b/apps/erp/app/components/Hyperlink.tsx@@ -25,8 +25,13 @@ const Hyperlink = ({<ButtonrightIcon={<LuPanelRight />}variant="secondary"- className="flex-shrink-0 opacity-0 transition-opacity duration-200 group-hover/hyperlink:opacity-100 no-underline"+ // pointer-events-none so clicks fall through to the anchor: a plain+ // click navigates in-tab, a Cmd/Ctrl (or middle) click opens a new tab.+ // A real <button> here would otherwise swallow the anchor's native+ // modifier-click behavior and always open in the same tab.+ className="flex-shrink-0 opacity-0 transition-opacity duration-200 group-hover/hyperlink:opacity-100 no-underline pointer-events-none"size="sm"+ tabIndex={-1}>Open</Button>diff --git a/apps/erp/app/components/ItemThumnailUpload.tsx b/apps/erp/app/components/ItemThumnailUpload.tsxindex 48302ed498..498a64014d 100644--- a/apps/erp/app/components/ItemThumnailUpload.tsx+++ b/apps/erp/app/components/ItemThumnailUpload.tsx@@ -12,11 +12,13 @@ const logger = getLogger("erp", "itemthumnailupload");export function ItemThumbnailUpload({path,itemId,- modelId+ modelId,+ isReadOnly = false}: {path?: string | null;itemId: string;modelId?: string | null;+ isReadOnly?: boolean;}) {const { t } = useLingui();const { company } = useUser();@@ -171,27 +173,29 @@ export function ItemThumbnailUpload({</span></div>)}- <HStack className="absolute bottom-2 right-2">- {thumbnailPath && (- <Button+ {!isReadOnly && (+ <HStack className="absolute bottom-2 right-2">+ {thumbnailPath && (+ <Button+ variant="secondary"+ className="bg-card opacity-100"+ size="sm"+ onClick={onFileRemove}+ >+ <Trans>Remove</Trans>+ </Button>+ )}+ <FileUpload+ accept="image/*"variant="secondary"- className="bg-card opacity-100"size="sm"- onClick={onFileRemove}+ className="bg-card opacity-100"+ onChange={onFileChange}>- <Trans>Remove</Trans>- </Button>- )}- <FileUpload- accept="image/*"- variant="secondary"- size="sm"- className="bg-card opacity-100"- onChange={onFileChange}- >- <Trans>Upload</Trans>- </FileUpload>- </HStack>+ <Trans>Upload</Trans>+ </FileUpload>+ </HStack>+ )}</div>);}diff --git a/apps/erp/app/components/New.tsx b/apps/erp/app/components/New.tsxindex 340c5a8fe5..1d8b36b371 100644--- a/apps/erp/app/components/New.tsx+++ b/apps/erp/app/components/New.tsx@@ -39,7 +39,7 @@ const New = ({ label, to, variant = "primary" }: NewProps) => {variant={variant}ref={buttonRef}>- <Link to={to} prefetch="intent">+ <Link to={to}>{translatedLabel ? `${t`Add`} ${translatedLabel}` : t`Add`}</Link></Button>diff --git a/apps/erp/app/components/RealtimeDataProvider.tsx b/apps/erp/app/components/RealtimeDataProvider.tsxindex a970cb596e..834ddd8aed 100644--- a/apps/erp/app/components/RealtimeDataProvider.tsx+++ b/apps/erp/app/components/RealtimeDataProvider.tsx@@ -124,6 +124,8 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {await Promise.all([fetchAllFromTable<{id: string;+ readableId: string;+ revision: string;readableIdWithRevision: string;unitOfMeasureCode: string;name: string;@@ -134,7 +136,7 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {}>(carbon,"item",- "id, readableIdWithRevision, unitOfMeasureCode, name, type, replenishmentSystem, active, itemTrackingType",+ "id, readableId, revision, readableIdWithRevision, unitOfMeasureCode, name, type, replenishmentSystem, active, itemTrackingType",(query) =>query.eq("companyId", companyId)@@ -261,6 +263,8 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {{id: inserted.id,name: inserted.name,+ readableId: inserted.readableId,+ revision: inserted.revision,readableIdWithRevision: inserted.readableIdWithRevision,description: inserted.description,replenishmentSystem: inserted.replenishmentSystem,@@ -285,6 +289,8 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {if (i.id === updated.id) {return {...i,+ readableId: updated.readableId,+ revision: updated.revision,readableIdWithRevision:updated.readableIdWithRevision,name: updated.name,diff --git a/apps/erp/app/components/Table/Table.tsx b/apps/erp/app/components/Table/Table.tsxindex fbd0237139..83aef1919b 100644--- a/apps/erp/app/components/Table/Table.tsx+++ b/apps/erp/app/components/Table/Table.tsx@@ -72,6 +72,7 @@ import type {EditableTableCellComponent,Position} from "~/components/Editable";+import { useUrlParams } from "~/hooks";import { useSavedViews } from "~/hooks/useSavedViews";import type { fieldMappings } from "~/modules/shared";import {@@ -942,11 +943,22 @@ const Table = <T extends object>({};const navigation = useNavigation();+ const [params] = useUrlParams();const { hasFilters, clearFilters } = useFilters();const isLoading = useSpinDelay(navigation.state === "loading", {delay: 300});+ // Genuinely-empty table: no rows and nothing narrowing them+ // (filters/sorts/search). Single source of truth — passed to TableHeader so+ // the top toolbar and the bottom pagination footer hide together, leaving only+ // the title bar + primary action.+ const isTableEmpty =+ data.length === 0 &&+ !hasFilters &&+ params.getAll("sort").filter(Boolean).length === 0 &&+ !params.get("search")?.trim();+return (<VStackkey={view ?? tableName ?? ""}@@ -969,6 +981,7 @@ const Table = <T extends object>({data={data}editMode={editMode}filters={filters}+ isEmpty={isTableEmpty}importCSV={importCSV}pagination={pagination}primaryAction={primaryAction}@@ -1313,7 +1326,7 @@ const Table = <T extends object>({)}</div></div>- {withPagination && <Pagination {...pagination} />}+ {withPagination && !isTableEmpty && <Pagination {...pagination} />}</VStack>);};diff --git a/apps/erp/app/components/Table/components/TableHeader.tsx b/apps/erp/app/components/Table/components/TableHeader.tsxindex e9e8b63667..19611b4dd0 100644--- a/apps/erp/app/components/Table/components/TableHeader.tsx+++ b/apps/erp/app/components/Table/components/TableHeader.tsx@@ -71,6 +71,9 @@ type HeaderProps<T> = {data: object[];editMode: boolean;filters: ColumnFilter[];+ // True when the table has no rows and no active filter/sort/search — hides the+ // toolbar row. Computed once by Table (single source) and passed down.+ isEmpty: boolean;importCSV?: {table: keyof typeof fieldMappings;label: string;@@ -105,6 +108,7 @@ const TableHeader = <T extends object>({data,editMode,filters,+ isEmpty,importCSV,primaryAction,pagination,@@ -281,106 +285,112 @@ const TableHeader = <T extends object>({</HStack>))}- <HStack- className={cn(- compact- ? "px-4 py-2 justify-between bg-card border-b border-border w-full"- : "px-4 md:px-0 justify-between bg-card w-full"- )}- >- <HStack>- {withSelectableRows &&- selectedRows.length > 0 &&- typeof renderActions === "function" && (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- className="pl-2 pr-1"- leftIcon={<LuCheck />}- variant="secondary"- >- <Badge variant="secondary">- <span>{selectedRows.length}</span>- </Badge>- </Button>- </DropdownMenuTrigger>- {renderActions(selectedRows)}- </DropdownMenu>- )}- {withSearch && (- <SearchFilter param="search" size="sm" placeholder={t`Search`} />+ {!isEmpty && (+ <HStack+ className={cn(+ compact+ ? "px-4 py-2 justify-between bg-card border-b border-border w-full"+ : "px-4 md:px-0 justify-between bg-card w-full")}- {!!filters?.length && <Filter filters={filters} />}- </HStack>- <HStack>- {sort === undefined ? <Sort sortKeyToLabel={sortKeyToLabel} /> : sort}+ >+ <HStack>+ {withSelectableRows &&+ selectedRows.length > 0 &&+ typeof renderActions === "function" && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ className="pl-2 pr-1"+ leftIcon={<LuCheck />}+ variant="secondary"+ >+ <Badge variant="secondary">+ <span>{selectedRows.length}</span>+ </Badge>+ </Button>+ </DropdownMenuTrigger>+ {renderActions(selectedRows)}+ </DropdownMenu>+ )}+ {withSearch && (+ <SearchFilter param="search" size="sm" placeholder={t`Search`} />+ )}+ {!!filters?.length && <Filter filters={filters} />}+ </HStack>+ <HStack>+ {sort === undefined ? (+ <Sort sortKeyToLabel={sortKeyToLabel} />+ ) : (+ sort+ )}- <Columns- columnOrder={columnOrder}- columns={columns}- setColumnOrder={setColumnOrder}- withSelectableRows={withSelectableRows}- />+ <Columns+ columnOrder={columnOrder}+ columns={columns}+ setColumnOrder={setColumnOrder}+ withSelectableRows={withSelectableRows}+ />- {canSaveView && (- <Tooltip>- <TooltipTrigger asChild>- <IconButton- aria-label={hasView ? t`Edit View` : t`Save View`}- variant={- savedViewDisclosure.isOpen || hasView ? "active" : "ghost"- }- icon={<LuLayers />}- onClick={savedViewDisclosure.onToggle}- />- </TooltipTrigger>- <TooltipContent>- <p>- {hasView ? (- <Trans>Edit View</Trans>- ) : (- <Trans>Save View</Trans>- )}- </p>- </TooltipContent>- </Tooltip>- )}+ {canSaveView && (+ <Tooltip>+ <TooltipTrigger asChild>+ <IconButton+ aria-label={hasView ? t`Edit View` : t`Save View`}+ variant={+ savedViewDisclosure.isOpen || hasView ? "active" : "ghost"+ }+ icon={<LuLayers />}+ onClick={savedViewDisclosure.onToggle}+ />+ </TooltipTrigger>+ <TooltipContent>+ <p>+ {hasView ? (+ <Trans>Edit View</Trans>+ ) : (+ <Trans>Save View</Trans>+ )}+ </p>+ </TooltipContent>+ </Tooltip>+ )}- <Download- data={data}- columnAccessors={columnAccessors}- exportValues={exportValues}- exportOnlyColumns={exportOnlyColumns}- columnOrder={columnOrder}- columnVisibility={columnVisibility}- />+ <Download+ data={data}+ columnAccessors={columnAccessors}+ exportValues={exportValues}+ exportOnlyColumns={exportOnlyColumns}+ columnOrder={columnOrder}+ columnVisibility={columnVisibility}+ />- {withPagination &&- (pagination.canNextPage || pagination.canPreviousPage) && (- <PaginationButtons {...pagination} condensed />- )}+ {withPagination &&+ (pagination.canNextPage || pagination.canPreviousPage) && (+ <PaginationButtons {...pagination} condensed />+ )}- {withInlineEditing &&- !forceEditMode &&- (editMode ? (- <Button- leftIcon={<LuLock />}- variant="secondary"- onClick={() => setEditMode(false)}- >- <Trans>Lock</Trans>- </Button>- ) : (- <Button- leftIcon={<LuFilePen />}- variant="secondary"- onClick={() => setEditMode(true)}- >- <Trans>Edit</Trans>- </Button>- ))}+ {withInlineEditing &&+ !forceEditMode &&+ (editMode ? (+ <Button+ leftIcon={<LuLock />}+ variant="secondary"+ onClick={() => setEditMode(false)}+ >+ <Trans>Lock</Trans>+ </Button>+ ) : (+ <Button+ leftIcon={<LuFilePen />}+ variant="secondary"+ onClick={() => setEditMode(true)}+ >+ <Trans>Edit</Trans>+ </Button>+ ))}+ </HStack></HStack>- </HStack>+ )}{currentFilters.length > 0 && (<HStackclassName={cn(diff --git a/apps/erp/app/modules/accounting/accounting.utils.ts b/apps/erp/app/modules/accounting/accounting.utils.tsindex b40dba007d..1f30b365b3 100644--- a/apps/erp/app/modules/accounting/accounting.utils.ts+++ b/apps/erp/app/modules/accounting/accounting.utils.ts@@ -363,7 +363,9 @@ export function addOneMonth(dateStr: string): Date {}export function getLastDayOfMonth(year: number, month: number): string {- const d = new Date(year, month + 1, 0);+ // Construct in UTC — a local-time Date serialized via toISOString() rolls+ // back a day in east-of-UTC (positive-offset) timezones (e.g. Feb 28 → Feb 27).+ const d = new Date(Date.UTC(year, month + 1, 0));return d.toISOString().split("T")[0];}diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/usePurchaseInvoiceAutoFill.ts b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/usePurchaseInvoiceAutoFill.tsindex d7f8e82949..f96ab165f5 100644--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/usePurchaseInvoiceAutoFill.ts+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/usePurchaseInvoiceAutoFill.ts@@ -113,6 +113,7 @@ export function usePurchaseInvoiceAutoFill(});const [supplierDetails, paymentTermData] = await Promise.all([+ // @ts-ignore Supabase composite key issuecarbon.from("supplier").select(diff --git a/apps/erp/app/modules/items/AGENTS.md b/apps/erp/app/modules/items/AGENTS.mdindex 04c930fafc..dc24d05abd 100644--- a/apps/erp/app/modules/items/AGENTS.md+++ b/apps/erp/app/modules/items/AGENTS.md@@ -78,9 +78,61 @@ import { getItem, upsertMaterial, getMakeMethods } from "~/modules/items";import { itemValidator, itemTrackingTypes, itemReplenishmentSystems } from "~/modules/items";```+## Change Orders (sub-area)++Engineering-change-order (ECO) workflow — a **top-to-bottom**, affected-items-first process: the user picks the parts/tools to change, sets a **per-item change type** (`Version` / `Revision` / `Replacement Part` / `New Part`), edits each item's BOM/BOP/attributes directly on a **real CO-owned Draft `makeMethod`** (via the normal embedded editors), and releases the CO — which activates each draft and propagates via supersession (except a net-new `New Part`, which has no predecessor). Lives **inside** the Items module (not a standalone module). Permission key is `parts` — loaders/actions use `requirePermissions(request, { view | update | delete | create: "parts" })`. Routes live under `apps/erp/app/routes/x+/items+/change-order+/` (detail + `affected`/`action` child mutations) and `x+/items+/change-orders+/` (list + Types config); URLs are `/x/items/change-order(s)…`. The **create form is the exception**: it lives at a top-level `apps/erp/app/routes/x+/change-order+/new.tsx` (URL `/x/change-order/new`, path helper `path.to.newChangeOrder`) so it renders with the app sidebar like `/x/part/new` and `/x/sales-order/new`, not nested under the Items module layout. Navigation is a "Change Orders" group in the Items sidebar (`useItemsSubmodules`). The `$id` **detail page uses the standard 3-pane detail convention** (`PanelProvider` + `ResizablePanels` from `~/components/Layout/Panels`, like sales-order / job): `ChangeOrderExplorer` (affected-items list) is the explorer, the content is a URL-addressed `Outlet`, and `ChangeOrderProperties` (header fields + affected assemblies + impact + release dialog, self-contained via `useRouteData`) is the properties panel. `$id.tsx` keeps `hideModuleSidebar: true` so the Items grouped sidebar doesn't stack next to the explorer. **The content follows the sales-order top-level-detail + line-route split:** `$id.details.tsx` is the **CO overview** (the `ChangeOrderStatusFlow` state bar + the two rich-text narrative fields `reasonForChange` / `description` via `ChangeOrderContent`, edited exactly like the quality issue's description — debounced direct `carbon.from("changeOrder").update` of tiptap JSON — plus the **CO-wide Changes rollup** (`ChangeOrderChanges` — every affected item's authoring diff, rendered between the description and the actions, same label+`ChangeOrderDiffViewer` list as the release dialog) and the action tasks via the shared `ActionTaskList` + "Add Actions" modal, reconciled through `$id.action`); each affected item is its own **line route** `$id.$affectedId.details.tsx` (URL `/x/items/change-order/$id/$affectedId/details`, `path.to.changeOrderAffectedItem`, rendering `AffectedItemDetail`), linked from the explorer (Revision / Replacement Part rows show "OLD → NEW" with the minted item's number, resolved from the items store; a **New Part shows a single id** — it is net-new, so its `newItemId` equals its `itemId` and there is no predecessor to arrow from, guarded by `newItemId !== itemId`). **Purchasable draft items get supplier-part management on the line**: a Revision/New Part line whose draft part is `Buy`/`Buy and Make` renders the embedded `SupplierParts` grid (data from `partData.supplierParts`, already in the `$id` loader); its create/edit drawers are child routes `$id.$affectedId.details.new.tsx` / `$id.$affectedId.details.$supplierPartId.tsx` (the `SupplierPartForm` posts to the PART purchasing actions — the part edit action returns `{ success }` instead of redirecting so embedded callers stay put), and delete is the action-only `$id.$affectedId.details.$supplierPartId.delete.tsx` (`path.to.changeOrderDeleteSupplierPart`). `$id._index` redirects to the overview; the header CO-id links back to it. Plain-text reason/description entered on the create form are converted to tiptap JSON on insert (`toRichText` in `x+/change-order+/new.tsx`).++**No staged mirror tables.** The v1 `changeOrderStaged*` tables were deleted. A CO's per-affected-item edits now live on a **real Draft `makeMethod`** whose `makeMethod.changeOrderId` points at the CO, edited via the embedded real `BillOfMaterial` / `BillOfProcess` editors on the CO detail page. The **same** draft method also surfaces on the affected item's own master page (`/x/part|tool/$itemId/details`): the item-detail loaders (`x+/part+/$itemId{.,}.tsx`, `x+/tool+/$itemId.details.tsx`) select it like any other method and **no longer exclude `changeOrderId`-stamped drafts**, so a revision/new-part item created by an open CO shows its BOM/BOP on the item master too — the two surfaces edit the same rows and stay in sync. (`Active` is still preferred as the default selection, so a `Version` CO's existing item keeps its live method by default.) `changeOrderId` is cleared at release.++Change-order code follows the one-service/models/server-per-module convention — it lives in the module's canonical files, NOT separate `changeOrder.*` files: `items.service.ts` holds header CRUD + guarded stage transition + Types config + affected-item CRUD + the CO-owned Draft orchestration (`createChangeOrderDraftMethod` / `addChangeOrderAffectedItem` / `updateChangeOrderAffectedItemChangeType` / cutover + `mintPlaceholderPart` + `getTopLevelProductsForItems` rollup) + the `diffMethod` pure engine + `getChangeOrderDiff` authoring-diff wrapper + item↔CO traceability reads (`findChangeOrdersForItem`, linked-NCR reverse) + freeform action-task CRUD; `items.server.ts` holds the server-only release path (`applyChangeOrder` orchestration + `releaseAffectedItem` + notifications); `items.models.ts` holds the validators + state machine + `changeOrderChangeTypes` + diff types. Non-server exports come through the Items barrel — import from `~/modules/items`; the server file is imported directly from `~/modules/items/items.server`.++**Approvals are not in V1.** No approval gate, reviewer/approval-task machinery, or toggle — stages advance freely; a CO reaches Done via `applyChangeOrder`. **Same-part parallel COs are now allowed** — the one-open-CO-per-part guard was dropped; `findOtherOpenChangeOrdersForItem` still exists but is advisory (no route/service enforces it).++### Key CO concepts++- **Stage flow** — `changeOrderStatus`: `Draft` → `Start` → `Engineering Complete` → `Implementation` → `Done`. Forward-only, one step (`changeOrderStatusTransitions` / `isAllowedChangeOrderTransition`). `isChangeOrderLocked(status)` is true only at `Done` (closed, read-only); `canEditChangeOrder` is its inverse. `changeOrderOpenStatuses` = every stage before Done. `Start`/`Implementation`/`Done` broadcast a team notification (`changeOrderBroadcastStages`).+- **Change type (capability matrix)** — `changeOrderAffectedItem.changeType` ∈ `Version | Revision | Replacement Part | New Part` (`changeOrderChangeTypes`) drives both the editable surface and the release action. Two axes: *is there a predecessor* and *same part number*. The **Add Affected Item** modal (`AffectedItemForm`) is **Parts-only**: the existing-item picker filters to `validItemTypes={["Part"]}` and the New Part mini-form always mints a Part — no Tool path in the UI (the service's `addChangeOrderAffectedItem`/`createChangeOrderDraftMethod` still technically accept Tools, but no route surfaces them). The modal's two branches (New Part vs existing-item) are separate `ValidatedForm`s that MUST carry distinct `key` props — same-slot same-type reconciliation would otherwise share one RVF store, hydrating controlled-field defaults only for whichever branch mounts first (New Part's replenishment/tracking Selects would then submit `""` → enum error).+ - `Version` — a new Draft method version on the **same item** (BoM/BoP edits); **no** supersession.+ - `Revision` — a new inactive revision item (same #, new rev) with **both BoM/BoP and attributes/docs**; the draft method is edited via the embedded `BillOfMaterial`/`BillOfProcess`, and the draft item's attributes + files via the embedded `PartProperties` (`embedded` variant) on the CO card; auto oldRev→newRev supersession at release. (BoM/BoP on a Revision was a client ask — a revision can carry a manufacturing change, not just a doc/spec change.) The **Add Affected Item** modal shows a `revision` text input for a Revision change so the user can name the revision (e.g. `A`); blank → `createChangeOrderDraftMethod` auto-computes the next revision via `getNextRevision`. (The optional `revision` threads validator → `$id.affected` route → `addChangeOrderAffectedItem` → `createChangeOrderDraftMethod`.)+ - `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 (`changeOrderNewPartValidator` — Part Number, Name, Replenishment System, Tracking Type; **no Part/Tool choice — always a Part**; `addChangeOrderAffectedItem`'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 `addChangeOrderAffectedItem` 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 (`createChangeOrderDraftMethod`, called by `addChangeOrderAffectedItem`)** — per change type: `Version` → `upsertMakeMethodVersion` + `copyMakeMethod` on the same item; `Revision` → `createRevision(active:false)`; `Replacement Part` → mint a new numeric `readableId` derived from the source (`getNextItemIdFromSource`) + `copyItem`; `New Part` → the item is minted by `addChangeOrderAffectedItem`'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** (`updateChangeOrderAffectedItemChangeType`), resetting edits — but a `New Part` cannot be switched to/from. Removing an affected item discards its draft. (`mintPlaceholderPart` exists but is **not wired** into any current path — the old G3 forward-reference claim is stale.)+- **Authoring diff (git-style end-state)** — `getChangeOrderDiff` + pure `diffMethod` (unit-tested in `changeOrder.diff.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 surfaces the draft's **supplier parts** as additions — the source item's suppliers are NOT copied to the draft, so `getChangeOrderDiff` (via `readDraftSupplierParts`) emits each `supplierPart` row as `added`; a `Version` shares the live item's suppliers and shows none. Rendered **read-only** by `ChangeOrderDiffViewer` — the single diff renderer, reused by the affected-item "Changes" card (`AffectedItemDetail`), the CO-wide `ChangeOrderChanges` rollup on the overview, and the release dialog (shown during authoring, not just at release).+- **Release confirmation** — `ChangeOrderReleaseMerge` (properties panel, at Implementation) is a plain review-then-confirm dialog: it shows each affected item's authoring diff (`getChangeOrderDiff`) 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 + `getChangeOrderReleaseDiff` / `reconcileDraftWithLive` were removed.+- **Release (`applyChangeOrder` → `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). `applyChangeOrder` 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.+- **Supersession propagation (no parent cascade)** — changing a component does **not** re-BOM its parents. Propagation is via supersession chains (`itemSupersession`): the auto affected→new cutover per Revision/Replacement Part affected item (a net-new New Part has no predecessor, so no supersession). **N→1 consolidation** ("3 parts become 1") is modeled as a parent-assembly `Version`/`Revision` change whose draft BOM removes the old component lines and adds a `New Part` line — surfaced by `diffMethod` as removed + added, **not** as supersessions. `item.changeOrderId` is the revision→CO back-link powering the "Created by CO-…" chip and part-side change history.+- **Impact panel** — read-only "where used" view: for each affected item, where it is referenced across the system (jobs, job materials, POs, receipts, sales orders, shipments, quotes, methods, NCRs, …), reusing the part detail page's `getPartUsedIn` data + the shared `UsedInItem` tree rows (`ImpactPanel` maps one where-used group per affected item; empty categories are dropped). Always shown in the properties panel. Loaded per affected item in the CO `$id` loader via `getPartUsedIn(client, affectedItem.itemId, companyId)` → `impactUsedIn`. (The old `getChangeOrderImpact` open-PO/jobs/sales table was removed.)+- **Linked NCR** — a CO may reference a non-conformance (`changeOrder.nonConformanceId`), cross-linked both ways with the Issue detail.+- **Change-orders list** (`ChangeOrdersTable`, `x+/items+/change-orders+/_index.tsx`) — reads the `changeOrders` view. Rows are **expandable** (`renderExpandedRow`/`canExpandRow`, storage-units spine style) to reveal each affected item (readableId + `ChangeTypeBadge` + OLD→NEW for Revision/Replacement Part; a New Part shows a single id — net-new, `newItemId === itemId`), and an **Item** filter (`isArray` static filter → `filter=itemIds:contains:<id>` → `.overlaps("itemIds", …)`) narrows COs to those affecting the selected items. The `itemIds` column is hidden by default (`defaultColumnVisibility`) — it still drives the filter and CSV export.++**Deferred (not yet built):** Tool affected items — the Add Affected Item modal is Parts-only, so there is no UI path to add a Tool (or edit Tool attributes) under a CO today, even though the service layer still accepts Tools.++### CO Safety++- MUST advance stages only through `updateChangeOrderStatus` — the single guarded writer (forward-only + compare-and-swap on `fromStatus`).+- MUST check `isChangeOrderLocked(status)` (Done) before editing header/content.+- MUST add affected items through `addChangeOrderAffectedItem` — it spins the CO-owned Draft method and writes the draft refs back; a bare `changeOrderAffectedItem` insert leaves the diff/release with no draft to activate.+- MUST use `applyChangeOrder` (the Implementation → Done "release") for the release lifecycle — never re-implement `activateMethodVersion`/`itemSupersession` inline. It orchestrates canonical helpers via edge-function calls, so it is **not** one transaction (G2); only the final flip to Done is a Kysely CAS. It is idempotent per affected item (a Draft whose `changeOrderId` is already cleared is skipped) and CO-wide (the closing CAS on `status='Implementation'`).+- `findChangeOrdersForItem` (in `items.service.ts`) is G6 — the single canonical "change orders referencing this item" query (spans affected items, BOM components on CO-owned draft methods, manual supersession predecessor/successor, and the `item.changeOrderId` reverse link on released revisions), scoped by `readableId`. Flat queries + JS union (no PostgREST embeds — TS2589 budget). Powers the part/tool detail history + open-CO alert. Do not add a second query for this.+- Never split CO code into separate `changeOrder.*` service/models/server files — it lives in the module's canonical `items.service.ts` / `items.models.ts` / `items.server.ts` (the one-service/models/server-per-module convention). Add CO functions there, alongside the rest of the items module.++### CO data model++| Table / Column | Purpose |+|---|---|+| `changeOrder` | Header: `changeOrderId`, `name`, `status`, `changeOrderTypeId`, `type` (legacy), `priority`, `nonConformanceId`, dates, `assignee`, `reasonForChange`/`description` |+| `changeOrders` (view) | List-view rollup of `changeOrder` + `itemIds` (text[] of affected item ids — powers the list's **Item** filter via `.overlaps`) + `affectedItems` (jsonb `{id,itemId,changeType,newItemId}[]` — powers the list's **expandable rows**). `getChangeOrders` reads this view (not the base table); the single-CO `getChangeOrder` still reads the base table, so `ChangeOrder` (list, nullable view cols) and the detail shape are distinct types (`ChangeOrderListItem` vs `ChangeOrder`) |+| `changeOrderType` | The "Category" lookup (configured like Issue Types) |+| `changeOrderAffectedItem` | The items the CO changes — user-selected first (or minted, for a net-new `New Part`). Carries `changeType` (`Version`/`Revision`/`Replacement Part`/`New Part`), the CO-owned Draft refs `draftMakeMethodId` + `baseMakeMethodId` (the source Active method; null for a net-new `New Part`), the revealed item `newItemId` (Revision/Replacement Part/New Part; also the release idempotency marker), and cutover config (`supersessionMode`, `discontinuationDate`, `successorEffectivityDate` — not used by `New Part`) |+| `makeMethod.changeOrderId` | Draft-method → CO link: a Draft `makeMethod` with a non-null `changeOrderId` is CO-owned. Shown/edited both in the CO workspace and on the affected item's own master page (item-detail loaders select it in sync — they do **not** exclude `changeOrderId` drafts); cleared at release |+| `changeOrderSupersession` | MANUAL different-part obsolescence declarations (`predecessorItemId` → `successorItemId`). **Table retained** (still read by `findChangeOrdersForItem`) but the create UI + CRUD were removed — no v2 path writes rows; the auto affected→new cutover covers same-part supersession |+| `changeOrderActionTask` | Freeform non-gating tasks (Actions) |+| `item.changeOrderId` | Revision/new-part → CO back-link, stamped at release; powers change history + revision-centric audit |+## Related Modules-- **purchasing** — supplier parts pricing; PO lines reference items; `conversionFactor` on `supplierPart`+- **purchasing** — supplier parts pricing; PO lines reference items; `conversionFactor` on `supplierPart`; CO impact panel reads open PO lines (`openPurchaseOrderLines`) for deleted parts- **inventory** — quantities tracked per item/location; tracking type drives receipt/picking behavior- **production** — jobs manufacture items; make methods copied to jobs via `get-method` edge function- **sales** — quote lines and sales order lines reference items; `itemUnitSalePrice` is base pricediff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.tsindex a56f7a7730..fef7d12604 100644--- a/apps/erp/app/modules/items/items.models.ts+++ b/apps/erp/app/modules/items/items.models.ts@@ -1,5 +1,7 @@+import type { PostgrestError } from "@supabase/supabase-js";import { z } from "zod";import { zfd } from "zod-form-data";+import { nonConformancePriority } from "../quality/quality.models";import {methodItemType,methodOperationOrders,@@ -59,6 +61,90 @@ export const itemReplenishmentSystems = ["Buy and Make"] as const;+// Maps an edit of ONE of the three interlocked item-level fields+// (replenishmentSystem, defaultMethodType, sourcingType) to the columns that must+// change together on the item, plus the values to mirror down to method materials.+// Pure — no DB access — so the interlock rule lives in ONE place, shared by the+// inline item-update route (x+/items+/update.tsx) and the change-order attributes+// editor. Keeping them in sync via a hand-copied mapping is exactly the drift this+// avoids.+export function deriveItemMethodUpdate(+ field: "replenishmentSystem" | "defaultMethodType" | "sourcingType",+ value: string+): {+ itemUpdate: {+ replenishmentSystem?: (typeof itemReplenishmentSystems)[number];+ defaultMethodType?: (typeof methodType)[number];+ sourcingType?: (typeof sourcingType)[number];+ };+ cascade: {+ sourcingType?: (typeof sourcingType)[number];+ methodType?: (typeof methodType)[number];+ };+} {+ switch (field) {+ case "replenishmentSystem": {+ const replenishmentSystem =+ value as (typeof itemReplenishmentSystems)[number];+ // Picking a concrete replenishment system pins the default method type.+ if (value !== "Buy and Make") {+ const defaultMethodType: (typeof methodType)[number] =+ value === "Make"+ ? "Make to Order"+ : value === "Buy"+ ? "Purchase to Order"+ : "Pull from Inventory";+ return {+ itemUpdate: { replenishmentSystem, defaultMethodType },+ cascade: { methodType: defaultMethodType }+ };+ }+ return { itemUpdate: { replenishmentSystem }, cascade: {} };+ }+ case "defaultMethodType": {+ const defaultMethodType = value as (typeof methodType)[number];+ // A concrete method type pins the replenishment system to match.+ if (value !== "Pull from Inventory") {+ const replenishmentSystem: (typeof itemReplenishmentSystems)[number] =+ value === "Make to Order"+ ? "Make"+ : value === "Purchase to Order"+ ? "Buy"+ : "Buy and Make";+ return {+ itemUpdate: { defaultMethodType, replenishmentSystem },+ cascade: { methodType: defaultMethodType }+ };+ }+ return {+ itemUpdate: { defaultMethodType },+ cascade: { methodType: defaultMethodType }+ };+ }+ case "sourcingType": {+ const sourcingTypeValue = value as (typeof sourcingType)[number];+ // Sourcing drives method type: Drop Ship → Purchase to Order, Ship from+ // Inventory → Pull from Inventory, Specified → leave method type as-is.+ const derivedMethodType: (typeof methodType)[number] | undefined =+ value === "Drop Ship"+ ? "Purchase to Order"+ : value === "Ship from Inventory"+ ? "Pull from Inventory"+ : undefined;+ return {+ itemUpdate: {+ sourcingType: sourcingTypeValue,+ ...(derivedMethodType ? { defaultMethodType: derivedMethodType } : {})+ },+ cascade: {+ sourcingType: sourcingTypeValue,+ methodType: derivedMethodType+ }+ };+ }+ }+}+export const shelfLifeModes = ["NotManaged","Fixed Duration",@@ -583,6 +669,34 @@ export const supersessionModes = ["No Stock"] as const;+export type SupersessionMode = (typeof supersessionModes)[number];++// Single source of truth for how each supersession mode is presented — the same+// color + description is reused everywhere the mode shows up (the item+// supersession picker, the item lifecycle badge, and the change-order cutover),+// so they never drift.+export const supersessionModeMeta: Record<+ SupersessionMode,+ { color: "green" | "blue" | "orange" | "red"; description: string }+> = {+ "Consume First": {+ color: "green",+ description: "Use remaining stock before switching to the successor"+ },+ "Prefer New": {+ color: "blue",+ description: "Default to the successor; old part as fallback only"+ },+ "Stock Only": {+ color: "orange",+ description: "Hold a minimum reserve for service; no production use"+ },+ "No Stock": {+ color: "red",+ description: "Fully obsolete — do not plan or stock"+ }+};+export const itemSupersessionValidator = z.object({itemId: z.string().min(1, { message: "Item ID is required" }),@@ -848,3 +962,300 @@ export const unitOfMeasureValidator = z.object({code: z.string().min(1, { message: "Code is required" }).max(10),name: z.string().min(1, { message: "Name is required" }).max(50)});++export const itemRevisionStatus = [+ "Design",+ "Prototype",+ "Production",+ "Obsolete"+] as const;++// companySettings.plmReleaseControl+export const plmReleaseControl = ["off", "warn", "enforce"] as const;++// Error shape returned by the change order service functions: either a real+// Supabase PostgrestError or a hand-built message (sequence/lookup failures that+// don't originate from a query). One alias so callers get a consistent contract.+export type ChangeOrderError = PostgrestError | { message: string };++// =============================================================================+// Change Orders — validators, enums, and the stage state machine.+//+// A sub-area of the Items module, modeled on Quality. The header evolves the+// existing `changeOrder` table. v2: a CO's per-affected-item edits live on a+// REAL CO-owned Draft make method (no staged mirror tables); the change type+// drives the release action. Validators here cover the header, affected items ++// change type, cutover, manual supersession, and freeform actions.+// =============================================================================++// changeOrder.type — the legacy category enum on the header. Retained (the+// column still exists); the primary "Category" is `changeOrderTypeId` (a row in+// the changeOrderType lookup, reseeded to Design improvement / Obsolescence /+// Cost reduction).+export const changeOrderType = [+ "Engineering",+ "Manufacturing",+ "Documentation"+] as const;++// V1 stage flow (forward, one step at a time). Broadcast on Start /+// Implementation / Done; silent on Draft / Engineering Complete. "Cancelled" is+// the off-ramp: a CO can be closed from any open stage and reopened to Draft.+export const changeOrderStatus = [+ "Draft",+ "Start",+ "Engineering Complete",+ "Implementation",+ "Done",+ "Cancelled"+] as const;++// The forward progress stages only (excludes the "Cancelled" off-ramp). Drives+// the read-only status-flow progress bar so a cancelled CO doesn't render as a+// sixth step.+export const changeOrderStageFlow: (typeof changeOrderStatus)[number][] = [+ "Draft",+ "Start",+ "Engineering Complete",+ "Implementation",+ "Done"+];++export const changeOrderTaskStatus = [+ "Pending",+ "In Progress",+ "Completed",+ "Skipped"+] as const;++// v2 per-affected-item change type. Drives the release action + which editing+// surface is shown. Two axes — is there a predecessor, and same part number?+// Version = new method version on the SAME item (BoM/BoP, no supersession)+// Revision = new revision item, same #, new rev (BoM/BoP + attrs, auto+// old-rev→new-rev supersession)+// Replacement Part = new P/N derived from + auto-superseding the affected part+// (BoM/BoP + attrs) — the 1:1 replacement, renamed from the old+// "New Part"+// New Part = net-new part, NO predecessor, NO supersession — introduced by+// the CO (Make or Buy). Used to introduce a part under change+// control, incl. the consolidated "1" in an N→1 assembly BOM+// change.+// BoM/BoP is editable on ANY change type for a manufactured (non-Buy) draft; only+// Version's extra editing scope differs (no attributes/docs/cutover surface).+export const changeOrderChangeTypes = [+ "Version",+ "Revision",+ "Replacement Part",+ "New Part"+] as const;+export type ChangeOrderChangeType = (typeof changeOrderChangeTypes)[number];++// changeOrder.priority reuses quality's nonConformancePriority DB enum.+export const changeOrderPriority = nonConformancePriority;++// -----------------------------------------------------------------------------+// Stage state machine (G8 — one place). Forward, single step, plus the Cancel /+// Reopen off-ramp. This map only encodes the allowed shape of a transition.+// IMPORTANT: the forward stage is always index 0 — the header's "Advance" action+// reads `transitions[status][0]`, so "Cancelled" must never be first.+// -----------------------------------------------------------------------------+export const changeOrderStatusTransitions: Record<+ (typeof changeOrderStatus)[number],+ (typeof changeOrderStatus)[number][]+> = {+ Draft: ["Start", "Cancelled"],+ Start: ["Engineering Complete", "Cancelled"],+ "Engineering Complete": ["Implementation", "Cancelled"],+ Implementation: ["Done", "Cancelled"],+ Done: [],+ // Reopen a closed CO back to Draft (fully editable). Done stays terminal.+ Cancelled: ["Draft"]+};++export function isAllowedChangeOrderTransition(+ from: string | null | undefined,+ to: string | null | undefined+): boolean {+ if (!from || !to || from === to) return false;+ const allowed =+ changeOrderStatusTransitions[from as (typeof changeOrderStatus)[number]];+ if (!allowed) return false;+ return (allowed as readonly string[]).includes(to);+}++// The stages that broadcast a team notification on entry.+export const changeOrderBroadcastStages: (typeof changeOrderStatus)[number][] =+ ["Start", "Implementation", "Done"];++// "Open" = every stage before the record is closed at Done. Used by the item+// open-CO alert and the single-open-CO guard.+export const changeOrderOpenStatuses: (typeof changeOrderStatus)[number][] = [+ "Draft",+ "Start",+ "Engineering Complete",+ "Implementation"+];++// Locked once closed — Done (released, part of the audit trail) or Cancelled+// (abandoned). Reopen a Cancelled CO to Draft to edit it again.+export function isChangeOrderLocked(+ status: string | null | undefined+): boolean {+ return status === "Done" || status === "Cancelled";+}++// Content (reason/description/products/BOM changes/actions) is editable until+// the CO is closed.+export function canEditChangeOrder(status: string | null | undefined): boolean {+ return !isChangeOrderLocked(status);+}++// -----------------------------------------------------------------------------+// Header+// -----------------------------------------------------------------------------+export const changeOrderValidator = z.object({+ id: zfd.text(z.string().optional()),+ changeOrderId: zfd.text(z.string().optional()),+ name: z.string().min(1, { message: "Name is required" }),+ reasonForChange: zfd.text(z.string().optional()),+ description: zfd.text(z.string().optional()),+ type: z.enum(changeOrderType).optional(),+ priority: z.enum(nonConformancePriority).optional(),+ changeOrderTypeId: zfd.text(z.string().optional()),+ nonConformanceId: zfd.text(z.string().optional()),+ openDate: z.string().min(1, { message: "Open date is required" }),+ dueDate: zfd.text(z.string().optional()),+ assignee: zfd.text(z.string().optional()),+ // Optional affected Parts/Tools to attach at create time — each is added as a+ // Version affected item (Buy items coerced to Revision service-side). More can+ // be added later on the CO detail. Only consumed by the create action.+ affectedItemIds: zfd.repeatableOfType(z.string()).optional()+});++// Status transition (used by the $id.status route). fromStatus drives a+// compare-and-swap so a stale/concurrent transition is rejected.+export const changeOrderStatusValidator = z.object({+ id: z.string().min(1, { message: "Id is required" }),+ fromStatus: z.enum(changeOrderStatus),+ status: z.enum(changeOrderStatus),+ assignee: zfd.text(z.string().optional())+});++// =============================================================================+// Top-to-bottom change content (v2) — affected items + per-item change type ++// cutover + manual supersession. The user selects affected parts first; each+// part's edits live on a REAL CO-owned Draft make method edited via the normal+// BillOfMaterial/BillOfProcess/PartProperties editors (no staged mirror tables).+// All validators are flat objects (no discriminated unions / heavy generics) to+// stay clear of TS2589 when threaded through @carbon/form's `validator()`.+// =============================================================================++// Affected item — the part the user selects to change. Adding one creates a+// CO-owned Draft make method per the change type (service side).+export const changeOrderAffectedItemValidator = z.object({+ id: zfd.text(z.string().optional()),+ changeOrderId: z.string().min(1, { message: "Change order is required" }),+ itemId: z.string().min(1, { message: "Item is required" }),+ changeType: z.enum(changeOrderChangeTypes).default("Version"),+ // Optional revision label for a Revision change (e.g. "A"). Blank → the next+ // revision is auto-computed server-side (createChangeOrderDraftMethod).+ revision: zfd.text(z.string().optional())+});++// Add-affected-item path for a net-new "New Part" (no existing itemId): the CO+// mints a brand-new inactive Part and adds it as a New Part affected item. Always+// a Part (no Part/Tool choice in the modal).+export const changeOrderNewPartValidator = z.object({+ changeOrderId: z.string().min(1, { message: "Change order is required" }),+ // The route branches on this raw FormData value; also seeds the change-type+ // Select so it reads "New Part" after the form remounts (see AffectedItemForm).+ changeType: z.enum(changeOrderChangeTypes).default("New Part"),+ readableId: z.string().min(1, { message: "Part number is required" }),+ name: z.string().min(1, { message: "Name is required" }),+ replenishmentSystem: z.enum(["Buy", "Make", "Buy and Make"]).default("Make"),+ itemTrackingType: z.enum(itemTrackingTypes).default("Inventory")+});++// Switch the change type on an existing affected item (rebuilds its CO-owned+// Draft make method for the new type — see updateChangeOrderAffectedItemChangeType).+export const changeOrderAffectedItemChangeTypeValidator = z.object({+ id: z.string().min(1, { message: "Id is required" }),+ changeType: z.enum(changeOrderChangeTypes)+});++// Per-item revision cutover config (Q3): existence of the oldRev→newRev+// supersession is automatic at release; the user only tunes mode + dates here.+export const changeOrderAffectedItemCutoverValidator = z.object({+ id: z.string().min(1, { message: "Id is required" }),+ supersessionMode: z.enum(supersessionModes),+ discontinuationDate: zfd.text(z.string().optional()),+ successorEffectivityDate: zfd.text(z.string().optional())+});++// Action task status transition (Start / Complete / Reopen). Actions are+// instantiated from templates (see changeOrderRequiredAction); there's no+// freeform-create validator.+export const changeOrderActionStatusValidator = z.object({+ id: z.string().min(1, { message: "Id is required" }),+ status: z.enum(changeOrderTaskStatus)+});++// Configurable default actions (changeOrderRequiredAction templates) — the+// per-company set a new change order is seeded from. Configured like Issue Types.+export const changeOrderRequiredActionValidator = z.object({+ id: zfd.text(z.string().optional()),+ name: z.string().min(1, { message: "Name is required" }),+ active: zfd.checkbox()+});++// -----------------------------------------------------------------------------+// Diff types (Q5 git-style) — one shape reused for the pre-release "tips"+// (staged-vs-live) and the post-release revision redline (oldRev-vs-newRev).+// -----------------------------------------------------------------------------+export type MethodDiffStatus = "added" | "removed" | "modified" | "unchanged";++export type MethodDiffEntry<T> = {+ status: MethodDiffStatus;+ before: T | null;+ after: T | null;+ // Field-level changes for a "modified" entry: { field: { before, after } }.+ changedFields?: Record<string, { before: unknown; after: unknown }>;+};++// One operation's child-level diff (steps / parameters / tools), each bucket+// classified added/removed/modified/unchanged. Defined here (not in+// changeOrder.diff.ts) so ChangeOrderItemDiff can carry the operation tree+// without a circular import; changeOrder.diff.ts re-exports these for its own+// callers.+export type OperationChildrenDiff = {+ steps: MethodDiffEntry<Record<string, unknown>>[];+ parameters: MethodDiffEntry<Record<string, unknown>>[];+ tools: MethodDiffEntry<Record<string, unknown>>[];+};++// An operation diff entry, optionally carrying its child-level diff. A superset+// of MethodDiffEntry, so consumers typed against the base entry keep working.+export type OperationDiffEntry = MethodDiffEntry<Record<string, unknown>> & {+ children?: OperationChildrenDiff;+};++export type ChangeOrderItemDiff = {+ affectedItemId: string;+ itemId: string;+ materials: MethodDiffEntry<Record<string, unknown>>[];+ // Operations carry the optional child (steps/parameters/tools) diff so the+ // read-only diff viewer can render the BOP as a tree.+ operations: OperationDiffEntry[];+ attributes: MethodDiffEntry<Record<string, unknown>>[];+ // Supplier parts on a Revision/New Part draft item. Drafts start with none+ // (the source's suppliers aren't copied), so these surface as `added` entries.+ supplierParts: MethodDiffEntry<Record<string, unknown>>[];+};++// -----------------------------------------------------------------------------+// Change Order Types (the "Category" lookup — configured like Issue Types)+// -----------------------------------------------------------------------------+export const changeOrderTypeValidator = z.object({+ id: zfd.text(z.string().optional()),+ name: z.string().min(1, { message: "Name is required" })+});diff --git a/apps/erp/app/modules/items/items.server.test.ts b/apps/erp/app/modules/items/items.server.test.tsnew file mode 100644index 0000000000..599c52a1a6--- /dev/null+++ b/apps/erp/app/modules/items/items.server.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it, vi } from "vitest";++// items.server's only runtime dependency; stubbed so the pure verdict logic+// can be tested without dragging in the app's full module graph.+vi.mock("~/modules/settings", () => ({ getCompanySettings: vi.fn() }));++// items.server pulls the items module graph (via ~/modules/items), which+// transitively loads @carbon/glossary — whose module-load-time Lingui `msg`+// macro isn't transformed under plain vitest and throws. Stub it; the verdict+// logic under test needs none of it.+vi.mock("@carbon/glossary", () => ({+ terms: {},+ getEntry: vi.fn(),+ lookupEntry: vi.fn(),+ hasEntry: vi.fn(),+ termSlug: vi.fn()+}));++const { getLockVerdict, LOCKED_REVISION_MESSAGE } = await import(+ "./items.server"+);++describe("getLockVerdict", () => {+ it("allows edits when the revision is not locked", () => {+ for (const releaseControl of ["off", "warn", "enforce"] as const) {+ expect(getLockVerdict({ isLocked: false, releaseControl })).toEqual({+ ok: true,+ warn: false+ });+ }+ });++ it("allows edits on a locked revision when release control is off", () => {+ expect(getLockVerdict({ isLocked: true, releaseControl: "off" })).toEqual({+ ok: true,+ warn: false+ });+ });++ it("allows edits with a warning on a locked revision when release control is warn", () => {+ expect(getLockVerdict({ isLocked: true, releaseControl: "warn" })).toEqual({+ ok: true,+ warn: true,+ message: LOCKED_REVISION_MESSAGE+ });+ });++ it("blocks edits on a locked revision when release control is enforce", () => {+ expect(+ getLockVerdict({ isLocked: true, releaseControl: "enforce" })+ ).toEqual({+ ok: false,+ warn: false,+ message: LOCKED_REVISION_MESSAGE+ });+ });+});diff --git a/apps/erp/app/modules/items/items.server.ts b/apps/erp/app/modules/items/items.server.tsnew file mode 100644index 0000000000..e54ae462cb--- /dev/null+++ b/apps/erp/app/modules/items/items.server.ts@@ -0,0 +1,465 @@+import type { Database } from "@carbon/database";+import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import { trigger } from "@carbon/jobs";+import { getLogger } from "@carbon/logger";+import { NotificationEvent } from "@carbon/notifications";+import type { SupabaseClient } from "@supabase/supabase-js";+import { activateMethodVersion, upsertItemSupersession } from "~/modules/items";+import { getCompanySettings } from "~/modules/settings";+import type { plmReleaseControl } from "./items.models";+import { supersessionModes } from "./items.models";++const logger = getLogger("erp", "change-orders");++// Release-lock helpers — gate BOM/BOP mutations on a released (Production)+// revision. A Production revision is the controlled, released make method;+// changes must flow through a change order. The pending revision an ECO creates+// is Design/Prototype (NOT Production), so it stays editable.++export type ReleaseControl = (typeof plmReleaseControl)[number];++type ItemRevisionStatus = Database["public"]["Enums"]["itemRevisionStatus"];++export const LOCKED_REVISION_MESSAGE =+ "This revision is released (Production). Open a change order to modify it.";++export type LockKind =+ | "item"+ | "makeMethod"+ | "material"+ | "operation"+ | "tool"+ | "parameter";++export type RevisionLock = {+ isLocked: boolean;+ releaseControl: ReleaseControl;+ revisionStatus: ItemRevisionStatus | null;+};++export type LockCheck =+ | { ok: true; warn: false }+ | { ok: true; warn: true; message: string }+ | { ok: false; warn: false; message: string };++export function getLockVerdict(lock: {+ isLocked: boolean;+ releaseControl: ReleaseControl;+}): LockCheck {+ if (!lock.isLocked || lock.releaseControl === "off") {+ return { ok: true, warn: false };+ }+ if (lock.releaseControl === "warn") {+ return { ok: true, warn: true, message: LOCKED_REVISION_MESSAGE };+ }+ return { ok: false, warn: false, message: LOCKED_REVISION_MESSAGE };+}++// Each kind resolves entity -> item.revisionStatus in a single nested PostgREST+// select instead of walking the FK chain with sequential single-row queries.+// Every base query is scoped by companyId (defense-in-depth; the id is a global+// UUID but tenant scoping is a golden rule). The lock is advisory — RLS ++// requirePermissions are the real boundary — so a null/unresolvable status+// leaves the gate open by design (see checkRevisionLock).+async function resolveRevisionStatus(+ client: SupabaseClient<Database>,+ kind: LockKind,+ id: string,+ companyId: string+): Promise<ItemRevisionStatus | null> {+ switch (kind) {+ case "item": {+ const item = await client+ .from("item")+ .select("revisionStatus")+ .eq("id", id)+ .eq("companyId", companyId)+ .maybeSingle();+ return item.data?.revisionStatus ?? null;+ }+ case "makeMethod": {+ const makeMethod = await client+ .from("makeMethod")+ .select("item(revisionStatus)")+ .eq("id", id)+ .eq("companyId", companyId)+ .maybeSingle();+ return makeMethod.data?.item?.revisionStatus ?? null;+ }+ case "material": {+ // methodMaterial has two FKs to makeMethod (makeMethodId and+ // materialMakeMethodId) — the parent method is methodMaterial_methodId_fkey+ const material = await client+ .from("methodMaterial")+ .select("makeMethod!methodMaterial_methodId_fkey(item(revisionStatus))")+ .eq("id", id)+ .eq("companyId", companyId)+ .maybeSingle();+ return material.data?.makeMethod?.item?.revisionStatus ?? null;+ }+ case "operation": {+ const operation = await client+ .from("methodOperation")+ .select("makeMethod(item(revisionStatus))")+ .eq("id", id)+ .eq("companyId", companyId)+ .maybeSingle();+ return operation.data?.makeMethod?.item?.revisionStatus ?? null;+ }+ case "tool": {+ const tool = await client+ .from("methodOperationTool")+ .select("methodOperation(makeMethod(item(revisionStatus)))")+ .eq("id", id)+ .eq("companyId", companyId)+ .maybeSingle();+ return (+ tool.data?.methodOperation?.makeMethod?.item?.revisionStatus ?? null+ );+ }+ case "parameter": {+ const parameter = await client+ .from("methodOperationParameter")+ .select("methodOperation(makeMethod(item(revisionStatus)))")+ .eq("id", id)+ .eq("companyId", companyId)+ .maybeSingle();+ return (+ parameter.data?.methodOperation?.makeMethod?.item?.revisionStatus ??+ null+ );+ }+ }+}++async function getReleaseControl(+ client: SupabaseClient<Database>,+ companyId: string+): Promise<ReleaseControl> {+ const settings = await getCompanySettings(client, companyId);+ return (settings.data?.plmReleaseControl ?? "enforce") as ReleaseControl;+}++// Read variant for loaders that need the raw lock state (revisionStatus ++// releaseControl) to drive read-only UI. A revision is locked ONLY when it is+// "Production".+export async function getRevisionLock(+ client: SupabaseClient<Database>,+ args: { itemId: string | null; companyId: string }+): Promise<RevisionLock> {+ const [revisionStatus, releaseControl] = await Promise.all([+ args.itemId+ ? resolveRevisionStatus(client, "item", args.itemId, args.companyId)+ : Promise.resolve(null),+ getReleaseControl(client, args.companyId)+ ]);++ return {+ isLocked: revisionStatus === "Production",+ releaseControl,+ revisionStatus+ };+}++// The single guard entry point for mutation routes: resolves the entity's+// parent item and returns the enforce/warn/off verdict. A missing/null id+// (cannot resolve) leaves the lock unlocked, so the gate is safely skipped.+export async function checkRevisionLock(+ client: SupabaseClient<Database>,+ args: { kind: LockKind; id: string | null | undefined; companyId: string }+): Promise<LockCheck> {+ const [revisionStatus, releaseControl] = await Promise.all([+ args.id+ ? resolveRevisionStatus(client, args.kind, args.id, args.companyId)+ : Promise.resolve(null),+ getReleaseControl(client, args.companyId)+ ]);++ return getLockVerdict({+ isLocked: revisionStatus === "Production",+ releaseControl+ });+}++// =============================================================================+// Change Orders — server-only helpers (imports @carbon/jobs).+// =============================================================================++// Maps a broadcast stage to its notification event. Only Start / Implementation+// / Done broadcast (PRD §3.1); Draft / Engineering Complete are silent, so+// callers simply don't invoke this for those stages.+export const changeOrderStageEvent: Record<string, NotificationEvent> = {+ Start: NotificationEvent.ChangeOrderStarted,+ Implementation: NotificationEvent.ChangeOrderImplementation,+ Done: NotificationEvent.ChangeOrderDone+};++// notifyChangeOrderTransition — broadcasts a stage transition to the whole+// company team (PRD §3.1 "Broadcast to team"). The recipient is the company+// employee group; the `notify` job expands it via the users_for_groups RPC.+// Best-effort: never throws into the caller's redirect path.+export async function notifyChangeOrderTransition(args: {+ event: NotificationEvent;+ changeOrderId: string;+ companyId: string;+ companyGroupId: string;+ userId: string;+}): Promise<void> {+ try {+ await trigger("notify", {+ event: args.event,+ companyId: args.companyId,+ documentId: args.changeOrderId,+ recipient: { type: "group", groupIds: [args.companyGroupId] },+ from: args.userId+ });+ } catch (e) {+ logger.error("Failed to trigger change order notification", { error: e });+ }+}++// =============================================================================+// applyChangeOrder — the top-to-bottom "release", run on the Implementation →+// Done transition (this function IS that transition). It materializes each+// affected item's CO-staged end-state onto a NEW inactive revision, activates+// it, then auto-writes the oldRev → newRev supersession (Q1/Q2/Q5).+//+// Atomicity (G2): createRevision + activateMethodVersion are edge-function+// (functions.invoke → get-method / convert) calls, so this CANNOT be one Kysely+// transaction. The apply is therefore an idempotent, CAS-guarded orchestration:+// - PER-AFFECTED-ITEM idempotency: each changeOrderAffectedItem gets its+// created revision id stamped into `newItemId` at the END of its processing.+// A re-run skips any affected item whose `newItemId` is already set, so a+// partial failure re-run resumes at the first unprocessed item instead of+// re-creating revisions.+// - CO-LEVEL idempotency: the final flip to 'Done' is a compare-and-swap on+// status='Implementation', so a re-run can't double-transition the CO; only+// the closing status flip is transactional.+// =============================================================================+export async function applyChangeOrder(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ args: {+ changeOrderId: string;+ userId: string;+ companyId: string;+ }+): Promise<{ data: { id: string } | null; error: { message: string } | null }> {+ const { changeOrderId, userId, companyId } = args;++ const co = await client+ .from("changeOrder")+ .select("id, status")+ .eq("id", changeOrderId)+ .eq("companyId", companyId)+ .single();+ if (co.error || !co.data) {+ return { data: null, error: { message: "Change order not found" } };+ }+ if (co.data.status !== "Implementation") {+ return {+ data: null,+ error: { message: "Change order must be at Implementation to apply" }+ };+ }++ // Load the affected items with change type + draft refs + cutover config.+ // v2: the draft make method already holds the edited BOM/BOP; release just+ // activates it (and reveals the new item for Revision/New Part). Idempotency+ // is per-item inside releaseAffectedItem (skip once the draft is no longer+ // CO-owned).+ const affectedItems = await client+ .from("changeOrderAffectedItem")+ .select(+ "id, itemId, changeType, draftMakeMethodId, baseMakeMethodId, newItemId, supersessionMode, discontinuationDate, successorEffectivityDate"+ )+ .eq("changeOrderId", changeOrderId)+ .eq("companyId", companyId)+ .order("sortOrder", { ascending: true })+ .order("createdAt", { ascending: true });+ if (affectedItems.error) {+ return { data: null, error: affectedItems.error };+ }++ // Release New Part (net-new) items first, so a parent assembly whose draft BOM+ // references a new part resolves to an already-active item when its own method+ // activates. Stable sort preserves the sortOrder/createdAt order within groups.+ const ordered = [...(affectedItems.data ?? [])].sort(+ (a, b) =>+ (a.changeType === "New Part" ? 0 : 1) -+ (b.changeType === "New Part" ? 0 : 1)+ );++ for (const affected of ordered) {+ const result = await releaseAffectedItem(client, {+ changeOrderId,+ companyId,+ userId,+ affected+ });+ if (result.error) return { data: null, error: result.error };+ }++ // Final compare-and-swap: Implementation → Done (the only transactional write).+ try {+ const updated = await db.transaction().execute(async (trx) => {+ const res = await trx+ .updateTable("changeOrder")+ .set({ status: "Done", updatedBy: userId })+ .where("id", "=", changeOrderId)+ .where("companyId", "=", companyId)+ .where("status", "=", "Implementation")+ .executeTakeFirst();+ return Number(res.numUpdatedRows);+ });+ if (updated === 0) {+ return {+ data: null,+ error: { message: "Change order has already been applied" }+ };+ }+ } catch (err) {+ return {+ data: null,+ error: { message: err instanceof Error ? err.message : "Apply failed" }+ };+ }++ return { data: { id: changeOrderId }, error: null };+}++// -----------------------------------------------------------------------------+// releaseAffectedItem (v2) — dispatch by change type. The CO-owned Draft make+// method already holds the edited BOM/BOP, so release just:+// Version → activate the Draft on the SAME item (prior Active →+// Archived); no new item, no supersession.+// Revision → activate the Draft + reveal the new revision item + auto+// oldRev→newRev supersession.+// Replacement Part → activate the Draft + reveal the new part + auto+// affected→new supersession.+// New Part → activate the Draft + reveal the net-new part; NO+// supersession (no predecessor).+// Idempotent: once the Draft's changeOrderId is cleared it counts as released.+// -----------------------------------------------------------------------------+async function releaseAffectedItem(+ client: SupabaseClient<Database>,+ input: {+ changeOrderId: string;+ companyId: string;+ userId: string;+ affected: {+ id: string;+ itemId: string;+ changeType: Database["public"]["Enums"]["changeOrderChangeType"];+ draftMakeMethodId: string | null;+ baseMakeMethodId: string | null;+ newItemId: string | null;+ supersessionMode: Database["public"]["Enums"]["supersessionMode"] | null;+ discontinuationDate: string | null;+ successorEffectivityDate: string | null;+ };+ }+): Promise<{ error: { message: string } | null }> {+ const { changeOrderId, companyId, userId, affected } = input;+ const { changeType, draftMakeMethodId, newItemId } = affected;+ const sourceItemId = affected.itemId;++ if (!draftMakeMethodId) {+ return { error: { message: "Affected item has no draft make method" } };+ }++ // Idempotency: a Draft still owned by this CO has not been released yet; once+ // released we clear changeOrderId, so a re-run skips it.+ const draft = await client+ .from("makeMethod")+ .select("changeOrderId")+ .eq("id", draftMakeMethodId)+ .eq("companyId", companyId)+ .maybeSingle();+ if (draft.error) return { error: draft.error };+ if (!draft.data || !draft.data.changeOrderId) {+ return { error: null };+ }++ // Activate the Draft method (Draft → Active; prior Active → Archived). A+ // Version simply appends a new Active version and archives the prior one — the+ // prior version's rows are preserved as method history, so there is nothing to+ // merge even if another CO released a newer version in the meantime.+ const activated = await activateMethodVersion(client, {+ id: draftMakeMethodId,+ companyId,+ userId+ });+ if (activated.error) {+ return { error: { message: "Failed to activate method" } };+ }++ // Reveal the new item for Revision / New Part (Version edits the same item).+ if (newItemId) {+ const reveal = await client+ .from("item")+ .update({+ active: true,+ changeOrderId,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ .eq("id", newItemId)+ .eq("companyId", companyId);+ if (reveal.error) return { error: reveal.error };+ }++ // Auto supersession: Revision (oldRev→newRev) / Replacement Part (affected→new).+ // Version edits the SAME item, and a net-new New Part has NO predecessor — so+ // neither writes a supersession (they still reveal their item above). This runs+ // BEFORE clearing the CO-ownership marker so a supersession failure leaves the+ // draft still owned by the CO (changeOrderId set) — the item is re-attempted on+ // retry instead of the CO silently completing without its required supersession.+ // Re-runs are safe: activate/reveal are idempotent and upsertItemSupersession is+ // an upsert.+ if (+ (changeType === "Revision" || changeType === "Replacement Part") &&+ newItemId+ ) {+ const sup = await upsertItemSupersession(client, {+ itemId: sourceItemId,+ successorItemId: newItemId,+ supersessionMode: normalizeSupersessionMode(affected.supersessionMode),+ // Empty per-item dates mean "effective immediately at release" — the+ // supersession redirect map treats a null successorEffectivityDate as+ // always-effective. Cutover timing is driven purely per affected item now.+ discontinuationDate: affected.discontinuationDate ?? undefined,+ successorEffectivityDate: affected.successorEffectivityDate ?? undefined,+ companyId,+ createdBy: userId,+ updatedBy: userId+ });+ if (sup.error) {+ logger.error("Failed to write revision supersession", {+ error: sup.error+ });+ return { error: sup.error };+ }+ }++ // Clear CO ownership on the Draft — the FINAL, idempotency-marking step. Once+ // cleared the draft is normal method history and a re-run skips this item.+ const clear = await client+ .from("makeMethod")+ .update({ changeOrderId: null })+ .eq("id", draftMakeMethodId)+ .eq("companyId", companyId);+ if (clear.error) return { error: clear.error };++ return { error: null };+}++// Coerce a possibly-null DB supersession mode to a valid enum member, defaulting+// to 'Consume First' (Q3 default) when unset/invalid.+function normalizeSupersessionMode(+ mode: string | null | undefined+): Database["public"]["Enums"]["supersessionMode"] {+ return (supersessionModes as readonly string[]).includes(mode ?? "")+ ? (mode as Database["public"]["Enums"]["supersessionMode"])+ : "Consume First";+}diff --git a/apps/erp/app/modules/items/items.service.test.ts b/apps/erp/app/modules/items/items.service.test.tsnew file mode 100644index 0000000000..d12120ffcd--- /dev/null+++ b/apps/erp/app/modules/items/items.service.test.ts@@ -0,0 +1,297 @@+import { describe, expect, it, vi } from "vitest";++// diffMethod now lives in items.service. Importing the real module drags in the+// items.service graph, which transitively loads @carbon/glossary — whose+// module-load-time Lingui `msg` macro isn't transformed under plain vitest and+// throws. The pure diffMethod under test needs none of it, so stub glossary; the+// diffMethod under test stays the genuine implementation.+vi.mock("@carbon/glossary", () => ({+ terms: {},+ getEntry: vi.fn(),+ lookupEntry: vi.fn(),+ hasEntry: vi.fn(),+ termSlug: vi.fn()+}));++const { diffMethod } = await import("./items.service");++// A minimal live methodMaterial row (only the fields diffMethod compares + id).+function baseMaterial(over: Record<string, unknown> = {}) {+ return {+ id: "mm_1",+ itemId: "P1",+ quantity: 2,+ order: 1,+ unitOfMeasureCode: "EA",+ methodType: "Buy",+ sourcingType: "Specified",+ ...over+ };+}++// A staged material pointing back at a live material via sourceMaterialId.+function stagedMaterial(over: Record<string, unknown> = {}) {+ return {+ id: "cosm_1",+ sourceMaterialId: "mm_1",+ itemId: "P1",+ quantity: 2,+ order: 1,+ unitOfMeasureCode: "EA",+ methodType: "Buy",+ sourcingType: "Specified",+ ...over+ };+}++function baseOperation(over: Record<string, unknown> = {}) {+ return {+ id: "mo_1",+ order: 1,+ operationOrder: "After Previous",+ description: "Cut",+ setupTime: 5,+ laborTime: 10,+ machineTime: 0,+ ...over+ };+}++function stagedOperation(over: Record<string, unknown> = {}) {+ return {+ id: "coso_1",+ sourceOperationId: "mo_1",+ order: 1,+ operationOrder: "After Previous",+ description: "Cut",+ setupTime: 5,+ laborTime: 10,+ machineTime: 0,+ ...over+ };+}++const EMPTY = {+ baseMaterials: [],+ targetMaterials: [],+ baseOperations: [],+ targetOperations: []+};++describe("diffMethod — materials", () => {+ it("classifies a staged line with no source pointer as added", () => {+ const { materials } = diffMethod({+ ...EMPTY,+ targetMaterials: [stagedMaterial({ sourceMaterialId: null })]+ });+ expect(materials).toHaveLength(1);+ expect(materials[0].status).toBe("added");+ expect(materials[0].before).toBeNull();+ expect(materials[0].after).not.toBeNull();+ });++ it("classifies a base line nothing points at as removed", () => {+ const { materials } = diffMethod({+ ...EMPTY,+ baseMaterials: [baseMaterial()]+ });+ expect(materials).toHaveLength(1);+ expect(materials[0].status).toBe("removed");+ expect(materials[0].before).not.toBeNull();+ expect(materials[0].after).toBeNull();+ });++ it("classifies a matched pair with a changed field as modified", () => {+ const { materials } = diffMethod({+ ...EMPTY,+ baseMaterials: [baseMaterial()],+ targetMaterials: [stagedMaterial({ quantity: 5 })]+ });+ expect(materials).toHaveLength(1);+ expect(materials[0].status).toBe("modified");+ expect(materials[0].changedFields).toEqual({+ quantity: { before: 2, after: 5 }+ });+ });++ it("classifies an identical matched pair as unchanged", () => {+ const { materials } = diffMethod({+ ...EMPTY,+ baseMaterials: [baseMaterial()],+ targetMaterials: [stagedMaterial()]+ });+ expect(materials).toHaveLength(1);+ expect(materials[0].status).toBe("unchanged");+ expect(materials[0].changedFields).toBeUndefined();+ });++ it("treats numeric-string vs number quantities as unchanged", () => {+ const { materials } = diffMethod({+ ...EMPTY,+ baseMaterials: [baseMaterial({ quantity: "2" })],+ targetMaterials: [stagedMaterial({ quantity: 2 })]+ });+ expect(materials[0].status).toBe("unchanged");+ });++ // N→1 consolidation: an assembly's draft BOM drops 3 components and adds one+ // new part. The diff must read as 3 removed + 1 added (no supersession) — the+ // shape the consolidation feature surfaces on the assembly's Changes card.+ it("consolidation: 3 base materials removed, 1 new part added", () => {+ const { materials } = diffMethod({+ ...EMPTY,+ baseMaterials: [+ baseMaterial({ id: "mm_1", itemId: "P1", order: 1 }),+ baseMaterial({ id: "mm_2", itemId: "P2", order: 2 }),+ baseMaterial({ id: "mm_3", itemId: "P3", order: 3 })+ ],+ targetMaterials: [+ stagedMaterial({+ id: "cosm_new",+ sourceMaterialId: null,+ itemId: "P_NEW",+ order: 1+ })+ ]+ });+ expect(materials.filter((m) => m.status === "removed")).toHaveLength(3);+ expect(materials.filter((m) => m.status === "added")).toHaveLength(1);+ expect(materials.filter((m) => m.status === "modified")).toHaveLength(0);+ expect(materials.find((m) => m.status === "added")?.after?.itemId).toBe(+ "P_NEW"+ );+ });+});++describe("diffMethod — operations", () => {+ it("classifies an added operation (null source)", () => {+ const { operations } = diffMethod({+ ...EMPTY,+ targetOperations: [stagedOperation({ sourceOperationId: null })]+ });+ expect(operations[0].status).toBe("added");+ });++ it("classifies a removed operation", () => {+ const { operations } = diffMethod({+ ...EMPTY,+ baseOperations: [baseOperation()]+ });+ expect(operations[0].status).toBe("removed");+ });++ it("classifies a modified operation and records the changed field", () => {+ const { operations } = diffMethod({+ ...EMPTY,+ baseOperations: [baseOperation()],+ targetOperations: [stagedOperation({ setupTime: 20 })]+ });+ expect(operations[0].status).toBe("modified");+ expect(operations[0].changedFields).toEqual({+ setupTime: { before: 5, after: 20 }+ });+ });++ it("classifies an unchanged operation", () => {+ const { operations } = diffMethod({+ ...EMPTY,+ baseOperations: [baseOperation()],+ targetOperations: [stagedOperation()]+ });+ expect(operations[0].status).toBe("unchanged");+ });+});++describe("diffMethod — operation children", () => {+ it("carries no children when child maps are omitted (backward compatible)", () => {+ const { operations } = diffMethod({+ ...EMPTY,+ baseOperations: [baseOperation()],+ targetOperations: [stagedOperation()]+ });+ expect(operations[0].children).toBeUndefined();+ });++ it("diffs steps/parameters/tools by sourceId per matched operation", () => {+ const { operations } = diffMethod({+ ...EMPTY,+ baseOperations: [baseOperation()],+ targetOperations: [stagedOperation()],+ baseOperationChildren: {+ // keyed by the LIVE operation id (mo_1)+ mo_1: {+ steps: [{ id: "mos_1", name: "Inspect", sortOrder: 1 }],+ parameters: [{ id: "mop_1", key: "speed", value: "100" }],+ tools: [{ id: "mot_1", toolId: "T1", quantity: 1 }]+ }+ },+ targetOperationChildren: {+ // keyed by the STAGED operation id (coso_1)+ coso_1: {+ steps: [+ // modified: sortOrder changed+ { id: "coss_1", sourceId: "mos_1", name: "Inspect", sortOrder: 2 }+ ],+ parameters: [+ // added: no sourceId+ { id: "cosp_1", sourceId: null, key: "feed", value: "5" }+ ],+ // tools: mot_1 nothing points at ⇒ removed+ tools: []+ }+ }+ });++ const children = operations[0].children!;+ expect(children.steps).toHaveLength(1);+ expect(children.steps[0].status).toBe("modified");+ expect(children.steps[0].changedFields).toEqual({+ sortOrder: { before: 1, after: 2 }+ });++ // base mop_1 dropped (removed) + staged cosp_1 with no sourceId (added)+ expect(children.parameters).toHaveLength(2);+ expect(children.parameters.map((e) => e.status).sort()).toEqual([+ "added",+ "removed"+ ]);++ expect(children.tools).toHaveLength(1);+ expect(children.tools[0].status).toBe("removed");+ });+});++describe("diffMethod — attributes", () => {+ it("reports one entry per changed attribute column", () => {+ const { attributes } = diffMethod({+ ...EMPTY,+ baseAttributes: { name: "Widget", description: "old" },+ targetAttributes: { name: "Widget", description: "new" }+ });+ expect(attributes).toHaveLength(1);+ expect(attributes[0].status).toBe("modified");+ expect(attributes[0].changedFields).toEqual({+ description: { before: "old", after: "new" }+ });+ });++ it("returns a single unchanged entry when no attribute differs", () => {+ const { attributes } = diffMethod({+ ...EMPTY,+ baseAttributes: { name: "Widget", description: "same" },+ targetAttributes: { name: "Widget", description: "same" }+ });+ expect(attributes).toHaveLength(1);+ expect(attributes[0].status).toBe("unchanged");+ });++ it("ignores audit/linkage columns in the attribute diff", () => {+ const { attributes } = diffMethod({+ ...EMPTY,+ baseAttributes: { name: "Widget", id: "a", updatedAt: "t1" },+ targetAttributes: { name: "Widget", id: "b", updatedAt: "t2" }+ });+ expect(attributes).toHaveLength(1);+ expect(attributes[0].status).toBe("unchanged");+ });+});diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex 795958cc4a..925e21bd19 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -14,6 +14,7 @@ import type { z } from "zod";import type { GenericQueryFilters } from "~/utils/query";import { setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";+import type { nonConformancePriority } from "../quality/quality.models";import type {operationParameterValidator,operationStepValidator,@@ -27,6 +28,13 @@ import {type SupplierPriceMap} from "../shared";import {+ type ChangeOrderChangeType,+ type ChangeOrderError,+ type ChangeOrderItemDiff,+ changeOrderOpenStatuses,+ type changeOrderStatus,+ type changeOrderTaskStatus,+ type changeOrderType,type configurationParameterGroupOrderValidator,type configurationParameterGroupValidator,type configurationParameterOrderValidator,@@ -36,14 +44,18 @@ import {type customerPartValidator,type getMethodValidator,ItemTrackingType,+ isAllowedChangeOrderTransition,type itemCostValidator,type itemManufacturingValidator,type itemPlanningValidator,type itemPostingGroupValidator,type itemPurchasingValidator,type itemSupersessionValidator,+ type itemTrackingTypes,type itemUnitSalePriceValidator,type itemValidator,+ type MethodDiffEntry,+ type MethodDiffStatus,type makeMethodVersionValidator,type materialDimensionValidator,type materialFinishValidator,@@ -54,6 +66,8 @@ import {type materialValidator,type methodMaterialValidator,type methodOperationValidator,+ type OperationChildrenDiff,+ type OperationDiffEntry,type partValidator,type pickMethodSortMethods,type pickMethodValidator,@@ -136,15 +150,42 @@ export async function copyMakeMethod(});}+// Copy a source item's item group (itemPostingGroupId, stored on itemCost) onto a+// freshly-created target item whose itemCost row was just auto-created with+// defaults by the item-insert trigger. No-op when the source has no group set.+export async function copyItemPostingGroup(+ client: SupabaseClient<Database>,+ args: { sourceItemId: string; targetItemId: string; companyId: string | null }+) {+ if (!args.companyId) return;+ const source = await client+ .from("itemCost")+ .select("itemPostingGroupId")+ .eq("itemId", args.sourceItemId)+ .eq("companyId", args.companyId)+ .maybeSingle();+ const groupId = source.data?.itemPostingGroupId ?? null;+ if (!groupId) return;+ await client+ .from("itemCost")+ .update({ itemPostingGroupId: groupId })+ .eq("itemId", args.targetItemId)+ .eq("companyId", args.companyId);+}+export async function createRevision(client: SupabaseClient<Database>,args: {item: NonNullable<Awaited<ReturnType<typeof getItem>>["data"]>;revision: string;createdBy: string;+ // Change-order draft revisions are created inactive so they don't surface+ // in item pickers/production until the change order is released. Manual+ // "New Revision" keeps the default (active).+ active?: boolean;}) {- const { item, revision, createdBy } = args;+ const { item, revision, createdBy, active = true } = args;const itemInsert = await client.from("item").insert({@@ -156,7 +197,14 @@ export async function createRevision(defaultMethodType: item.defaultMethodType,itemTrackingType: item.itemTrackingType,unitOfMeasureCode: item.unitOfMeasureCode,- active: true,+ // A revision starts as a faithful copy of the source's attributes so the+ // only differences the user (and the CO diff) sees are ones they made.+ description: item.description,+ sourcingType: item.sourcingType,+ requiresInspection: item.requiresInspection,+ thumbnailPath: item.thumbnailPath,+ mpn: item.mpn,+ active,modelUploadId: item.modelUploadId,companyId: item.companyId,createdBy: createdBy@@ -168,6 +216,14 @@ export async function createRevision(return itemInsert;}+ // Carry the source's item group (itemPostingGroupId lives on itemCost, which+ // the item-insert trigger auto-creates with defaults) onto the new revision.+ await copyItemPostingGroup(client, {+ sourceItemId: item.id,+ targetItemId: itemInsert.data.id,+ companyId: item.companyId+ });+if (item.replenishmentSystem !== "Buy") {await client.functions.invoke("get-method", {body: {@@ -183,6 +239,26 @@ export async function createRevision(return itemInsert;}+// getNextRevision — numeric → +1, A → …→ Z → AA, AA → AB, etc.+export function getNextRevision(maxRevision: string): string {+ if (/^\d+$/.test(maxRevision)) {+ return (parseInt(maxRevision) + 1).toString();+ } else if (/^[A-Z]{1,2}$/.test(maxRevision)) {+ if (maxRevision.length === 1) {+ return maxRevision === "Z"+ ? "AA"+ : String.fromCharCode(maxRevision.charCodeAt(0) + 1);+ }+ const firstChar = maxRevision[0];+ const secondChar = maxRevision[1];+ if (secondChar === "Z") {+ return String.fromCharCode(firstChar.charCodeAt(0) + 1) + "A";+ }+ return firstChar + String.fromCharCode(secondChar.charCodeAt(0) + 1);+ }+ return maxRevision;+}+export async function deleteConfigurationParameter(client: SupabaseClient<Database>,id: string@@ -476,6 +552,7 @@ export async function getConsumablesList(.order("name"));}+export async function getItem(client: SupabaseClient<Database>, id: string) {return client.from("item").select("*").eq("id", id).single();}@@ -4812,3 +4889,2565 @@ export async function getSupplierPartPriceBreaks(unitPrice: pb.unitPrice}));}+// =============================================================================+// Change Orders — header CRUD, stage transitions, list, and CO Types config.+// =============================================================================++// -----------------------------------------------------------------------------+// Reads+// -----------------------------------------------------------------------------+export async function getChangeOrder(+ client: SupabaseClient<Database>,+ changeOrderId: string,+ companyId: string+) {+ return client+ .from("changeOrder")+ .select("*")+ .eq("id", changeOrderId)+ .eq("companyId", companyId)+ .single();+}++export async function getChangeOrders(+ client: SupabaseClient<Database>,+ companyId: string,+ args?: GenericQueryFilters & { search: string | null }+) {+ let query = client+ .from("changeOrders")+ .select("*", { count: "exact" })+ .eq("companyId", companyId);++ if (args?.search) {+ query = query.or(+ `changeOrderId.ilike.%${args.search}%,name.ilike.%${args.search}%`+ );+ }++ if (args) {+ query = setGenericQueryFilters(query, args, [+ { column: "changeOrderId", ascending: false }+ ]);+ }++ return query;+}++// -----------------------------------------------------------------------------+// Header CRUD+// -----------------------------------------------------------------------------+export async function insertChangeOrder(+ client: SupabaseClient<Database>,+ input: {+ companyId: string;+ createdBy: string;+ changeOrderId?: string;+ name: string;+ type?: (typeof changeOrderType)[number];+ priority?: (typeof nonConformancePriority)[number];+ changeOrderTypeId?: string;+ nonConformanceId?: string;+ openDate: string;+ reasonForChange?: Json;+ description?: Json;+ dueDate?: string;+ assignee?: string;+ customFields?: Json;+ }+): Promise<{+ data: { id: string; changeOrderId: string } | null;+ error: ChangeOrderError | null;+}> {+ let changeOrderId: string;+ if (input.changeOrderId) {+ changeOrderId = input.changeOrderId;+ } else {+ const seq = await client.rpc("get_next_sequence", {+ sequence_name: "changeOrder",+ company_id: input.companyId+ });+ if (seq.error || !seq.data) {+ return {+ data: null,+ error: seq.error ?? {+ message: "Failed to generate changeOrder sequence"+ }+ };+ }+ changeOrderId = seq.data;+ }++ const result = await client+ .from("changeOrder")+ .insert({+ changeOrderId,+ name: input.name,+ type: input.type ?? "Engineering",+ priority: input.priority ?? null,+ changeOrderTypeId: input.changeOrderTypeId ?? null,+ nonConformanceId: input.nonConformanceId ?? null,+ openDate: input.openDate,+ reasonForChange: input.reasonForChange ?? {},+ description: input.description ?? {},+ dueDate: input.dueDate ?? null,+ assignee: input.assignee ?? null,+ customFields: input.customFields,+ companyId: input.companyId,+ createdBy: input.createdBy+ })+ .select("id, changeOrderId")+ .single();++ if (result.error || !result.data) {+ return { data: null, error: result.error };+ }++ // No default actions are seeded on create — the CO starts with zero required+ // actions selected; the user picks them afterward from the rail's Required+ // Actions multiselect (reconciled by setChangeOrderActionTasks).++ return {+ data: { id: result.data.id, changeOrderId: result.data.changeOrderId },+ error: null+ };+}++export async function updateChangeOrder(+ client: SupabaseClient<Database>,+ input: {+ id: string;+ updatedBy: string;+ changeOrderId?: string;+ name?: string;+ type?: (typeof changeOrderType)[number];+ priority?: (typeof nonConformancePriority)[number] | null;+ changeOrderTypeId?: string | null;+ nonConformanceId?: string | null;+ openDate?: string;+ reasonForChange?: Json;+ description?: Json;+ dueDate?: string | null;+ assignee?: string | null;+ customFields?: Json;+ }+): Promise<{+ data: { id: string } | null;+ error: ChangeOrderError | null;+}> {+ const { id, ...rest } = input;+ const result = await client+ .from("changeOrder")+ .update(sanitize(rest))+ .eq("id", id)+ .select("id")+ .single();++ if (result.error) return { data: null, error: result.error };+ return { data: { id: result.data.id }, error: null };+}++export async function deleteChangeOrder(+ client: SupabaseClient<Database>,+ changeOrderId: string,+ companyId: string+) {+ // Discard each affected item's CO-owned Draft first (the Draft make method for+ // a Version, or the revealed inactive item for a Revision/New Part). These are+ // NOT FK children of the change order, so the cascade below won't remove them —+ // only the changeOrderAffectedItem rows cascade. Without this, deleting a CO+ // orphans its drafts (mirrors removeChangeOrderAffectedItem's cleanup).+ const affected = await client+ .from("changeOrderAffectedItem")+ .select("draftMakeMethodId, newItemId")+ .eq("changeOrderId", changeOrderId)+ .eq("companyId", companyId);+ if (!affected.error && affected.data) {+ for (const item of affected.data) {+ await discardChangeOrderDraft(client, item, companyId);+ }+ }++ // Remaining children (affected items, action tasks) cascade via ON DELETE CASCADE.+ return client+ .from("changeOrder")+ .delete()+ .eq("id", changeOrderId)+ .eq("companyId", companyId);+}++// -----------------------------------------------------------------------------+// Stage transition — the single guarded writer (G8), a compare-and-swap (G2).+// Forward-only (isAllowedChangeOrderTransition).+// -----------------------------------------------------------------------------+export async function updateChangeOrderStatus(+ client: SupabaseClient<Database>,+ update: {+ id: string;+ companyId: string;+ fromStatus: (typeof changeOrderStatus)[number];+ toStatus: (typeof changeOrderStatus)[number];+ assignee?: string | null;+ updatedBy: string;+ }+): Promise<{+ data: { id: string; status: (typeof changeOrderStatus)[number] } | null;+ error: { message: string } | null;+}> {+ const { id, companyId, fromStatus, toStatus, ...rest } = update;++ if (!isAllowedChangeOrderTransition(fromStatus, toStatus)) {+ return {+ data: null,+ error: {+ message: `Cannot change status from ${fromStatus} to ${toStatus}`+ }+ };+ }++ // Build the update explicitly rather than sanitize({...rest}): sanitize coerces+ // every `undefined` field to null, which would wipe an existing assignee on a+ // transition where the caller passes it as undefined. Only set an optional+ // field when the caller provided a value.+ const payload: {+ status: (typeof changeOrderStatus)[number];+ updatedBy: string;+ assignee?: string | null;+ } = { status: toStatus, updatedBy: rest.updatedBy };+ if (rest.assignee !== undefined) payload.assignee = rest.assignee;++ const result = await client+ .from("changeOrder")+ .update(payload)+ .eq("id", id)+ .eq("companyId", companyId)+ .eq("status", fromStatus)+ .select("id, status")+ .maybeSingle();++ if (result.error) return { data: null, error: result.error };+ if (!result.data) {+ return {+ data: null,+ error: {+ message:+ "The change order was updated by someone else. Refresh and try again."+ }+ };+ }+ return { data: result.data, error: null };+}++// -----------------------------------------------------------------------------+// Change Order Types (the "Category" lookup — configured like Issue Types)+// -----------------------------------------------------------------------------+export async function getChangeOrderTypes(+ client: SupabaseClient<Database>,+ companyId: string,+ args?: GenericQueryFilters & { search: string | null }+) {+ let query = client+ .from("changeOrderType")+ .select("*", { count: "exact" })+ .eq("companyId", companyId);++ if (args?.search) {+ query = query.ilike("name", `%${args.search}%`);+ }++ if (args) {+ query = setGenericQueryFilters(query, args, [+ { column: "name", ascending: true }+ ]);+ }++ return query;+}++export async function getChangeOrderTypesList(+ client: SupabaseClient<Database>,+ companyId: string+) {+ return client+ .from("changeOrderType")+ .select("id, name")+ .eq("companyId", companyId)+ .order("name", { ascending: true });+}++export async function getChangeOrderType(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("changeOrderType").select("*").eq("id", id).single();+}++export async function upsertChangeOrderType(+ client: SupabaseClient<Database>,+ changeOrderType:+ | {+ name: string;+ companyId: string;+ createdBy: string;+ customFields?: Json;+ }+ | {+ id: string;+ name: string;+ updatedBy: string;+ customFields?: Json;+ }+) {+ if ("createdBy" in changeOrderType) {+ return client+ .from("changeOrderType")+ .insert([changeOrderType])+ .select("id")+ .single();+ }+ return client+ .from("changeOrderType")+ .update(sanitize(changeOrderType))+ .eq("id", changeOrderType.id)+ .select("id")+ .single();+}++export async function deleteChangeOrderType(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("changeOrderType").delete().eq("id", id);+}++// =============================================================================+// Phase 2 — Products Affected+// =============================================================================++// Joins to `item` throughout Phase 2 are done as separate FLAT scalar selects ++// a JS stitch rather than PostgREST embeds: an embedded select instantiates+// PostgREST's deeply-recursive relation parser, and across the module that+// pushed TS's global instantiation budget over the edge (TS2589 in unrelated+// files). Flat selects barely instantiate.++// Climb the BOM (methodMaterial → makeMethod → item) from a set of start items up+// to the top-level products — items that are used by nothing. Returns each product+// with `sourceItemIds`: which of the start items (the targeted assemblies) rolled up+// into it (provenance, for the "affected by" display). Flat queries (no PostgREST+// embeds — TS2589 budget); a per-item origin set that only grows drives a fixpoint,+// so a corrupt/cyclic BOM can't loop forever and provenance fully propagates.+// `nodeBudget` is a pure infinite-loop backstop, not a depth limit.+export async function getTopLevelProductsForItems(+ client: SupabaseClient<Database>,+ itemIds: string[],+ companyId: string+): Promise<{+ data: Array<{ productId: string; sourceItemIds: string[] }>;+ error: { message: string } | null;+}> {+ const start = [...new Set(itemIds.filter(Boolean))];+ if (start.length === 0) return { data: [], error: null };++ // origins[item] = the start items (targeted assemblies) that reach it.+ const origins = new Map<string, Set<string>>();+ for (const s of start) origins.set(s, new Set([s]));+ // parentsCache[item] = its immediate parent items (one level up), fetched once.+ const parentsCache = new Map<string, Set<string>>();+ const roots = new Map<string, Set<string>>();++ const fetchParents = async (ids: string[]) => {+ const unknown = ids.filter((id) => !parentsCache.has(id));+ if (unknown.length === 0) return;+ for (const id of unknown) parentsCache.set(id, new Set());++ const materials = await client+ .from("methodMaterial")+ .select("itemId, makeMethodId")+ .in("itemId", unknown)+ .eq("companyId", companyId);+ if (materials.error) throw materials.error;++ const makeMethodIds = [+ ...new Set((materials.data ?? []).map((m) => m.makeMethodId))+ ];+ const parentByMethod = new Map<string, string>();+ if (makeMethodIds.length > 0) {+ const methods = await client+ .from("makeMethod")+ .select("id, itemId")+ .in("id", makeMethodIds)+ .eq("companyId", companyId);+ if (methods.error) throw methods.error;+ for (const mm of methods.data ?? []) parentByMethod.set(mm.id, mm.itemId);+ }+ for (const row of materials.data ?? []) {+ const parent = parentByMethod.get(row.makeMethodId);+ if (parent) parentsCache.get(row.itemId)?.add(parent);+ }+ };++ let queue = [...start];+ let nodeBudget = 20000;+ try {+ while (queue.length > 0 && nodeBudget > 0) {+ const batch = [...new Set(queue)];+ queue = [];+ nodeBudget -= batch.length;+ await fetchParents(batch);++ for (const id of batch) {+ const parents = parentsCache.get(id);+ const idOrigins = origins.get(id) ?? new Set<string>();++ if (!parents || parents.size === 0) {+ // used by nothing → a top-level product; record its origins+ if (!roots.has(id)) roots.set(id, new Set());+ const rootOrigins = roots.get(id)!;+ for (const o of idOrigins) rootOrigins.add(o);+ continue;+ }++ for (const parent of parents) {+ if (!origins.has(parent)) origins.set(parent, new Set());+ const target = origins.get(parent)!;+ const before = target.size;+ for (const o of idOrigins) target.add(o);+ // Re-enqueue when the parent's origin set grew (monotonic, finite → the+ // loop terminates even on cyclic data) so provenance fully propagates.+ if (target.size > before) queue.push(parent);+ }+ }+ }+ } catch (err) {+ return { data: [], error: { message: (err as Error).message } };+ }++ return {+ data: [...roots.entries()].map(([productId, srcs]) => ({+ productId,+ sourceItemIds: [...srcs]+ })),+ error: null+ };+}++// G3 — forward-reference to a not-yet-synced part. Mints a REAL item row+// (active=false, revisionStatus='Design') through the standard item shape so+// `changeOrderStagedMaterial.itemId` is always non-null and no placeholder branch+// is threaded downstream. Onshape sync reconciles by matching readableId+company+// (flip active, fill details). A cancelled CO can leave an inactive stub — it's+// filterable and tied to the CO, far cheaper than nullable-threading everywhere.+export async function mintPlaceholderPart(+ client: SupabaseClient<Database>,+ input: {+ readableId: string;+ name: string;+ companyId: string;+ createdBy: string;+ unitOfMeasureCode?: string;+ }+): Promise<{+ data: { id: string } | null;+ error: ChangeOrderError | null;+}> {+ const item = await client+ .from("item")+ .insert({+ readableId: input.readableId,+ revision: "0",+ name: input.name,+ type: "Part",+ replenishmentSystem: "Buy",+ defaultMethodType: "Pull from Inventory",+ itemTrackingType: "Inventory",+ unitOfMeasureCode: input.unitOfMeasureCode ?? "EA",+ active: false,+ revisionStatus: "Design",+ companyId: input.companyId,+ createdBy: input.createdBy+ })+ .select("id")+ .single();++ if (item.error || !item.data) return { data: null, error: item.error };++ const part = await client.from("part").insert({+ id: input.readableId,+ companyId: input.companyId,+ createdBy: input.createdBy+ });+ if (part.error) return { data: null, error: part.error };++ return { data: { id: item.data.id }, error: null };+}++// =============================================================================+// v2 — CO-owned Draft make-method orchestration (affected items).+//+// A CO's edits for one affected item live on a REAL Draft makeMethod owned by+// the CO (makeMethod.changeOrderId set). That draft is shown/edited both in the+// CO workspace and on the affected item's own master page (same rows, in sync);+// changeOrderId is cleared at release. Creating an affected item spins that+// draft per the change type:+// Version → new Draft method version on the SAME item (BoM/BoP edits).+// Revision → new inactive revision item + its Draft method (attrs/docs).+// New Part → new inactive part number (new readableId) + copied Draft method.+// All three keep the user client (the release path uses the same client for the+// same privileged method helpers — see applyChangeOrder / changeOrder.server).+// =============================================================================++// Mint the next readableId for a CO-derived New Part, following the SAME numbering+// scheme as the source part — so "GA-0029" yields "GA-0030", not a bare number.+// Server-side mirror of useNextItemId: split the source readableId into its+// non-numeric prefix + trailing number, ask the matching sequence RPC for the+// current MAX with that shape, then increment + zero-pad to the same width.+// Falls back to a plain numeric id when the source has no prefix.+async function getNextItemIdFromSource(+ client: SupabaseClient<Database>,+ companyId: string,+ itemType: Database["public"]["Enums"]["itemType"],+ sourceReadableId: string+): Promise<string> {+ const prefix = sourceReadableId.match(/^(.*?)\d+$/)?.[1] ?? "";++ const rpc = prefix+ ? await client.rpc("get_next_prefixed_sequence", {+ company_id: companyId,+ item_type: itemType,+ prefix+ })+ : await client.rpc("get_next_numeric_sequence", {+ company_id: companyId,+ item_type: itemType+ });++ const current = rpc.data;+ const sequence = current?.slice(prefix.length) ?? "";+ const currentSequence = parseInt(sequence, 10);+ if (!current || Number.isNaN(currentSequence)) {+ return `${prefix}${(1).toString().padStart(9, "0")}`;+ }+ // Preserve the source's digit width (mirrors useNextItemId's pad math).+ const tail = current.split(`${currentSequence}`)?.[1]?.length ?? 0;+ const width = Math.max(sequence.length - tail, 1);+ return `${prefix}${(currentSequence + 1).toString().padStart(width, "0")}`;+}++// Resolve the current Active make method id for an item (the base the draft is+// copied from + the merge base at release). Falls back to the highest version.+// Also returns `maxVersion` = the highest version number across ALL of the+// item's methods (Draft/Active/Archived) — a new draft must be numbered above+// this, not above the Active one, so parallel COs on the same item don't collide+// on the `(itemId, version)` unique constraint (a hidden CO draft already holds+// Active+1).+async function getActiveMakeMethodId(+ client: SupabaseClient<Database>,+ itemId: string,+ companyId: string+): Promise<{+ id: string;+ version: number;+ maxVersion: number;+ // `status` of the chosen method. Since `chosen = active ?? rows[0]`, a value of+ // "Draft" means the item has NO Active method — its current method is still an+ // un-activated draft (the common case for a Make item that never spun a v2).+ status: string;+} | null> {+ const methods = await client+ .from("makeMethod")+ .select("id, version, status")+ .eq("itemId", itemId)+ .eq("companyId", companyId)+ .order("version", { ascending: false });+ const rows = methods.data ?? [];+ if (rows.length === 0) return null;+ const active = rows.find((r) => r.status === "Active");+ const chosen = active ?? rows[0];+ // rows are ordered by version DESC, so rows[0] holds the highest version.+ const maxVersion = rows[0].version ?? chosen.version ?? 1;+ return {+ id: chosen.id,+ version: chosen.version ?? 1,+ maxVersion,+ status: chosen.status+ };+}++// Fetch the (single) Draft make method for a freshly-created item — the trigger+// creates one and createRevision/copyItem populate it.+async function getDraftMakeMethodIdForItem(+ client: SupabaseClient<Database>,+ itemId: string,+ companyId: string+): Promise<string | null> {+ const draft = await client+ .from("makeMethod")+ .select("id")+ .eq("itemId", itemId)+ .eq("companyId", companyId)+ .eq("status", "Draft")+ .order("version", { ascending: false })+ .limit(1)+ .maybeSingle();+ return draft.data?.id ?? null;+}++type DraftMethodResult = {+ data: {+ draftMakeMethodId: string | null;+ baseMakeMethodId: string | null;+ newItemId: string | null;+ } | null;+ error: ChangeOrderError | null;+};++// Create the CO-owned Draft make method for an affected item per its change type.+export async function createChangeOrderDraftMethod(+ client: SupabaseClient<Database>,+ input: {+ changeOrderId: string;+ itemId: string;+ changeType: ChangeOrderChangeType;+ // Optional revision label for the Revision path — when the caller already+ // knows the target revision (e.g. the value typed in the new-revision+ // modal). Omitted → the next revision is auto-computed.+ revision?: string;+ companyId: string;+ userId: string;+ }+): Promise<DraftMethodResult> {+ const { changeOrderId, itemId, changeType, revision, companyId, userId } =+ input;++ const base = await getActiveMakeMethodId(client, itemId, companyId);++ if (changeType === "Version") {+ if (!base) {+ return {+ data: null,+ error: { message: "Item has no make method to version" }+ };+ }+ // If the item's current method is still an un-activated Draft (no Active+ // version — the common case for a Make item that never spun a v2), promote it+ // to Active as we create the CO's new draft, mirroring the make-method-tools+ // "New Version" flow. Otherwise the CO draft (numbered above the base) would+ // outrank the base draft in `activeMakeMethods` — which falls back to the+ // 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+ // 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, {+ copyFromId: base.id,+ activeVersionId,+ version: nextVersion,+ companyId,+ createdBy: userId+ });+ if (!res.error && res.data) {+ draftId = res.data.id;+ break;+ }+ // 23505 = unique_violation (makeMethod_unique_itemId_version); a parallel+ // CO grabbed this number first — recompute the next free version + retry.+ if (res.error?.code === "23505") {+ const latest = await getActiveMakeMethodId(client, itemId, companyId);+ nextVersion = (latest?.maxVersion ?? nextVersion) + 1;+ continue;+ }+ return {+ data: null,+ error: res.error ?? { message: "Failed to create draft version" }+ };+ }+ if (!draftId) {+ return {+ data: null,+ error: { message: "Failed to create draft version" }+ };+ }+ // @ts-expect-error TS2345 - getMethodValidator flags default via edge fn+ const copy = await copyMakeMethod(client, {+ 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 })+ .eq("id", draftId)+ .eq("companyId", companyId);+ if (stamp.error) return { data: null, error: stamp.error };+ return {+ data: {+ draftMakeMethodId: draftId,+ baseMakeMethodId: base.id,+ newItemId: null+ },+ error: null+ };+ }++ if (changeType === "Revision") {+ const source = await getItem(client, itemId);+ if (source.error || !source.data) {+ return { data: null, error: { message: "Item not found" } };+ }+ // Honor a caller-supplied revision label (e.g. the value typed in the+ // new-revision modal); otherwise auto-pick the next revision string across+ // the item's readableId siblings.+ let nextRevision = revision?.trim();+ if (!nextRevision) {+ const siblings = await client+ .from("item")+ .select("revision")+ .eq("readableId", source.data.readableId)+ .eq("companyId", companyId)+ .eq("type", source.data.type)+ .order("revision", { ascending: false });+ const maxRevision = siblings.data?.[0]?.revision ?? "0";+ nextRevision = getNextRevision(maxRevision);+ }++ const created = await createRevision(client, {+ item: source.data,+ revision: nextRevision,+ createdBy: userId,+ active: false+ });+ if (created.error || !created.data) {+ return { data: null, error: created.error };+ }+ const newItemId = created.data.id;+ const draftId = await getDraftMakeMethodIdForItem(+ client,+ newItemId,+ companyId+ );+ const stampItem = await client+ .from("item")+ .update({ changeOrderId })+ .eq("id", newItemId)+ .eq("companyId", companyId);+ if (stampItem.error) return { data: null, error: stampItem.error };+ if (draftId) {+ await client+ .from("makeMethod")+ .update({ changeOrderId })+ .eq("id", draftId)+ .eq("companyId", companyId);+ }+ return {+ data: {+ draftMakeMethodId: draftId,+ baseMakeMethodId: base?.id ?? null,+ newItemId+ },+ error: null+ };+ }++ if (changeType === "New Part") {+ // Net-new part — no predecessor, no supersession. addChangeOrderAffectedItem+ // already minted the item (inactive, CO-stamped); here `itemId` IS that new+ // item. Its insert trigger created a Draft makeMethod (status default 'Draft');+ // stamp it CO-owned so it hides from version lists until release (parity with+ // Revision). No source to copy from → empty draft, no baseMakeMethodId.+ const draftId = await getDraftMakeMethodIdForItem(+ client,+ itemId,+ companyId+ );+ if (draftId) {+ const stamp = await client+ .from("makeMethod")+ .update({ changeOrderId })+ .eq("id", draftId)+ .eq("companyId", companyId);+ if (stamp.error) return { data: null, error: stamp.error };+ }+ return {+ data: {+ draftMakeMethodId: draftId,+ baseMakeMethodId: null,+ newItemId: itemId+ },+ error: null+ };+ }++ // Replacement Part — a new part number derived from + (at release) superseding+ // the affected part. This is the only remaining change type here: Version /+ // Revision / New Part all returned above, so `changeType` is narrowed to+ // "Replacement Part". ECO scope is Parts + Tools (Materials/Consumables/Services+ // excluded); reject other types rather than mint a malformed row.+ const source = await getItem(client, itemId);+ if (source.error || !source.data) {+ return { data: null, error: { message: "Item not found" } };+ }+ if (source.data.type !== "Part" && source.data.type !== "Tool") {+ return {+ data: null,+ error: {+ message: `New Part is only supported for Parts and Tools (got ${source.data.type})`+ }+ };+ }+ const newReadableId = await getNextItemIdFromSource(+ client,+ companyId,+ source.data.type,+ source.data.readableId+ );+ const newItem = await client+ .from("item")+ .insert({+ readableId: newReadableId,+ revision: "0",+ name: source.data.name,+ type: source.data.type,+ replenishmentSystem: source.data.replenishmentSystem,+ defaultMethodType: source.data.defaultMethodType,+ itemTrackingType: source.data.itemTrackingType,+ unitOfMeasureCode: source.data.unitOfMeasureCode,+ // Faithfully copy the source's attributes so the CO diff shows only the+ // user's edits, not gaps left by an incomplete copy.+ description: source.data.description,+ sourcingType: source.data.sourcingType,+ requiresInspection: source.data.requiresInspection,+ thumbnailPath: source.data.thumbnailPath,+ mpn: source.data.mpn,+ active: false,+ revisionStatus: "Design",+ changeOrderId,+ companyId,+ createdBy: userId+ })+ .select("id")+ .single();+ if (newItem.error || !newItem.data) {+ return { data: null, error: newItem.error };+ }+ const newItemId = newItem.data.id;+ const typeTable = source.data.type === "Part" ? "part" : "tool";+ const typeRow = await client+ .from(typeTable)+ .insert({ id: newReadableId, companyId, createdBy: userId });+ if (typeRow.error) return { data: null, error: typeRow.error };++ // Carry the source's item group (on itemCost) onto the new part.+ await copyItemPostingGroup(client, {+ sourceItemId: itemId,+ targetItemId: newItemId,+ companyId+ });++ // Copy the affected part's method into the new item's (trigger-created) draft.+ // @ts-expect-error TS2345 - getMethodValidator flags default via edge fn+ const copy = await copyItem(client, {+ sourceId: itemId,+ targetId: newItemId,+ companyId,+ userId+ });+ if (copy.error) {+ return { data: null, error: { message: "Failed to copy make method" } };+ }+ const draftId = await getDraftMakeMethodIdForItem(+ client,+ newItemId,+ companyId+ );+ if (draftId) {+ await client+ .from("makeMethod")+ .update({ changeOrderId })+ .eq("id", draftId)+ .eq("companyId", companyId);+ }+ return {+ data: {+ draftMakeMethodId: draftId,+ baseMakeMethodId: base?.id ?? null,+ newItemId+ },+ error: null+ };+}++// Discard an affected item's CO-owned Draft (used on change-type switch + when+// removing the affected item). Deletes the new item for Revision/New Part+// (cascades its method rows) or the Draft method for Version.+async function discardChangeOrderDraft(+ client: SupabaseClient<Database>,+ affected: {+ draftMakeMethodId: string | null;+ newItemId: string | null;+ },+ companyId: string+): Promise<void> {+ if (affected.newItemId) {+ await client+ .from("item")+ .delete()+ .eq("id", affected.newItemId)+ .eq("companyId", companyId);+ return;+ }+ if (affected.draftMakeMethodId) {+ await client+ .from("makeMethod")+ .delete()+ .eq("id", affected.draftMakeMethodId)+ .eq("companyId", companyId);+ }+}++// Add an affected item to a CO: insert the row, then spin its CO-owned Draft+// make method per the change type and write the draft refs back. Rolls the row+// back if draft creation fails (edge-fn calls can't share one txn — G2).+export async function addChangeOrderAffectedItem(+ client: SupabaseClient<Database>,+ input: {+ changeOrderId: string;+ // The existing affected item (Version / Revision / Replacement Part). Omitted+ // for the net-new New Part path, where `newPart` is supplied and the item is+ // minted here.+ itemId?: string;+ changeType: ChangeOrderChangeType;+ // Forwarded to the Revision draft path so a Revision affected item can take+ // an explicit revision label (e.g. from the new-revision modal).+ revision?: string;+ // Net-new "New Part": mint a brand-new inactive Part/Tool and add it as a New+ // Part affected item (no existing itemId, no predecessor/supersession).+ newPart?: {+ readableId: string;+ name: string;+ itemType: "Part" | "Tool";+ replenishmentSystem: "Buy" | "Make" | "Buy and Make";+ itemTrackingType?: (typeof itemTrackingTypes)[number];+ };+ companyId: string;+ userId: string;+ }+): Promise<{+ data: { id: string; draftMakeMethodId: string | null } | null;+ error: ChangeOrderError | null;+}> {+ const { changeOrderId, changeType, revision, newPart, companyId, userId } =+ input;+ let itemId = input.itemId;+ let effectiveChangeType: ChangeOrderChangeType = changeType;++ if (newPart) {+ // Net-new part introduced by the CO — mint an inactive Part/Tool + its type+ // row, CO-stamped. The minted id becomes the affected item (no predecessor).+ if (newPart.itemType !== "Part" && newPart.itemType !== "Tool") {+ return {+ data: null,+ error: { message: "New Part is only supported for Parts and Tools" }+ };+ }+ const defaultMethodType =+ newPart.replenishmentSystem === "Make"+ ? "Make to Order"+ : newPart.replenishmentSystem === "Buy"+ ? "Purchase to Order"+ : "Pull from Inventory";+ const minted = await client+ .from("item")+ .insert({+ readableId: newPart.readableId,+ revision: "0",+ name: newPart.name,+ type: newPart.itemType,+ replenishmentSystem: newPart.replenishmentSystem,+ defaultMethodType,+ itemTrackingType: newPart.itemTrackingType ?? "Inventory",+ unitOfMeasureCode: "EA",+ active: false,+ revisionStatus: "Design",+ changeOrderId,+ companyId,+ createdBy: userId+ })+ .select("id")+ .single();+ if (minted.error || !minted.data) {+ return { data: null, error: minted.error };+ }+ itemId = minted.data.id;+ const typeTable = newPart.itemType === "Part" ? "part" : "tool";+ const typeRow = await client+ .from(typeTable)+ .insert({ id: newPart.readableId, companyId, createdBy: userId });+ if (typeRow.error) return { data: null, error: typeRow.error };+ effectiveChangeType = "New Part";+ }++ if (!itemId) {+ return { data: null, error: { message: "Item is required" } };+ }++ // A purchased (Buy) item has no BoM/BoP, so a Version change is a no-op —+ // default it to a Revision (part-data/docs), the meaningful change for Buy.+ if (!newPart && changeType === "Version") {+ const item = await client+ .from("item")+ .select("replenishmentSystem")+ .eq("id", itemId)+ .eq("companyId", companyId)+ .maybeSingle();+ if (item.data?.replenishmentSystem === "Buy") {+ effectiveChangeType = "Revision";+ }+ }++ const last = await client+ .from("changeOrderAffectedItem")+ .select("sortOrder")+ .eq("changeOrderId", changeOrderId)+ .eq("companyId", companyId)+ .order("sortOrder", { ascending: false })+ .limit(1)+ .maybeSingle();+ const sortOrder = (last.data?.sortOrder ?? -1) + 1;++ const inserted = await client+ .from("changeOrderAffectedItem")+ .insert({+ changeOrderId,+ itemId,+ changeType: effectiveChangeType,+ sortOrder,+ companyId,+ createdBy: userId+ })+ .select("id")+ .single();+ if (inserted.error || !inserted.data) {+ return { data: null, error: inserted.error };+ }+ const affectedItemId = inserted.data.id;++ const draft = await createChangeOrderDraftMethod(client, {+ changeOrderId,+ itemId,+ changeType: effectiveChangeType,+ revision,+ companyId,+ userId+ });+ if (draft.error || !draft.data) {+ await client+ .from("changeOrderAffectedItem")+ .delete()+ .eq("id", affectedItemId)+ .eq("companyId", companyId);+ return { data: null, error: draft.error };+ }++ await client+ .from("changeOrderAffectedItem")+ .update({+ draftMakeMethodId: draft.data.draftMakeMethodId,+ baseMakeMethodId: draft.data.baseMakeMethodId,+ newItemId: draft.data.newItemId,+ updatedBy: userId+ })+ .eq("id", affectedItemId)+ .eq("companyId", companyId);++ return {+ data: {+ id: affectedItemId,+ draftMakeMethodId: draft.data.draftMakeMethodId+ },+ error: null+ };+}++// Switch an affected item's change type: discard its current draft and rebuild+// for the new type (Q2 — the editable surface differs per type, so edits reset).+export async function updateChangeOrderAffectedItemChangeType(+ client: SupabaseClient<Database>,+ input: {+ id: string;+ changeType: ChangeOrderChangeType;+ companyId: string;+ userId: string;+ }+): Promise<{ data: { id: string } | null; error: ChangeOrderError | null }> {+ const { id, changeType, companyId, userId } = input;++ const affected = await client+ .from("changeOrderAffectedItem")+ .select(+ "id, changeOrderId, itemId, changeType, draftMakeMethodId, newItemId"+ )+ .eq("id", id)+ .eq("companyId", companyId)+ .single();+ if (affected.error || !affected.data) {+ return { data: null, error: { message: "Affected item not found" } };+ }+ // A New Part is net-new by construction — it cannot be switched to another type,+ // nor can an existing-part change become net-new. Reject both directions.+ if (changeType === "New Part" || affected.data.changeType === "New Part") {+ return {+ data: null,+ error: { message: "New Part change type cannot be switched" }+ };+ }+ if (affected.data.changeType === changeType) {+ return { data: { id }, error: null };+ }++ // Create the replacement Draft BEFORE destroying the current one, so a failure+ // in creation or the ref swap leaves the affected row still pointing at a valid+ // (undeleted) draft instead of a dangling reference. The old draft is discarded+ // only after the swap succeeds (worst case on a late failure is an orphaned+ // draft, never a dangling ref). Capture the old refs first.+ const previousDraft = {+ draftMakeMethodId: affected.data.draftMakeMethodId,+ newItemId: affected.data.newItemId+ };++ const draft = await createChangeOrderDraftMethod(client, {+ changeOrderId: affected.data.changeOrderId,+ itemId: affected.data.itemId,+ changeType,+ companyId,+ userId+ });+ if (draft.error || !draft.data) {+ return { data: null, error: draft.error };+ }++ const updated = await client+ .from("changeOrderAffectedItem")+ .update({+ changeType,+ draftMakeMethodId: draft.data.draftMakeMethodId,+ baseMakeMethodId: draft.data.baseMakeMethodId,+ newItemId: draft.data.newItemId,+ updatedBy: userId+ })+ .eq("id", id)+ .eq("companyId", companyId);+ if (updated.error) return { data: null, error: updated.error };++ // Swap succeeded — now safe to discard the superseded draft.+ await discardChangeOrderDraft(client, previousDraft, companyId);+ return { data: { id }, error: null };+}++// Update the per-item revision cutover config (mode + dates). The existence of+// the oldRev→newRev supersession is automatic at release; this only tunes it.+export async function updateChangeOrderAffectedItemCutover(+ client: SupabaseClient<Database>,+ input: {+ id: string;+ supersessionMode: Database["public"]["Enums"]["supersessionMode"];+ discontinuationDate?: string;+ successorEffectivityDate?: string;+ userId: string;+ }+) {+ const { id, userId, ...rest } = input;+ return client+ .from("changeOrderAffectedItem")+ .update({+ ...sanitize(rest),+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ .eq("id", id)+ .select("id")+ .single();+}++// =============================================================================+// Affected-item + supersession reads/writes (label-stitched). Flat selects + JS+// stitch (no composite-FK PostgREST embeds — the erp TS2589 budget).+// =============================================================================++// The minimal item label rendered next to each affected item / supersession.+export type ChangeOrderStagingItemLabel = {+ id: string;+ readableId: string;+ readableIdWithRevision: string | null;+ name: string;+ type: Database["public"]["Enums"]["itemType"];+ active: boolean;+ revisionStatus: Database["public"]["Enums"]["itemRevisionStatus"];+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"];+};++type ChangeOrderAffectedItemRow =+ Database["public"]["Tables"]["changeOrderAffectedItem"]["Row"];++export type ChangeOrderAffectedItemWithLabel = ChangeOrderAffectedItemRow & {+ item: ChangeOrderStagingItemLabel | null;+};++const ITEM_LABEL_COLUMNS =+ "id, readableId, readableIdWithRevision, name, type, active, revisionStatus, replenishmentSystem";++// Fetch minimal item labels for a set of ids, indexed by item id.+async function stitchItemLabels(+ client: SupabaseClient<Database>,+ itemIds: string[],+ companyId: string+): Promise<{+ labels: Map<string, ChangeOrderStagingItemLabel>;+ error: { message: string } | null;+}> {+ const uniqueIds = [...new Set(itemIds)];+ const labels = new Map<string, ChangeOrderStagingItemLabel>();+ if (uniqueIds.length === 0) return { labels, error: null };++ const items = await client+ .from("item")+ .select(ITEM_LABEL_COLUMNS)+ .in("id", uniqueIds)+ .eq("companyId", companyId);++ if (items.error) return { labels, error: items.error };+ for (const it of items.data ?? [])+ labels.set(it.id, it as ChangeOrderStagingItemLabel);++ return { labels, error: null };+}++// The affected items of a CO, each stitched to a minimal item label.+export async function getChangeOrderAffectedItems(+ client: SupabaseClient<Database>,+ changeOrderId: string,+ companyId: string+): Promise<{+ data: ChangeOrderAffectedItemWithLabel[];+ error: { message: string } | null;+}> {+ const affected = await client+ .from("changeOrderAffectedItem")+ .select("*")+ .eq("changeOrderId", changeOrderId)+ .eq("companyId", companyId)+ .order("sortOrder", { ascending: true })+ .order("createdAt", { ascending: true });++ if (affected.error) return { data: [], error: affected.error };+ const rows = affected.data ?? [];+ if (rows.length === 0) return { data: [], error: null };++ const { labels, error } = await stitchItemLabels(+ client,+ rows.map((r) => r.itemId),+ companyId+ );+ if (error) return { data: [], error };++ return {+ data: rows.map((r) => ({ ...r, item: labels.get(r.itemId) ?? null })),+ error: null+ };+}++// Remove an affected item + discard its CO-owned Draft (delete the new item for+// Revision/New Part, or the Draft method for Version) so no orphan draft leaks.+export async function removeChangeOrderAffectedItem(+ client: SupabaseClient<Database>,+ id: string,+ companyId: string+) {+ const affected = await client+ .from("changeOrderAffectedItem")+ .select("draftMakeMethodId, newItemId")+ .eq("id", id)+ .eq("companyId", companyId)+ .maybeSingle();+ if (!affected.error && affected.data) {+ await discardChangeOrderDraft(client, affected.data, companyId);+ }+ return client+ .from("changeOrderAffectedItem")+ .delete()+ .eq("id", id)+ .eq("companyId", companyId);+}++// =============================================================================+// Change Orders — item traceability reads (part/tool ↔ CO) and the linked-NCR+// reverse view. Split out of changeOrder.service.ts to keep each file focused+// and under the module's 1000-line budget (G4).+// =============================================================================++// G6 — the SINGLE canonical "change orders referencing this item" query,+// parameterized by status. The item-detail history (all COs), the open-CO alert+// (open statuses), and the single-open-CO guard all call this — no forked+// implementations. Spans every way a CO references an item in the top-to-bottom+// model: an affected item the user selected to change, a staged BOM component,+// a manual supersession (predecessor or successor), and the reverse link from a+// released revision (`item.changeOrderId`). Scoped by readableId so it matches+// the part across all its revisions. Flat queries + JS union (no embeds —+// TS2589 budget).+export type ChangeOrderForItem = {+ id: string;+ changeOrderId: string;+ name: string;+ status: Database["public"]["Enums"]["changeOrderStatus"];+ changeOrderTypeId: string | null;+ createdAt: string;+};++export async function findChangeOrdersForItem(+ client: SupabaseClient<Database>,+ args: {+ itemId: string;+ companyId: string;+ statuses?: Database["public"]["Enums"]["changeOrderStatus"][];+ }+): Promise<{ data: ChangeOrderForItem[]; error: { message: string } | null }> {+ const { itemId, companyId, statuses } = args;++ // Resolve every revision (item row) sharing this part's readableId.+ const item = await client+ .from("item")+ .select("readableId")+ .eq("id", itemId)+ .eq("companyId", companyId)+ .maybeSingle();+ if (item.error) return { data: [], error: item.error };+ if (!item.data?.readableId) return { data: [], error: null };++ const siblings = await client+ .from("item")+ .select("id, changeOrderId")+ .eq("readableId", item.data.readableId)+ .eq("companyId", companyId);+ if (siblings.error) return { data: [], error: siblings.error };+ const itemIds = (siblings.data ?? []).map((s) => s.id);+ if (itemIds.length === 0) return { data: [], error: null };++ // Collect referencing changeOrderIds from every relation. v2: instead of a+ // staged-material mirror, "this item is a component in a CO's edited BOM" is+ // found via methodMaterial rows on CO-owned draft methods (makeMethod with a+ // non-null changeOrderId).+ const [affected, componentMaterials, predecessors, successors] =+ await Promise.all([+ client+ .from("changeOrderAffectedItem")+ .select("changeOrderId")+ .in("itemId", itemIds)+ .eq("companyId", companyId),+ client+ .from("methodMaterial")+ .select("makeMethodId")+ .in("itemId", itemIds)+ .eq("companyId", companyId),+ client+ .from("changeOrderSupersession")+ .select("changeOrderId")+ .in("predecessorItemId", itemIds)+ .eq("companyId", companyId),+ client+ .from("changeOrderSupersession")+ .select("changeOrderId")+ .in("successorItemId", itemIds)+ .eq("companyId", companyId)+ ]);+ if (affected.error) return { data: [], error: affected.error };+ if (componentMaterials.error)+ return { data: [], error: componentMaterials.error };+ if (predecessors.error) return { data: [], error: predecessors.error };+ if (successors.error) return { data: [], error: successors.error };++ // Resolve which of those make methods are CO-owned drafts.+ const makeMethodIds = [+ ...new Set(+ (componentMaterials.data ?? []).map((m) => m.makeMethodId).filter(Boolean)+ )+ ] as string[];+ const coOwnedMethods = makeMethodIds.length+ ? await client+ .from("makeMethod")+ .select("changeOrderId")+ .in("id", makeMethodIds)+ .not("changeOrderId", "is", null)+ .eq("companyId", companyId)+ : { data: [], error: null };+ if (coOwnedMethods.error) return { data: [], error: coOwnedMethods.error };++ const coIds = new Set<string>();+ for (const a of affected.data ?? []) coIds.add(a.changeOrderId);+ for (const m of coOwnedMethods.data ?? []) {+ if (m.changeOrderId) coIds.add(m.changeOrderId);+ }+ for (const p of predecessors.data ?? []) coIds.add(p.changeOrderId);+ for (const s of successors.data ?? []) coIds.add(s.changeOrderId);++ // Reverse link: a released revision points at the CO that created it.+ for (const s of siblings.data ?? []) {+ if (s.changeOrderId) coIds.add(s.changeOrderId);+ }++ if (coIds.size === 0) return { data: [], error: null };++ let query = client+ .from("changeOrder")+ .select("id, changeOrderId, name, status, changeOrderTypeId, createdAt")+ .in("id", [...coIds])+ .eq("companyId", companyId);+ if (statuses && statuses.length > 0) query = query.in("status", statuses);+ query = query.order("createdAt", { ascending: false });++ const result = await query;+ if (result.error) return { data: [], error: result.error };+ return { data: result.data ?? [], error: null };+}++// Reverse of the Linked-NCR cross-link (4a): every change order that references+// a given non-conformance. Read-only, minimal columns; rendered on the Issue+// detail. Flat select (no embeds — TS2589 budget).+export async function getChangeOrdersForNonConformance(+ client: SupabaseClient<Database>,+ nonConformanceId: string,+ companyId: string+) {+ return client+ .from("changeOrder")+ .select("id, changeOrderId, name, status")+ .eq("nonConformanceId", nonConformanceId)+ .eq("companyId", companyId)+ .order("createdAt", { ascending: false });+}++// Single-open-CO-per-part guard (V1 — no parallel change orders): the OTHER+// open change orders that already reference a part, excluding the current CO.+// Reuses the canonical G6 query at the open-status filter. A non-empty result+// means adding the part here would create a parallel open CO — the routes (and+// the staging service) reject it.+export async function findOtherOpenChangeOrdersForItem(+ client: SupabaseClient<Database>,+ args: { itemId: string; companyId: string; excludeChangeOrderId: string }+): Promise<ChangeOrderForItem[]> {+ const { data } = await findChangeOrdersForItem(client, {+ itemId: args.itemId,+ companyId: args.companyId,+ statuses: changeOrderOpenStatuses+ });+ return data.filter((co) => co.id !== args.excludeChangeOrderId);+}++// Loader data for the "Change Orders" history section + open-CO alert on an+// item detail page (part/tool/material) — the CO history for the item plus the+// type lookup used to label rows. One shared source so the detail routes don't+// each re-implement the pair of reads.+export async function getItemChangeOrderData(+ client: SupabaseClient<Database>,+ itemId: string,+ companyId: string+) {+ const [changeOrders, changeOrderTypes] = await Promise.all([+ findChangeOrdersForItem(client, { itemId, companyId }),+ getChangeOrderTypesList(client, companyId)+ ]);+ return {+ changeOrders: changeOrders.data,+ changeOrderTypes: changeOrderTypes.data ?? []+ };+}++// =============================================================================+// Change Orders — Actions (freeform tasks; reuse changeOrderActionTask). Any+// user, any stage; non-gating. Split out of changeOrder.service.ts to keep+// each file focused and under the module's 1000-line budget (G4).+// =============================================================================+export async function getChangeOrderActions(+ client: SupabaseClient<Database>,+ changeOrderId: string,+ companyId: string+) {+ return client+ .from("changeOrderActionTask")+ .select("*")+ .eq("changeOrderId", changeOrderId)+ .eq("companyId", companyId)+ .order("sortOrder", { ascending: true })+ .order("createdAt", { ascending: true });+}++export async function updateChangeOrderActionStatus(+ client: SupabaseClient<Database>,+ input: {+ id: string;+ status: (typeof changeOrderTaskStatus)[number];+ userId: string;+ }+) {+ const today = new Date().toISOString().split("T")[0];+ return client+ .from("changeOrderActionTask")+ .update({+ status: input.status,+ completedDate: input.status === "Completed" ? today : null,+ updatedBy: input.userId+ })+ .eq("id", input.id)+ .select("id")+ .single();+}++export async function deleteChangeOrderAction(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("changeOrderActionTask").delete().eq("id", id);+}++// Bulk reorder (drag-sort) — a multi-row write, so Kysely (route passes+// getDatabaseClient()).+export async function updateChangeOrderActionOrder(+ db: Kysely<KyselyDatabase>,+ updates: { id: string; sortOrder: number; updatedBy: string }[]+) {+ return db.transaction().execute(async (trx) => {+ for (const { id, sortOrder, updatedBy } of updates) {+ await trx+ .updateTable("changeOrderActionTask")+ .set({ sortOrder, updatedBy })+ .where("id", "=", id)+ .execute();+ }+ });+}++// =============================================================================+// Change Order Required Actions (the configurable default-action templates the+// config CRUD page manages, and the source new change orders are seeded from).+// =============================================================================+export async function getChangeOrderRequiredActions(+ client: SupabaseClient<Database>,+ companyId: string,+ args?: GenericQueryFilters & { search: string | null }+) {+ let query = client+ .from("changeOrderRequiredAction")+ .select("*", { count: "exact" })+ .eq("companyId", companyId);++ if (args?.search) {+ query = query.ilike("name", `%${args.search}%`);+ }++ if (args) {+ query = setGenericQueryFilters(query, args, [+ { column: "name", ascending: true }+ ]);+ }++ return query;+}++export async function getChangeOrderRequiredActionsList(+ client: SupabaseClient<Database>,+ companyId: string+) {+ return client+ .from("changeOrderRequiredAction")+ .select("id, name")+ .eq("companyId", companyId)+ .eq("active", true)+ .order("name", { ascending: true });+}++export async function getChangeOrderRequiredAction(+ client: SupabaseClient<Database>,+ id: string+) {+ return client+ .from("changeOrderRequiredAction")+ .select("*")+ .eq("id", id)+ .single();+}++export async function upsertChangeOrderRequiredAction(+ client: SupabaseClient<Database>,+ input: {+ id?: string;+ name: string;+ active: boolean;+ companyId: string;+ userId: string;+ }+) {+ if (input.id) {+ return client+ .from("changeOrderRequiredAction")+ .update({+ name: input.name,+ active: input.active,+ updatedBy: input.userId+ })+ .eq("id", input.id)+ .select("id")+ .single();+ }++ return client+ .from("changeOrderRequiredAction")+ .insert({+ name: input.name,+ active: input.active,+ companyId: input.companyId,+ createdBy: input.userId+ })+ .select("id")+ .single();+}++export async function deleteChangeOrderRequiredAction(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("changeOrderRequiredAction").delete().eq("id", id);+}++// Reconcile a change order's action tasks to a chosen set of required-action+// templates — the sidebar's editable "Required Actions" multiselect (mirrors+// Quality's requiredActionIds field). Templates newly selected are instantiated+// (appended); templates deselected have their task removed. Tasks with no+// template link (actionTypeId IS NULL) are left untouched.+export async function setChangeOrderActionTasks(+ client: SupabaseClient<Database>,+ input: {+ changeOrderId: string;+ requiredActionIds: string[];+ companyId: string;+ userId: string;+ }+) {+ const existing = await client+ .from("changeOrderActionTask")+ .select("id, actionTypeId, sortOrder")+ .eq("changeOrderId", input.changeOrderId)+ .eq("companyId", input.companyId);+ if (existing.error) return existing;++ const rows = existing.data ?? [];+ const desired = new Set(input.requiredActionIds);+ const linked = new Set(+ rows.map((r) => r.actionTypeId).filter((id): id is string => Boolean(id))+ );++ const toRemove = rows+ .filter((r) => r.actionTypeId && !desired.has(r.actionTypeId))+ .map((r) => r.id);+ if (toRemove.length > 0) {+ const del = await client+ .from("changeOrderActionTask")+ .delete()+ .in("id", toRemove);+ if (del.error) return del;+ }++ const toAddIds = input.requiredActionIds.filter((id) => !linked.has(id));+ if (toAddIds.length > 0) {+ const templates = await client+ .from("changeOrderRequiredAction")+ .select("id, name")+ .in("id", toAddIds)+ .eq("companyId", input.companyId);+ if (templates.error) return templates;++ const base = rows.reduce((max, r) => Math.max(max, r.sortOrder ?? 0), 0);+ const ins = await client.from("changeOrderActionTask").insert(+ (templates.data ?? []).map((template, index) => ({+ changeOrderId: input.changeOrderId,+ actionTypeId: template.id,+ name: template.name,+ status: "Pending" as const,+ sortOrder: base + index + 1,+ companyId: input.companyId,+ createdBy: input.userId+ }))+ );+ if (ins.error) return ins;+ }++ return { data: null, error: null };+}++// Instantiate one changeOrderActionTask per active template onto a new change+// order. Called by insertChangeOrder; non-gating, so callers ignore a soft+// failure rather than roll back the change order.+export async function seedDefaultChangeOrderActions(+ client: SupabaseClient<Database>,+ input: { changeOrderId: string; companyId: string; userId: string }+) {+ const templates = await getChangeOrderRequiredActionsList(+ client,+ input.companyId+ );+ if (templates.error || !templates.data?.length) return templates;++ return client.from("changeOrderActionTask").insert(+ templates.data.map((template, index) => ({+ changeOrderId: input.changeOrderId,+ actionTypeId: template.id,+ name: template.name,+ status: "Pending" as const,+ sortOrder: index + 1,+ companyId: input.companyId,+ createdBy: input.userId+ }))+ );+}++// =============================================================================+// Change Orders — the reusable method-diff engine (Q5 git-style end-state).+//+// `diffMethod` is a PURE function (no DB access, unit-testable): it compares two+// method snapshots (a `base` = the current live method, a `target` = the CO's+// staged desired end-state) and classifies every material / operation as+// added / removed / modified / unchanged, plus a column-by-column attribute diff.+// The same shape is reused for the pre-release "tips" (staged-vs-live) and the+// post-release oldRev↔newRev redline (Task 17).+//+// `getChangeOrderDiff` is the DB-facing wrapper: for each affected item it reads+// the current source method live + the staged rows, runs `diffMethod`, and also+// returns the manual supersession declarations. Reads are flat selects + JS+// stitch (no composite-FK PostgREST embeds — the erp TS2589 budget; see lessons).+// =============================================================================++// A plain record — DB rows are passed straight through; the engine is generic+// over the shape and only reads the compared field subset + the identity keys.+type Row = Record<string, unknown>;++// Materials are matched by identity: a staged/target row's `sourceMaterialId`+// links it to a base row's `id`. Operations use `sourceOperationId`. Operation+// CHILDREN (steps / parameters / tools) use `sourceId` (the staged child's+// pointer at the live child it was copied from; NULL ⇒ added child line).+const MATERIAL_SOURCE_KEY = "sourceMaterialId";+const OPERATION_SOURCE_KEY = "sourceOperationId";+const CHILD_SOURCE_KEY = "sourceId";++// Never compared — audit / linkage / tenancy columns. The compared set for every+// staged entity is derived as (staged row keys − this set), so adding a mirrored+// business column to a staged table automatically includes it in the diff; only+// genuine noise columns need listing here.+const IGNORED_FIELDS = new Set<string>([+ "id",+ "companyId",+ "changeOrderId",+ "affectedItemId",+ "sourceMaterialId",+ "sourceOperationId",+ "sourceId",+ "stagedOperationId",+ // v2: base and draft rows live on different real methods/operations, so these+ // linkage columns always differ and must never count as a business change.+ "makeMethodId",+ "operationId",+ // The customFields JSON bag differs as a copy artifact (null vs {}), surfacing+ // a meaningless "— → Set" on unrelated edits — never diff it as a whole column.+ "customFields",+ "createdAt",+ "createdBy",+ "updatedAt",+ "updatedBy"+]);++// Loose equality tolerant of the numeric-string ↔ number skew that Supabase+// returns for NUMERIC columns (a live `quantity` may be `"1"` while a staged one+// is `1`). null and undefined are the same "empty" value. JSON/array columns+// (workInstruction, step description, listValues/fileTypes) are separate object+// instances on the live vs staged side, so they're compared structurally — a+// reference check would report every non-null one as changed.+function valuesEqual(a: unknown, b: unknown): boolean {+ if (a === b) return true;+ if (a == null && b == null) return true;+ if (a == null || b == null) return false;+ if (typeof a === "number" || typeof b === "number") {+ const na = typeof a === "number" ? a : Number(a);+ const nb = typeof b === "number" ? b : Number(b);+ if (!Number.isNaN(na) && !Number.isNaN(nb)) return na === nb;+ }+ if (typeof a === "object" && typeof b === "object") {+ return JSON.stringify(a) === JSON.stringify(b);+ }+ return false;+}++// The business columns to compare for a matched (base, target) pair: every key+// the CO actually STAGED (the target row), minus the audit/linkage/tenancy set.+// Deriving from the staged row — not a hand-maintained per-entity list, and not+// the union with the live row — is what keeps the diff in lockstep with the+// mirrored schema: staging copies exactly the changeable columns, live rows carry+// extra columns (makeMethodId, …) that must NOT be compared against `undefined`.+function comparedFields(target: Row): string[] {+ return Object.keys(target).filter((k) => !IGNORED_FIELDS.has(k));+}++// Build the field-level change map for a matched (base, target) pair. Returns+// undefined when nothing changed.+function diffFields(+ base: Row,+ target: Row+): Record<string, { before: unknown; after: unknown }> | undefined {+ const changed: Record<string, { before: unknown; after: unknown }> = {};+ for (const field of comparedFields(target)) {+ if (!valuesEqual(base[field], target[field])) {+ changed[field] = {+ before: base[field] ?? null,+ after: target[field] ?? null+ };+ }+ }+ return Object.keys(changed).length > 0 ? changed : undefined;+}++// Match target rows to base rows by the given source-pointer key, then classify.+// - base row with no target pointing at it ⇒ removed+// - target row with a null/absent source pointer ⇒ added+// - target whose source pointer references a base row ⇒ modified | unchanged+function diffRows(+ base: Row[],+ target: Row[],+ sourceKey: string+): MethodDiffEntry<Row>[] {+ const entries: MethodDiffEntry<Row>[] = [];++ // Index base rows by their id for O(1) lookup, and track which get matched.+ const baseById = new Map<string, Row>();+ for (const row of base) {+ const id = row.id;+ if (typeof id === "string") baseById.set(id, row);+ }+ const matchedBaseIds = new Set<string>();++ for (const targetRow of target) {+ const sourceId = targetRow[sourceKey];+ const baseRow =+ typeof sourceId === "string" ? baseById.get(sourceId) : undefined;++ if (!baseRow) {+ // No live counterpart — a newly-added line.+ entries.push({ status: "added", before: null, after: targetRow });+ continue;+ }++ matchedBaseIds.add(baseRow.id as string);+ const changedFields = diffFields(baseRow, targetRow);+ const status: MethodDiffStatus = changedFields ? "modified" : "unchanged";+ entries.push({+ status,+ before: baseRow,+ after: targetRow,+ ...(changedFields ? { changedFields } : {})+ });+ }++ // Any base row nothing pointed at was dropped from the staged end-state.+ for (const baseRow of base) {+ const id = baseRow.id;+ if (typeof id === "string" && !matchedBaseIds.has(id)) {+ entries.push({ status: "removed", before: baseRow, after: null });+ }+ }++ return entries;+}++// -----------------------------------------------------------------------------+// Operation children (steps / parameters / tools)+// -----------------------------------------------------------------------------++// The three staged child buckets for a single operation, keyed by the staged+// operation's id. Both the live (base) children and the staged (target) children+// share this shape.+export type OperationChildren = {+ steps: Row[];+ parameters: Row[];+ tools: Row[];+};++// OperationChildrenDiff and OperationDiffEntry now live in changeOrder.models+// (imported + re-exported above) so ChangeOrderItemDiff can reference them+// without a circular import. Their shape is unchanged (Row = Record<string,+// unknown>, the same as MethodDiffEntry's generic here).++// Base/target children keyed by operation id. For target (staged) operations the+// key is the staged operation's own id; for base (live) operations it's the live+// operation's id. Matching a staged operation to its base children goes through+// the operation's `sourceOperationId`.+export type ChildrenByOperationId = Record<string, OperationChildren>;++function emptyChildren(): OperationChildren {+ return { steps: [], parameters: [], tools: [] };+}++// Diff one operation's children. `base`/`target` are the live/staged child+// buckets; each bucket is matched by `sourceId` over its own compare-field set.+function diffOperationChildren(+ base: OperationChildren,+ target: OperationChildren+): OperationChildrenDiff {+ return {+ steps: diffRows(base.steps, target.steps, CHILD_SOURCE_KEY),+ parameters: diffRows(base.parameters, target.parameters, CHILD_SOURCE_KEY),+ tools: diffRows(base.tools, target.tools, CHILD_SOURCE_KEY)+ };+}++// Diff operations AND, when child buckets are supplied, attach a per-operation+// child diff. Matches operations exactly like diffRows (by `sourceOperationId`);+// for each entry it pairs the base children (via the matched base operation id)+// with the target children (via the staged operation id) and runs+// `diffOperationChildren`. When no child maps are supplied it degrades to the+// plain operation diff (identical to `diffRows`), so existing callers/tests are+// unaffected.+function diffOperations(+ base: Row[],+ target: Row[],+ baseChildren?: ChildrenByOperationId,+ targetChildren?: ChildrenByOperationId+): OperationDiffEntry[] {+ const entries = diffRows(+ base,+ target,+ OPERATION_SOURCE_KEY+ ) as OperationDiffEntry[];++ if (!baseChildren && !targetChildren) return entries;++ for (const entry of entries) {+ const baseId = (entry.before as { id?: string } | null)?.id;+ const targetId = (entry.after as { id?: string } | null)?.id;+ const baseKids = (baseId && baseChildren?.[baseId]) || emptyChildren();+ const targetKids =+ (targetId && targetChildren?.[targetId]) || emptyChildren();+ entry.children = diffOperationChildren(baseKids, targetKids);+ }++ return entries;+}++// Column-by-column diff of two attribute objects. Every key present in either+// object (minus the ignored audit/linkage set) is compared; each changed column+// becomes one MethodDiffEntry whose `changedFields` holds the single field. When+// nothing changed a single "unchanged" entry is returned so callers can render+// "no attribute changes" uniformly.+function diffAttributes(+ base: Row | null,+ target: Row | null+): MethodDiffEntry<Row>[] {+ const b = base ?? {};+ const t = target ?? {};+ // Compare only the columns the CO staged (target), minus audit/linkage — the+ // live source select carries extra columns (e.g. modelUploadId) the staged row+ // doesn't mirror, and comparing those against `undefined` would be spurious.+ const keys = target ? comparedFields(target) : [];++ const entries: MethodDiffEntry<Row>[] = [];+ for (const key of keys) {+ if (valuesEqual(b[key], t[key])) continue;+ entries.push({+ status: "modified",+ before: base,+ after: target,+ changedFields: {+ [key]: { before: b[key] ?? null, after: t[key] ?? null }+ }+ });+ }++ if (entries.length === 0) {+ return [{ status: "unchanged", before: base, after: target }];+ }+ return entries;+}++// -----------------------------------------------------------------------------+// The pure diff engine+// -----------------------------------------------------------------------------++export type DiffMethodInput = {+ baseMaterials: Row[];+ targetMaterials: Row[];+ baseOperations: Row[];+ targetOperations: Row[];+ baseAttributes?: Row | null;+ targetAttributes?: Row | null;+ // Optional per-operation children (steps/parameters/tools), keyed by operation+ // id (live op id for base, staged op id for target). When omitted, operation+ // entries carry no `children` and the result is identical to the pre-Task-16+ // shape.+ baseOperationChildren?: ChildrenByOperationId;+ targetOperationChildren?: ChildrenByOperationId;+};++export type DiffMethodResult = {+ materials: MethodDiffEntry<Row>[];+ // Operations may carry an optional child-level diff (see OperationDiffEntry).+ // OperationDiffEntry is a superset of MethodDiffEntry<Row>, so consumers typed+ // against MethodDiffEntry<Row>[] keep working.+ operations: OperationDiffEntry[];+ attributes: MethodDiffEntry<Row>[];+};++// PURE. Compares two method snapshots. No DB access — the caller supplies plain+// rows (live method rows as `base`, CO-staged rows as `target`), and optionally+// the per-operation child buckets to also diff steps/parameters/tools.+export function diffMethod(input: DiffMethodInput): DiffMethodResult {+ return {+ materials: diffRows(+ input.baseMaterials,+ input.targetMaterials,+ MATERIAL_SOURCE_KEY+ ),+ operations: diffOperations(+ input.baseOperations,+ input.targetOperations,+ input.baseOperationChildren,+ input.targetOperationChildren+ ),+ attributes: diffAttributes(+ input.baseAttributes ?? null,+ input.targetAttributes ?? null+ )+ };+}++// -----------------------------------------------------------------------------+// DB-facing wrapper+// -----------------------------------------------------------------------------++export type ChangeOrderDiff = {+ items: ChangeOrderItemDiff[];+};++// Editable item attribute columns compared for the attribute diff. `mpn` lives on+// item; the item group (itemPostingGroupId) lives on itemCost and is merged in+// separately by readItemAttributes. `active` is intentionally excluded — a CO+// draft is created inactive until release, so it always differs (not a real edit).+const ITEM_ATTRIBUTE_COLUMNS =+ "name, description, unitOfMeasureCode, itemTrackingType, defaultMethodType, replenishmentSystem, sourcingType, requiresInspection, thumbnailPath, mpn";++// Read one make method's materials + operations + per-operation children (real+// method tables — the v2 substrate). Empty for a null makeMethodId (e.g. a Buy+// item with no method, or before a draft exists).+async function readMethodRows(+ client: SupabaseClient<Database>,+ makeMethodId: string | null,+ companyId: string+): Promise<{+ materials: Row[];+ operations: Row[];+ children: ChildrenByOperationId;+ error: { message: string } | null;+}> {+ const empty = { materials: [], operations: [], children: {}, error: null };+ if (!makeMethodId) return empty;++ const [materials, operations] = await Promise.all([+ client+ .from("methodMaterial")+ .select("*")+ .eq("makeMethodId", makeMethodId)+ .eq("companyId", companyId)+ .order("order", { ascending: true }),+ client+ .from("methodOperation")+ .select("*")+ .eq("makeMethodId", makeMethodId)+ .eq("companyId", companyId)+ .order("order", { ascending: true })+ ]);+ if (materials.error) return { ...empty, error: materials.error };+ if (operations.error) return { ...empty, error: operations.error };++ const ops = (operations.data ?? []) as Row[];+ const children: ChildrenByOperationId = {};+ const opIds = ops+ .map((o) => o.id)+ .filter((id): id is string => typeof id === "string");++ if (opIds.length > 0) {+ const [steps, parameters, tools] = await Promise.all([+ client+ .from("methodOperationStep")+ .select("*")+ .in("operationId", opIds)+ .eq("companyId", companyId),+ client+ .from("methodOperationParameter")+ .select("*")+ .in("operationId", opIds)+ .eq("companyId", companyId),+ client+ .from("methodOperationTool")+ .select("*")+ .in("operationId", opIds)+ .eq("companyId", companyId)+ ]);+ if (steps.error) return { ...empty, error: steps.error };+ if (parameters.error) return { ...empty, error: parameters.error };+ if (tools.error) return { ...empty, error: tools.error };++ for (const id of opIds)+ children[id] = { steps: [], parameters: [], tools: [] };+ for (const r of (steps.data ?? []) as Row[]) {+ const op = r.operationId;+ if (typeof op === "string") children[op]?.steps.push(r);+ }+ for (const r of (parameters.data ?? []) as Row[]) {+ const op = r.operationId;+ if (typeof op === "string") children[op]?.parameters.push(r);+ }+ for (const r of (tools.data ?? []) as Row[]) {+ const op = r.operationId;+ if (typeof op === "string") children[op]?.tools.push(r);+ }+ }++ return {+ materials: (materials.data ?? []) as Row[],+ operations: ops,+ children,+ error: null+ };+}++// The v2 draft method is created by copying the base method, so it initially+// mirrors the base 1:1 with NO back-pointer ids. We reconstruct the source+// pointers the pure engine expects by matching each target row to a base row on+// a natural key (materials → component itemId, operations → order, children →+// name/key/toolId), first-unmatched-wins. An unmatched target row is an add; an+// unmatched base row is a remove.+function correlate(+ base: Row[],+ target: Row[],+ keyField: string,+ sourceKey: string+): void {+ const usedBaseIds = new Set<string>();+ for (const t of target) {+ const key = t[keyField];+ const match = base.find(+ (b) =>+ b[keyField] === key &&+ typeof b.id === "string" &&+ !usedBaseIds.has(b.id)+ );+ if (match && typeof match.id === "string") {+ usedBaseIds.add(match.id);+ t[sourceKey] = match.id;+ } else {+ t[sourceKey] = null;+ }+ }+}++async function readItemAttributes(+ client: SupabaseClient<Database>,+ itemId: string,+ companyId: string+): Promise<Row | null> {+ const [item, cost] = await Promise.all([+ client+ .from("item")+ .select(ITEM_ATTRIBUTE_COLUMNS)+ .eq("id", itemId)+ .eq("companyId", companyId)+ .maybeSingle(),+ // The item group lives on itemCost, not item — merge it in so it diffs too.+ client+ .from("itemCost")+ .select("itemPostingGroupId")+ .eq("itemId", itemId)+ .eq("companyId", companyId)+ .maybeSingle()+ ]);+ if (!item.data) return null;+ return {+ ...(item.data as Row),+ itemPostingGroupId: cost.data?.itemPostingGroupId ?? null+ };+}++// A Revision/New Part draft item starts with no supplier parts (the source's+// aren't copied); the ones the user sets up on the CO line are surfaced as `added`+// entries. Mirrors getSupplierParts (items.service) — active rows for the item.+async function readDraftSupplierParts(+ client: SupabaseClient<Database>,+ itemId: string,+ companyId: string+): Promise<{+ data: MethodDiffEntry<Row>[];+ error: { message: string } | null;+}> {+ const res = await client+ .from("supplierPart")+ .select("*")+ .eq("itemId", itemId)+ .eq("companyId", companyId)+ .eq("active", true);+ if (res.error) return { data: [], error: res.error };+ return {+ data: (res.data ?? []).map((row) => ({+ status: "added" as const,+ before: null,+ after: row as Row+ })),+ error: null+ };+}++// Resolve item-group ids → their names for readable diff display.+async function readPostingGroupNames(+ client: SupabaseClient<Database>,+ ids: string[],+ companyId: string+): Promise<Map<string, string>> {+ const map = new Map<string, string>();+ const unique = [...new Set(ids)].filter((id) => id.length > 0);+ if (unique.length === 0) return map;+ const groups = await client+ .from("itemPostingGroup")+ .select("id, name")+ .in("id", unique)+ .eq("companyId", companyId);+ for (const g of groups.data ?? []) {+ if (g.id && g.name) map.set(g.id, g.name);+ }+ return map;+}++// Resolve component item UUIDs → human-readable ids (e.g. `P000123.A`). The diff+// viewer labels each BOM line by its component; a `methodMaterial` row carries only+// the item UUID, and the client `useItems` store can miss a just-minted/placeholder+// component. Resolving here (server-side, guaranteed present) makes the label+// store-independent. Flat select scoped by companyId.+async function readItemReadableIds(+ client: SupabaseClient<Database>,+ itemIds: string[],+ companyId: string+): Promise<Map<string, string>> {+ const map = new Map<string, string>();+ const unique = [...new Set(itemIds)].filter((id) => id.length > 0);+ if (unique.length === 0) return map;+ const items = await client+ .from("item")+ .select("id, readableIdWithRevision")+ .in("id", unique)+ .eq("companyId", companyId);+ for (const row of items.data ?? []) {+ if (row.id && row.readableIdWithRevision)+ map.set(row.id, row.readableIdWithRevision);+ }+ return map;+}++// Stamp the resolved readable id onto each material diff row (before + after) under+// `itemReadableId`, so the read-only viewer can label the line without a store+// lookup. Applied AFTER diffMethod so it never counts as a business-field change.+function stampMaterialReadableIds(+ materials: MethodDiffEntry<Row>[],+ readableIds: Map<string, string>+): void {+ for (const entry of materials) {+ for (const row of [entry.before, entry.after]) {+ const itemId = (row as { itemId?: string } | null)?.itemId;+ if (row && typeof itemId === "string") {+ const readable = readableIds.get(itemId);+ if (readable) (row as Row).itemReadableId = readable;+ }+ }+ }+}++// A methodOperationTool row references a Tool item by `toolId` (a UUID). Stamp the+// resolved readable id onto each tool child row (before + after) under+// `toolReadableId` so the viewer labels the tool by its readable id, not the UUID.+function stampToolReadableIds(+ operations: OperationDiffEntry[],+ readableIds: Map<string, string>+): void {+ for (const op of operations) {+ for (const entry of op.children?.tools ?? []) {+ for (const row of [entry.before, entry.after]) {+ const toolId = (row as { toolId?: string } | null)?.toolId;+ if (row && typeof toolId === "string") {+ const readable = readableIds.get(toolId);+ if (readable) (row as Row).toolReadableId = readable;+ }+ }+ }+ }+}++// Operation rows reference a process / work center / procedure / supplier process+// by UUID. Resolve those to human names and rewrite them IN PLACE — both the+// changedFields (old→new) and the before/after rows (add/remove property lists) —+// so the diff and merge UIs read "CNC Milling", not a raw id. Display-only, applied+// AFTER diffMethod (so it never counts as a business-field change); the release+// apply re-reads rows by id, so mutating these display rows is safe.+const OPERATION_REF_FIELDS = [+ "processId",+ "workCenterId",+ "procedureId",+ "operationSupplierProcessId"+] as const;+const OPERATION_REF_FIELD_SET = new Set<string>(OPERATION_REF_FIELDS);++async function stampOperationRefNames(+ client: SupabaseClient<Database>,+ operations: OperationDiffEntry[],+ companyId: string+): Promise<void> {+ // Gather every referenced id per field, from both the rows and changedFields.+ const collected: Record<string, Set<string>> = {+ processId: new Set(),+ workCenterId: new Set(),+ procedureId: new Set(),+ operationSupplierProcessId: new Set()+ };+ const addFrom = (row: Row | null) => {+ if (!row) return;+ for (const f of OPERATION_REF_FIELDS) {+ const v = row[f];+ if (typeof v === "string" && v) collected[f].add(v);+ }+ };+ for (const op of operations) {+ addFrom(op.before as Row | null);+ addFrom(op.after as Row | null);+ for (const [f, cf] of Object.entries(op.changedFields ?? {})) {+ if (!OPERATION_REF_FIELD_SET.has(f)) continue;+ if (typeof cf.before === "string" && cf.before)+ collected[f].add(cf.before);+ if (typeof cf.after === "string" && cf.after) collected[f].add(cf.after);+ }+ }++ const names = new Map<string, string>(); // id → display name (any ref type)+ const load = async (+ table: "process" | "workCenter" | "procedure",+ ids: Set<string>+ ) => {+ const unique = [...ids];+ if (unique.length === 0) return;+ const rows = await client+ .from(table)+ .select("id, name")+ .in("id", unique)+ .eq("companyId", companyId);+ for (const r of rows.data ?? []) {+ if (r.id && r.name) names.set(r.id, r.name);+ }+ };++ // A supplier process has no name of its own — resolve it to its process name+ // (its underlying process ids join the process lookup below).+ const supplierProcessIds = [...collected.operationSupplierProcessId];+ const supplierProcessToProcess = new Map<string, string>();+ if (supplierProcessIds.length > 0) {+ const sp = await client+ .from("supplierProcess")+ .select("id, processId")+ .in("id", supplierProcessIds)+ .eq("companyId", companyId);+ for (const r of sp.data ?? []) {+ if (r.id && r.processId) {+ supplierProcessToProcess.set(r.id, r.processId);+ collected.processId.add(r.processId);+ }+ }+ }++ await Promise.all([+ load("process", collected.processId),+ load("workCenter", collected.workCenterId),+ load("procedure", collected.procedureId)+ ]);+ for (const [spId, processId] of supplierProcessToProcess) {+ const name = names.get(processId);+ if (name) names.set(spId, name);+ }++ const rewrite = (row: Row | null) => {+ if (!row) return;+ for (const f of OPERATION_REF_FIELDS) {+ const v = row[f];+ if (typeof v === "string" && names.has(v)) row[f] = names.get(v);+ }+ };+ for (const op of operations) {+ rewrite(op.before as Row | null);+ rewrite(op.after as Row | null);+ for (const [f, cf] of Object.entries(op.changedFields ?? {})) {+ if (!OPERATION_REF_FIELD_SET.has(f)) continue;+ if (typeof cf.before === "string" && names.has(cf.before))+ cf.before = names.get(cf.before);+ if (typeof cf.after === "string" && names.has(cf.after))+ cf.after = names.get(cf.after);+ }+ }+}++// For every affected item: read the base (source Active) method as `base` and the+// CO-owned Draft method as `target` (both REAL method tables), correlate by+// natural keys, run the pure `diffMethod`, and collect. Also returns the manual+// supersession declarations. Flat selects scoped by companyId (no embeds).+export async function getChangeOrderDiff(+ client: SupabaseClient<Database>,+ changeOrderId: string,+ companyId: string+): Promise<{ data: ChangeOrderDiff; error: { message: string } | null }> {+ const affected = await getChangeOrderAffectedItems(+ client,+ changeOrderId,+ companyId+ );+ if (affected.error) return { data: { items: [] }, error: affected.error };++ const items: ChangeOrderItemDiff[] = [];++ for (const affectedItem of affected.data) {+ const base = await readMethodRows(+ client,+ affectedItem.baseMakeMethodId,+ companyId+ );+ if (base.error) return { data: { items: [] }, error: base.error };+ const target = await readMethodRows(+ client,+ affectedItem.draftMakeMethodId,+ companyId+ );+ if (target.error) return { data: { items: [] }, error: target.error };++ // Reconstruct source pointers by natural key.+ correlate(base.materials, target.materials, "itemId", MATERIAL_SOURCE_KEY);+ correlate(+ base.operations,+ target.operations,+ "order",+ OPERATION_SOURCE_KEY+ );+ for (const top of target.operations) {+ const baseOpId = top[OPERATION_SOURCE_KEY];+ const topId = top.id;+ if (typeof baseOpId !== "string" || typeof topId !== "string") continue;+ const bKids = base.children[baseOpId];+ const tKids = target.children[topId];+ if (!bKids || !tKids) continue;+ correlate(bKids.steps, tKids.steps, "name", CHILD_SOURCE_KEY);+ correlate(bKids.parameters, tKids.parameters, "key", CHILD_SOURCE_KEY);+ correlate(bKids.tools, tKids.tools, "toolId", CHILD_SOURCE_KEY);+ }++ // Attribute diff: base = source item columns; target = the draft item's+ // columns. For a Version the draft is on the same item, so there is no+ // attribute change (Q2) and both sides read the same row.+ const draftItemId = affectedItem.newItemId ?? affectedItem.itemId;+ const baseAttributes = await readItemAttributes(+ client,+ affectedItem.itemId,+ companyId+ );+ const targetAttributes =+ draftItemId === affectedItem.itemId+ ? baseAttributes+ : await readItemAttributes(client, draftItemId, companyId);++ // Supplier parts on the draft item (Revision/New Part only; a Version shares+ // the live item's suppliers, which are not a CO change). Surfaced as additions.+ let supplierParts: MethodDiffEntry<Row>[] = [];+ if (draftItemId !== affectedItem.itemId) {+ const sp = await readDraftSupplierParts(client, draftItemId, companyId);+ if (sp.error) return { data: { items: [] }, error: sp.error };+ supplierParts = sp.data;+ }++ const diff = diffMethod({+ baseMaterials: base.materials,+ targetMaterials: target.materials,+ baseOperations: base.operations,+ targetOperations: target.operations,+ baseAttributes,+ targetAttributes,+ baseOperationChildren: base.children,+ targetOperationChildren: target.children+ });++ // Label BOM lines by their component's readable id and BOP tools by the tool+ // item's readable id (both reference item UUIDs) — store-independent. One+ // batch resolve over every referenced item id.+ const componentIds = [...base.materials, ...target.materials]+ .map((m) => m.itemId)+ .filter((id): id is string => typeof id === "string");+ const toolIds = diff.operations.flatMap((op) =>+ (op.children?.tools ?? [])+ .flatMap((tool) => [tool.before, tool.after])+ .map((row) => (row as { toolId?: string } | null)?.toolId)+ .filter((id): id is string => typeof id === "string")+ );+ const readableIds = await readItemReadableIds(+ client,+ [...componentIds, ...toolIds],+ companyId+ );+ stampMaterialReadableIds(diff.materials, readableIds);+ stampToolReadableIds(diff.operations, readableIds);+ await stampOperationRefNames(client, diff.operations, companyId);++ // Resolve the item-group id → name so the attribute diff reads "Group A →+ // Group B" instead of opaque ids.+ const groupIds = diff.attributes.flatMap((a) => {+ const cf = a.changedFields?.itemPostingGroupId;+ return cf+ ? [cf.before, cf.after].filter(+ (v): v is string => typeof v === "string"+ )+ : [];+ });+ if (groupIds.length > 0) {+ const names = await readPostingGroupNames(client, groupIds, companyId);+ for (const a of diff.attributes) {+ const cf = a.changedFields?.itemPostingGroupId;+ if (!cf) continue;+ if (typeof cf.before === "string")+ cf.before = names.get(cf.before) ?? cf.before;+ if (typeof cf.after === "string")+ cf.after = names.get(cf.after) ?? cf.after;+ }+ }++ items.push({+ affectedItemId: affectedItem.id,+ itemId: affectedItem.itemId,+ materials: diff.materials,+ operations: diff.operations,+ attributes: diff.attributes,+ supplierParts+ });+ }++ return { data: { items }, error: null };+}diff --git a/apps/erp/app/modules/items/types.ts b/apps/erp/app/modules/items/types.tsindex 9c1a7e0b62..4537f72fc9 100644--- a/apps/erp/app/modules/items/types.ts+++ b/apps/erp/app/modules/items/types.ts@@ -1,5 +1,8 @@import type { Database } from "@carbon/database";import type {+ getChangeOrder,+ getChangeOrders,+ getChangeOrderTypes,getConfigurationParameters,getConfigurationRules,getConsumable,@@ -36,6 +39,35 @@ import type {getUnitOfMeasuresList} from "./items.service";+export type ItemRevisionStatus =+ Database["public"]["Enums"]["itemRevisionStatus"];++// The single change order (base table, NOT-NULL columns) — the shape detail+// routes and the properties/header/explorer components consume via useRouteData.+export type ChangeOrder = NonNullable<+ Awaited<ReturnType<typeof getChangeOrder>>["data"]+>;++// A row of the change-orders LIST — the `changeOrders` view, which additionally+// rolls up `itemIds` (text[]) and `affectedItems` (jsonb) per CO. View columns are+// all nullable, so this is a distinct type from the single-CO `ChangeOrder`.+export type ChangeOrderListItem = NonNullable<+ Awaited<ReturnType<typeof getChangeOrders>>["data"]+>[number];++export type ChangeOrderType = NonNullable<+ Awaited<ReturnType<typeof getChangeOrderTypes>>["data"]+>[number];++export type ChangeOrderStatus =+ Database["public"]["Enums"]["changeOrderStatus"];++export type ChangeOrderActionTask =+ Database["public"]["Tables"]["changeOrderActionTask"]["Row"];++export type ChangeOrderRequiredAction =+ Database["public"]["Tables"]["changeOrderRequiredAction"]["Row"];+export type MaterialConfigurationData = {materialId?: string;materialSubstanceId?: string;diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/AffectedItemDetail.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/AffectedItemDetail.tsxnew file mode 100644index 0000000000..5bcf57991e--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/AffectedItemDetail.tsx@@ -0,0 +1,470 @@+import { ValidatedForm } from "@carbon/form";+import {+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ HStack,+ Status,+ VStack+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useState } from "react";+import { useFetcher } from "react-router";+import { CadModel, DeferredFiles } from "~/components";+import { DatePicker, Hidden, Select, Submit } from "~/components/Form";+import { path } from "~/utils/path";+import type { SupersessionMode } from "../../items.models";+import {+ changeOrderAffectedItemChangeTypeValidator,+ changeOrderAffectedItemCutoverValidator,+ changeOrderChangeTypes,+ supersessionModeMeta,+ supersessionModes+} from "../../items.models";+import type { ChangeOrderAffectedItemWithLabel } from "../../items.service";+import {+ BillOfMaterial,+ BillOfProcess,+ ItemDocuments,+ SupplierParts+} from "../Item";+import PartProperties from "../Parts/PartProperties";+import type { AffectedItemDraft } from "./affectedItem.types";+import ChangeOrderDiffViewer from "./ChangeOrderDiffViewer";+import ChangeTypeBadge from "./ChangeTypeBadge";+import ItemLink from "./ItemLink";++const supersessionModeOptions = supersessionModes.map((value) => ({+ value,+ label: <Status color={supersessionModeMeta[value].color}>{value}</Status>+}));++const changeTypeOptions = changeOrderChangeTypes.map((c) => ({+ value: c,+ label: c+}));++// The affected-item line detail: everything about the ONE selected affected item,+// unwrapped from a single card into as many standalone cards as the change needs+// (no tabs). Change Type comes first (carrying the item identity + remove), then+// Part Supersession (cutover) right under it, the read-only Changes diff,+// Properties, Supplier Parts, the method cards (BillOfMaterial / BillOfProcess,+// which self-card), then Files + CAD Model (Revision / New Part) after the method+// cards.+export default function AffectedItemDetail({+ changeOrderId,+ affected,+ isDisabled+}: {+ changeOrderId: string;+ affected: AffectedItemDraft;+ isDisabled: boolean;+}) {+ const { t } = useLingui();++ const affectedItem = affected.affectedItem;+ const partData = affected.partData;+ const label = affectedItem.item;+ const changeType = affectedItem.changeType;+ // Change-type availability keys off the SOURCE item: a Version is a method+ // version of the affected part itself, meaningless when that part is purchased.+ const sourceIsManufactured = label?.replenishmentSystem !== "Buy";+ // BoM/BoP visibility keys off the item actually being edited/released — for a+ // New Part that's the new item (whose replenishment the user can flip in the+ // Properties card), for a Version/Revision it's the same/derived item.+ const draftIsManufactured =+ (affected.partData?.partSummary?.replenishmentSystem ??+ label?.replenishmentSystem) !== "Buy";+ // BoM/BoP is now editable for ANY change type on a manufactured draft — Version,+ // Revision, Replacement Part, and New Part alike (client ask: allow editing+ // BoM/BoP on revisions; a net-new New Part authors its recipe from scratch).+ const showBomBop = draftIsManufactured;+ // Attribute editing (Properties card) applies to every type that mints/derives+ // a real item: Revision, Replacement Part, and net-new New Part. Version edits+ // the same item's method only.+ const showAttributes =+ changeType === "Revision" ||+ changeType === "Replacement Part" ||+ changeType === "New Part";+ // Supplier-part management for a purchasable draft item (Revision / Replacement+ // Part / New Part on a Part) — so a Buy draft doesn't release un-purchasable.+ // The grid's create/edit drawers are child routes of the line detail; data+ // comes from partData.supplierParts (already loaded by the $id loader).+ const showSupplierParts =+ showAttributes &&+ affected.partData !== null &&+ ["Buy", "Buy and Make"].includes(+ affected.partData.partSummary?.replenishmentSystem ?? ""+ );+ // Cutover config exists only when there is a predecessor to supersede — Revision+ // (oldRev→newRev) and Replacement Part (affected→new). A net-new New Part has no+ // predecessor, and Version edits the same item, so neither shows cutover.+ const showCutover = changeType !== "Version" && changeType !== "New Part";+ // A purchased item under a type that would otherwise expose BoM/BoP: explain it.+ // The attr-editing types (Revision / Replacement Part / New Part) are attrs/docs+ // for a Buy item — no note needed.+ const showBuyNote =+ !draftIsManufactured &&+ changeType !== "Revision" &&+ changeType !== "Replacement Part" &&+ changeType !== "New Part";++ return (+ <VStack spacing={4} className="w-full">+ {/* Change Type — the first card, carrying the item identity + remove. */}+ <Card>+ <CardHeader>+ <HStack className="justify-between w-full">+ <CardTitle>+ <ItemLink+ itemId={affectedItem.itemId}+ type={label?.type}+ className="text-base font-medium"+ >+ {label?.readableIdWithRevision ??+ label?.readableId ??+ affectedItem.itemId}+ </ItemLink>+ </CardTitle>+ {/* Single combined change-type + draft-version badge (e.g. "Version 2"+ / "Revision 2" / "New"), replacing the old delete icon here.+ Deletion stays available from the explorer row's ⋮ menu. */}+ <ChangeTypeBadge+ changeType={changeType}+ version={affected.makeMethod?.version}+ />+ </HStack>+ {label?.name && (+ <span className="text-xs text-muted-foreground">{label.name}</span>+ )}+ </CardHeader>+ <CardContent>+ <VStack spacing={4}>+ <ChangeTypeControl+ changeOrderId={changeOrderId}+ affected={affectedItem}+ isManufactured={sourceIsManufactured}+ isDisabled={isDisabled}+ />+ {showBuyNote && (+ <p className="text-sm text-muted-foreground">+ <Trans>+ This is a purchased item — it has no BoM/BoP; only its+ attributes and documents can change.+ </Trans>+ </p>+ )}+ </VStack>+ </CardContent>+ </Card>++ {/* Part Supersession — cutover config (types with a predecessor to+ supersede), surfaced right under the Change Type card. */}+ {showCutover && (+ <Card>+ <CardHeader>+ <CardTitle>+ <Trans>Part Supersession</Trans>+ </CardTitle>+ </CardHeader>+ <CardContent>+ <CutoverControl+ changeOrderId={changeOrderId}+ affected={affectedItem}+ isDisabled={isDisabled}+ />+ </CardContent>+ </Card>+ )}++ {/* Changes — the read-only end-state diff, surfaced at the top right under+ the item header. */}+ <Card>+ <CardHeader>+ <CardTitle>+ <Trans>Changes</Trans>+ </CardTitle>+ </CardHeader>+ <CardContent>+ <ChangeOrderDiffViewer bare diff={affected.diff} />+ </CardContent>+ </Card>++ {/* Properties — item attributes (Revision / New Part only). */}+ {showAttributes && (+ <Card>+ <CardHeader>+ <CardTitle>+ <Trans>Properties</Trans>+ </CardTitle>+ </CardHeader>+ <CardContent>+ {affected.partData ? (+ <PartProperties+ embedded+ layout="form"+ section="properties"+ data={affected.partData}+ isReadOnly={isDisabled}+ changeType={changeType}+ />+ ) : (+ <p className="text-sm text-muted-foreground py-2">+ <Trans>No editable properties for this item.</Trans>+ </p>+ )}+ </CardContent>+ </Card>+ )}++ {/* Supplier Parts — purchasing setup for a Buy draft item (renders its own+ card + the Outlet hosting the create/edit drawer child routes). */}+ {showSupplierParts && affected.partData && (+ <SupplierParts+ supplierParts={affected.partData.supplierParts}+ isReadOnly={isDisabled}+ deleteSupplierPath={(supplierPartId) =>+ path.to.changeOrderDeleteSupplierPart(+ changeOrderId,+ affectedItem.id,+ supplierPartId+ )+ }+ />+ )}++ {/* Bill of Materials + Bill of Process — each renders its own card. */}+ {showBomBop &&+ (affected.makeMethod ? (+ <>+ <BillOfMaterial+ key={`bom:${affected.makeMethod.id}`}+ makeMethod={affected.makeMethod}+ parentItemId={affected.draftItemId}+ // @ts-expect-error mapped loader shape (mirrors the part route)+ materials={affected.methodMaterials}+ operations={affected.methodOperations}+ configurable={affected.configurable}+ configurationRules={affected.configurationRules}+ parameters={affected.parameters}+ replenishmentSystem={label?.replenishmentSystem ?? undefined}+ revisionStatus={affected.revisionStatus}+ releaseControl={affected.releaseControl ?? undefined}+ />+ <BillOfProcess+ key={`bop:${affected.makeMethod.id}`}+ makeMethod={affected.makeMethod}+ materials={affected.methodMaterials}+ // @ts-expect-error mapped loader shape (mirrors the part route)+ operations={affected.methodOperations}+ configurable={affected.configurable}+ configurationRules={affected.configurationRules}+ parameters={affected.parameters}+ tags={affected.tags}+ revisionStatus={affected.revisionStatus}+ releaseControl={affected.releaseControl ?? undefined}+ />+ </>+ ) : (+ <Card>+ <CardContent>+ <p className="text-sm text-muted-foreground py-2">+ <Trans>No draft make method for this item yet.</Trans>+ </p>+ </CardContent>+ </Card>+ ))}++ {/* Files + CAD Model — attachments on the draft item (Revision / New Part+ only), after the method cards. Same components as the part detail page:+ ItemDocuments (which self-cards + lists the model row) and the CadModel+ viewer/uploader. */}+ {showAttributes &&+ (partData ? (+ <>+ <DeferredFiles resolve={partData.files}>+ {(resolvedFiles) => (+ <ItemDocuments+ files={resolvedFiles}+ itemId={partData.itemId}+ modelUpload={partData.partSummary ?? undefined}+ type="Part"+ isReadOnly={isDisabled}+ />+ )}+ </DeferredFiles>+ <CadModel+ isReadOnly={isDisabled}+ metadata={{ itemId: partData.itemId }}+ modelPath={partData.partSummary?.modelPath ?? null}+ title={t`CAD Model`}+ />+ </>+ ) : (+ <Card>+ <CardHeader>+ <CardTitle>+ <Trans>Files</Trans>+ </CardTitle>+ </CardHeader>+ <CardContent>+ <p className="text-sm text-muted-foreground py-2">+ <Trans>No files for this item.</Trans>+ </p>+ </CardContent>+ </Card>+ ))}+ </VStack>+ );+}++// Per-affected-item change-type selector. Switching rebuilds the CO-owned Draft+// for the new type (edits reset — Q2). Explicit Apply avoids accidental resets.+function ChangeTypeControl({+ changeOrderId,+ affected,+ isManufactured,+ isDisabled+}: {+ changeOrderId: string;+ affected: ChangeOrderAffectedItemWithLabel;+ isManufactured: boolean;+ isDisabled: boolean;+}) {+ const { t } = useLingui();+ const fetcher = useFetcher<{ success: boolean }>();+ // Track the picked value so the Apply button (and its "resets edits" warning)+ // only appear once the user selects a type different from the saved one.+ const [selected, setSelected] = useState<string>(affected.changeType);+ const hasChanged = selected !== affected.changeType;+ // Version = a manufacturing-method change, meaningless for a Buy item — don't+ // offer it there (Buy items default to Revision on add). New Part is net-new by+ // construction — it can't be switched to/from, so it's never a switcher option.+ const options = (+ isManufactured+ ? changeTypeOptions+ : changeTypeOptions.filter((o) => o.value !== "Version")+ ).filter((o) => o.value !== "New Part");++ // A New Part affected item shows its type read-only (no switcher): converting a+ // net-new part into a predecessor-bound type (or vice-versa) is contradictory.+ if (affected.changeType === "New Part") return null;++ return (+ <ValidatedForm+ fetcher={fetcher}+ method="post"+ action={path.to.changeOrderAffectedChangeType(changeOrderId, affected.id)}+ validator={changeOrderAffectedItemChangeTypeValidator}+ defaultValues={{ id: affected.id, changeType: affected.changeType }}+ className="w-full"+ >+ <Hidden name="id" value={affected.id} />+ <HStack className="w-full items-end gap-2">+ <div className="w-52">+ <Select+ name="changeType"+ label={t`Change type`}+ termId="change-order-change-type"+ options={options}+ isReadOnly={isDisabled}+ onChange={(option) =>+ setSelected(option?.value ?? affected.changeType)+ }+ />+ </div>+ {!isDisabled && hasChanged && (+ <>+ <Submit withBlocker={false} isDisabled={fetcher.state !== "idle"}>+ <Trans>Apply</Trans>+ </Submit>+ <span className="text-xs text-muted-foreground pb-2">+ <Trans>Changing type resets this item's draft edits.</Trans>+ </span>+ </>+ )}+ </HStack>+ </ValidatedForm>+ );+}++function CutoverControl({+ changeOrderId,+ affected,+ isDisabled+}: {+ changeOrderId: string;+ affected: ChangeOrderAffectedItemWithLabel;+ isDisabled: boolean;+}) {+ const { t } = useLingui();+ const fetcher = useFetcher<{ success: boolean }>();+ // Drives the mode-description helper text, reusing the canonical supersession+ // presentation so the CO cutover matches the item supersession form exactly.+ const [mode, setMode] = useState<SupersessionMode | "">(+ (affected.supersessionMode as SupersessionMode | null) ?? ""+ );++ return (+ <ValidatedForm+ fetcher={fetcher}+ method="post"+ action={path.to.changeOrderAffectedCutover(changeOrderId, affected.id)}+ validator={changeOrderAffectedItemCutoverValidator}+ defaultValues={{+ id: affected.id,+ supersessionMode: affected.supersessionMode,+ discontinuationDate: affected.discontinuationDate ?? "",+ successorEffectivityDate: affected.successorEffectivityDate ?? ""+ }}+ className="w-full"+ >+ <Hidden name="id" value={affected.id} />+ <VStack spacing={2}>+ <HStack className="w-full items-start gap-2 flex-wrap">+ <div className="w-52">+ <Select+ name="supersessionMode"+ label={t`Supersession Mode`}+ termId="supersession-mode"+ options={supersessionModeOptions}+ isReadOnly={isDisabled}+ helperText={+ mode ? supersessionModeMeta[mode].description : undefined+ }+ onChange={(option) =>+ setMode((option?.value as SupersessionMode) ?? "")+ }+ />+ </div>+ <div className="w-44">+ <DatePicker+ name="discontinuationDate"+ label={t`Discontinuation date`}+ helperText={t`Stop raising purchase orders after this date`}+ isDisabled={isDisabled}+ />+ </div>+ <div className="w-44">+ <DatePicker+ name="successorEffectivityDate"+ label={t`Successor effectivity`}+ helperText={t`When MRP uses the successor for new demand`}+ isDisabled={isDisabled}+ />+ </div>+ {!isDisabled && (+ // Fields align-start; nudge the label-less Save down so it lines up+ // with the inputs rather than the labels.+ <div className="pt-8">+ <Submit withBlocker={false} isDisabled={fetcher.state !== "idle"}>+ <Trans>Save</Trans>+ </Submit>+ </div>+ )}+ </HStack>+ </VStack>+ </ValidatedForm>+ );+}diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/AffectedItemForm.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/AffectedItemForm.tsxnew file mode 100644index 0000000000..e2b9c344f1--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/AffectedItemForm.tsx@@ -0,0 +1,328 @@+import { ValidatedForm } from "@carbon/form";+import {+ Alert,+ AlertDescription,+ AlertTitle,+ Button,+ HStack,+ ModalDrawer,+ ModalDrawerBody,+ ModalDrawerContent,+ ModalDrawerFooter,+ ModalDrawerHeader,+ ModalDrawerProvider,+ ModalDrawerTitle,+ VStack+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useEffect, useState } from "react";+import { LuTriangleAlert } from "react-icons/lu";+import { useFetcher, useNavigate } from "react-router";+import { TrackingTypeIcon } from "~/components";+import {+ Hidden,+ Input,+ InputControlled,+ Item,+ Select,+ Submit+} from "~/components/Form";+import { ReplenishmentSystemIcon } from "~/components/Icons";+import { useNextItemId } from "~/hooks";+import { path } from "~/utils/path";+import {+ type ChangeOrderChangeType,+ changeOrderAffectedItemValidator,+ changeOrderChangeTypes,+ changeOrderNewPartValidator,+ itemReplenishmentSystems,+ itemTrackingTypes+} from "../../items.models";++// The "Add affected item" modal, opened from the sidebar's bottom button —+// mirrors the PO "Add Line Item" flow (bottom button → modal). On success it+// selects the new item by navigating to its URL (the middle pane is URL-driven).+//+// A single change-type Select drives the body: Version / Revision / Replacement+// Part pick an EXISTING Part; New Part reveals a create-new-part mini-form (mints+// a brand-new part under the change order). Change orders operate on Parts only —+// no Tool selection. The two modes are separate ValidatedForms (each with its own+// validator); the Select carries `changeType` so the route action can tell them+// apart.+function startsWithLetter(value: string) {+ return /^[A-Za-z]/.test(value);+}++export default function AffectedItemForm({+ changeOrderId,+ blacklist,+ onClose+}: {+ changeOrderId: string;+ blacklist: string[];+ onClose: () => void;+}) {+ const { t } = useLingui();+ const navigate = useNavigate();+ const fetcher = useFetcher<{ success: boolean; id?: string }>();++ const [changeType, setChangeType] =+ useState<ChangeOrderChangeType>("Version");+ // A net-new affected item is always a Part (no Part/Tool choice) — mint under+ // the Part sequence.+ const { id: nextId, onIdChange, loading } = useNextItemId("Part");++ const isNewPart = changeType === "New Part";++ // Track the selected Part so we can warn when a Version change would promote its+ // current (draft) make method to Active. Fetch the item's method status on+ // selection; the warning shows only when it has a method but none is Active.+ const [selectedItemId, setSelectedItemId] = useState<string>("");+ const methodStatusFetcher = useFetcher<{+ hasActiveMethod: boolean;+ hasAnyMethod: boolean;+ }>();+ // Only re-fetch when the item/type changes; the fetcher identity is stable.+ // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher is stable+ useEffect(() => {+ if (changeType === "Version" && selectedItemId) {+ methodStatusFetcher.load(+ path.to.api.itemMakeMethodStatus(selectedItemId)+ );+ }+ }, [changeType, selectedItemId]);+ const willActivateDraft =+ changeType === "Version" &&+ !!selectedItemId &&+ methodStatusFetcher.data?.hasAnyMethod === true &&+ methodStatusFetcher.data?.hasActiveMethod === false;++ useEffect(() => {+ if (fetcher.state === "idle" && fetcher.data?.success) {+ onClose();+ if (fetcher.data.id) {+ navigate(+ path.to.changeOrderAffectedItem(changeOrderId, fetcher.data.id)+ );+ }+ }+ }, [fetcher.state, fetcher.data, onClose, navigate, changeOrderId]);++ const changeTypeOptions = changeOrderChangeTypes.map((c) => ({+ label: c,+ value: c+ }));+ const translateItemTrackingType = (v: string) =>+ v === "Inventory"+ ? t`Inventory`+ : v === "Non-Inventory"+ ? t`Non-Inventory`+ : v === "Serial"+ ? t`Serial`+ : t`Batch`;+ const itemTrackingTypeOptions = itemTrackingTypes.map((itemTrackingType) => ({+ label: (+ <span className="flex items-center gap-2">+ <TrackingTypeIcon type={itemTrackingType} />+ {translateItemTrackingType(itemTrackingType)}+ </span>+ ),+ value: itemTrackingType+ }));+ const replenishmentOptions = itemReplenishmentSystems.map(+ (itemReplenishmentSystem) => ({+ label: (+ <span className="flex items-center gap-2">+ <ReplenishmentSystemIcon type={itemReplenishmentSystem} />+ {itemReplenishmentSystem === "Buy"+ ? t`Buy`+ : itemReplenishmentSystem === "Make"+ ? t`Make`+ : t`Buy and Make`}+ </span>+ ),+ value: itemReplenishmentSystem+ })+ );++ // The change-type Select is identical in both modes; `onChange` switches modes.+ const changeTypeField = (+ <Select+ name="changeType"+ label={t`Change type`}+ termId="change-order-change-type"+ options={changeTypeOptions}+ onChange={(o) =>+ setChangeType((o?.value as ChangeOrderChangeType) ?? "Version")+ }+ />+ );++ const footer = (+ <ModalDrawerFooter>+ <HStack>+ <Submit withBlocker={false}>+ <Trans>Add</Trans>+ </Submit>+ <Button size="md" variant="solid" onClick={onClose}>+ <Trans>Cancel</Trans>+ </Button>+ </HStack>+ </ModalDrawerFooter>+ );++ return (+ <ModalDrawerProvider type="modal">+ <ModalDrawer+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ >+ <ModalDrawerContent>+ {isNewPart ? (+ // Distinct `key` per branch is REQUIRED. Both branches render a+ // <ValidatedForm> at the same JSX slot, so React would reconcile them+ // as ONE instance and the RVF store would hydrate only once (on the+ // initial existing-item branch). syncFormProps seeds controlled-field+ // defaults only when `!isHydrated`, so on switch the New Part Selects+ // (replenishment/tracking) never get seeded → "" → enum error. The key+ // forces a fresh mount + fresh store that hydrates with these defaults.+ <ValidatedForm+ key="new-part"+ validator={changeOrderNewPartValidator}+ method="post"+ action={path.to.changeOrderAffected(changeOrderId)}+ defaultValues={{+ changeOrderId,+ changeType: "New Part",+ readableId: "",+ name: "",+ replenishmentSystem: "Make",+ itemTrackingType: "Inventory"+ }}+ fetcher={fetcher}+ className="flex flex-col h-full"+ >+ <ModalDrawerHeader>+ <ModalDrawerTitle>+ <Trans>Add Affected Item</Trans>+ </ModalDrawerTitle>+ </ModalDrawerHeader>+ <ModalDrawerBody>+ <Hidden name="changeOrderId" value={changeOrderId} />+ <VStack spacing={4}>+ {changeTypeField}+ <InputControlled+ name="readableId"+ label={t`Part Number`}+ helperText={+ startsWithLetter(nextId)+ ? t`Use ... to get the next part ID`+ : undefined+ }+ value={nextId}+ onChange={onIdChange}+ isDisabled={loading}+ isUppercase+ />+ <Input name="name" label={t`Name`} characterLimit={40} />+ <Select+ name="replenishmentSystem"+ label={t`Replenishment System`}+ termId="replenishment-system"+ options={replenishmentOptions}+ isOptional={false}+ />+ <Select+ name="itemTrackingType"+ label={t`Tracking Type`}+ termId="item-tracking-type"+ options={itemTrackingTypeOptions}+ />+ </VStack>+ </ModalDrawerBody>+ {footer}+ </ValidatedForm>+ ) : (+ <ValidatedForm+ key="existing-item"+ validator={changeOrderAffectedItemValidator}+ method="post"+ action={path.to.changeOrderAffected(changeOrderId)}+ defaultValues={{+ changeOrderId,+ itemId: "",+ changeType,+ revision: ""+ }}+ fetcher={fetcher}+ className="flex flex-col h-full"+ >+ <ModalDrawerHeader>+ <ModalDrawerTitle>+ <Trans>Add Affected Item</Trans>+ </ModalDrawerTitle>+ </ModalDrawerHeader>+ <ModalDrawerBody>+ <Hidden name="changeOrderId" value={changeOrderId} />+ <VStack spacing={4}>+ {changeTypeField}+ <Item+ name="itemId"+ label={t`Part`}+ type="Part"+ validItemTypes={["Part"]}+ // Version = a new Draft make-method version (BoM/BoP edits),+ // which only makes sense for a manufactured (Make) part — Buy+ // parts have no BoM/BoP. Restrict the picker to Make parts for+ // Version; other change types allow any Part.+ replenishmentSystem={+ changeType === "Version" ? "Make" : undefined+ }+ onChange={(o) =>+ setSelectedItemId((o?.value as string) ?? "")+ }+ blacklist={blacklist}+ />+ {/* Mirror the make-method "New Version" warning: if the part's+ current method is still an un-activated Draft, adding a+ Version freezes it as Active (read-only) so production keeps+ using it until this CO releases the new draft. */}+ {willActivateDraft && (+ <Alert variant="warning">+ <LuTriangleAlert className="h-4 w-4" />+ <AlertTitle>+ <Trans>+ This will set the current version of the make method+ to Active, making it read-only.+ </Trans>+ </AlertTitle>+ <AlertDescription>+ <Trans>+ Your changes go into a new draft version released with+ this change order.+ </Trans>+ </AlertDescription>+ </Alert>+ )}+ {/* A Revision mints a new revision item; let the user name the+ revision (e.g. "A") instead of always auto-numbering.+ Blank → the next revision is computed server-side. */}+ {changeType === "Revision" && (+ <Input+ name="revision"+ label={t`Revision`}+ helperText={t`Leave blank to use the next revision automatically`}+ />+ )}+ </VStack>+ </ModalDrawerBody>+ {footer}+ </ValidatedForm>+ )}+ </ModalDrawerContent>+ </ModalDrawer>+ </ModalDrawerProvider>+ );+}diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderActions.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderActions.tsxnew file mode 100644index 0000000000..b60ad8f873--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderActions.tsx@@ -0,0 +1,202 @@+import { useCarbon } from "@carbon/auth";+import {+ IconButton,+ type JSONContent,+ toast,+ useDebounce+} from "@carbon/react";+import { useLingui } from "@lingui/react/macro";+import type { DragControls } from "framer-motion";+import { nanoid } from "nanoid";+import { useCallback, useState } from "react";+import { LuTrash2 } from "react-icons/lu";+import { useFetcher } from "react-router";+import {+ ActionTaskCard,+ type ActionTaskStatus+} from "~/components/ActionTasks/ActionTaskCard";+import { ActionTaskList } from "~/components/ActionTasks/ActionTaskList";+import { ActionTaskStatusButton } from "~/components/ActionTasks/ActionTaskStatusButton";+import { usePermissions, useRouteData, useUser } from "~/hooks";+import type { ListItem } from "~/types";+import { getPrivateUrl, path } from "~/utils/path";+import type { ChangeOrderActionTask } from "../../types";++// Change-order actions — a thin wrapper over the shared ActionTaskList (same+// component the Quality issue uses). Adding picks from the change order's+// configured required-action templates via the "Add Actions" modal and writes+// back through the reconcile route (`$id.action`), which instantiates the union+// of the current tasks and the newly-picked templates. Each row is an ActionItem+// (notes, status, assignee) with an inline delete. All actions live here on the+// top-level detail route.+export default function ChangeOrderActions({+ changeOrderId,+ actions,+ isDisabled+}: {+ changeOrderId: string;+ actions: ChangeOrderActionTask[];+ isDisabled: boolean;+}) {+ const routeData = useRouteData<{ requiredActions: ListItem[] }>(+ path.to.changeOrder(changeOrderId)+ );+ const addFetcher = useFetcher<{ success: boolean }>();++ // The reconcile route (`setChangeOrderActionTasks`) sets the exact set of+ // tasks from the posted actionTypeIds, so adding posts the union of the current+ // tasks' types and the newly-picked templates (removal is per-card, below).+ const onAdd = useCallback(+ (selectedIds: string[]) => {+ const existing = actions+ .map((a) => a.actionTypeId)+ .filter((id): id is string => Boolean(id));+ const merged = Array.from(new Set([...existing, ...selectedIds]));+ const formData = new FormData();+ formData.append("actionIds", merged.join(","));+ addFetcher.submit(formData, {+ method: "post",+ action: path.to.changeOrderAction(changeOrderId)+ });+ },+ [actions, changeOrderId, addFetcher]+ );++ return (+ <ActionTaskList+ tasks={actions}+ reorderAction={path.to.changeOrderActionOrder(changeOrderId)}+ templates={routeData?.requiredActions ?? []}+ onAdd={onAdd}+ isAddSubmitting={addFetcher.state !== "idle"}+ isDisabled={isDisabled}+ renderItem={(action, dragControls) => (+ <ActionItem+ changeOrderId={changeOrderId}+ action={action}+ isDisabled={isDisabled}+ dragControls={dragControls}+ />+ )}+ />+ );+}++// The CO wrapper over the shared ActionTaskCard: owns CO-specific persistence+// (notes via supabase, status + delete via CO routes) and passes the due date+// into the card's slots.+function ActionItem({+ changeOrderId,+ action,+ isDisabled,+ dragControls+}: {+ changeOrderId: string;+ action: ChangeOrderActionTask;+ isDisabled: boolean;+ dragControls: DragControls;+}) {+ const { t } = useLingui();+ const permissions = usePermissions();+ const {+ id: userId,+ company: { id: companyId }+ } = useUser();+ const { carbon } = useCarbon();+ const statusFetcher = useFetcher<{ success: boolean }>();+ const deleteFetcher = useFetcher<{ success: boolean }>();++ const [content, setContent] = useState((action.notes ?? {}) as JSONContent);+ const status = (action.status ?? "Pending") as ActionTaskStatus;+ const canEdit = permissions.can("update", "parts") && !isDisabled;++ const onUploadImage = async (file: File) => {+ const fileType = file.name.split(".").pop();+ const fileName = `${companyId}/parts/${nanoid()}.${fileType}`;+ const result = await carbon?.storage.from("private").upload(fileName, file);+ if (result?.error || !result?.data) {+ toast.error(t`Failed to upload image`);+ throw new Error(result?.error?.message ?? "Failed to upload image");+ }+ return getPrivateUrl(result.data.path);+ };++ const onUpdateContent = useDebounce(+ async (value: JSONContent) => {+ await carbon+ ?.from("changeOrderActionTask")+ .update({ notes: value, updatedBy: userId })+ .eq("id", action.id);+ },+ 2500,+ true+ );++ const onStatusChange = (next: ActionTaskStatus) => {+ if (isDisabled) return;+ const formData = new FormData();+ formData.append("id", action.id);+ formData.append("status", next);+ statusFetcher.submit(formData, {+ method: "post",+ action: path.to.changeOrderActionStatus(changeOrderId, action.id)+ });+ };++ const onDelete = () => {+ if (isDisabled) return;+ deleteFetcher.submit(+ {},+ {+ method: "post",+ action: path.to.deleteChangeOrderAction(changeOrderId, action.id)+ }+ );+ };++ return (+ <ActionTaskCard+ title={action.name ?? ""}+ status={status}+ notes={content}+ canEditNotes={canEdit}+ onNotesChange={(value) => {+ setContent(value);+ onUpdateContent(value);+ }}+ onUploadImage={onUploadImage}+ onStatusChange={onStatusChange}+ assigneeTable="changeOrderActionTask"+ assigneeId={action.id}+ assignee={action.assignee ?? undefined}+ isDisabled={isDisabled}+ showDragHandle={!isDisabled}+ dragControls={dragControls}+ statusBadge={+ <ActionTaskStatusButton+ status={status}+ onChange={onStatusChange}+ isDisabled={isDisabled}+ />+ }+ headerExtras={+ canEdit ? (+ <IconButton+ aria-label={t`Delete action`}+ icon={<LuTrash2 />}+ variant="ghost"+ onClick={onDelete}+ isDisabled={deleteFetcher.state !== "idle"}+ />+ ) : undefined+ }+ footerExtras={+ action.dueDate ? (+ <span className="text-xs text-muted-foreground tabular-nums whitespace-nowrap shrink-0">+ {action.dueDate}+ </span>+ ) : undefined+ }+ />+ );+}diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderChanges.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderChanges.tsxnew file mode 100644index 0000000000..33aa121902--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderChanges.tsx@@ -0,0 +1,68 @@+import {+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ HStack,+ VStack+} from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import ChangeOrderDiffViewer from "./ChangeOrderDiffViewer";+import type { ReleaseChange } from "./ChangeOrderReleaseMerge";+import ChangeTypeBadge from "./ChangeTypeBadge";++// The CO-wide changes rollup shown on the top-level overview ($id.details):+// every affected item's read-only authoring diff in one card, mirroring the+// release confirmation dialog's list (label + ChangeOrderDiffViewer per item).+export default function ChangeOrderChanges({+ changes+}: {+ changes: ReleaseChange[];+}) {+ return (+ <Card>+ <CardHeader>+ <CardTitle>+ <Trans>Changes</Trans>+ </CardTitle>+ </CardHeader>+ <CardContent>+ <VStack spacing={4} className="w-full">+ {changes.length === 0 ? (+ <span className="text-sm italic text-muted-foreground">+ <Trans>No affected items.</Trans>+ </span>+ ) : (+ changes.map((c) => (+ <VStack key={c.id} spacing={2} className="w-full min-w-0">+ <HStack className="w-full justify-between items-start gap-2">+ <VStack spacing={0} className="min-w-0">+ <h3+ className="max-w-full truncate text-sm font-medium text-foreground"+ title={c.label}+ >+ {c.label}+ </h3>+ {c.name && (+ <span className="max-w-full truncate text-xs text-muted-foreground">+ {c.name}+ </span>+ )}+ </VStack>+ {/* More real estate here than the explorer/card header, so the+ badge sits at the far right of the row, horizontally. */}+ <ChangeTypeBadge+ changeType={c.changeType}+ version={c.version}+ className="shrink-0"+ />+ </HStack>+ <ChangeOrderDiffViewer diff={c.diff} />+ </VStack>+ ))+ )}+ </VStack>+ </CardContent>+ </Card>+ );+}diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderContent.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderContent.tsxnew file mode 100644index 0000000000..de0fcc8129--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderContent.tsx@@ -0,0 +1,151 @@+import { useCarbon } from "@carbon/auth";+import type { JSONContent } from "@carbon/react";+import {+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ generateHTML,+ toast,+ useDebounce+} from "@carbon/react";+import { Editor } from "@carbon/react/Editor";+import { useLingui } from "@lingui/react/macro";+import { nanoid } from "nanoid";+import { useState } from "react";+import { usePermissions, useUser } from "~/hooks";+import { getPrivateUrl } from "~/utils/path";++// The two rich-text columns on the changeOrder header (reasonForChange ++// description). Both are stored as JSON and read/written the same way; the+// debounced writer targets the matching column directly through the+// request-scoped supabase client (mirrors IssueContent). Rendered as full Cards+// on the top-level CO detail route; `embedded` drops the Card chrome for callers+// that supply their own frame.+export function ChangeOrderContentSection({+ id,+ title,+ field,+ content: initialContent,+ isDisabled,+ embedded = false+}: {+ id: string;+ title: string;+ field: "reasonForChange" | "description";+ content: JSONContent;+ isDisabled: boolean;+ // When true, render just the editor/prose with no Card chrome — the caller+ // (e.g. the accordion rail) supplies the title + frame.+ embedded?: boolean;+}) {+ const {+ id: userId,+ company: { id: companyId }+ } = useUser();+ const { carbon } = useCarbon();+ const { t } = useLingui();+ const permissions = usePermissions();++ const [content, setContent] = useState(initialContent ?? {});++ const onUploadImage = async (file: File) => {+ const fileType = file.name.split(".").pop();+ const fileName = `${companyId}/parts/${nanoid()}.${fileType}`;++ const result = await carbon?.storage.from("private").upload(fileName, file);++ if (result?.error) {+ toast.error(t`Failed to upload image`);+ throw new Error(result.error.message);+ }++ if (!result?.data) {+ throw new Error("Failed to upload image");+ }++ return getPrivateUrl(result.data.path);+ };++ const onUpdateContent = useDebounce(+ async (value: JSONContent) => {+ await carbon+ ?.from("changeOrder")+ .update({+ [field]: value,+ updatedBy: userId+ })+ .eq("id", id);+ },+ 2500,+ true+ );++ const body =+ permissions.can("update", "parts") && !isDisabled ? (+ <Editor+ className="[&_.ProseMirror]:text-sm"+ initialValue={(content ?? {}) as JSONContent}+ onUpload={onUploadImage}+ onChange={(value) => {+ setContent(value);+ onUpdateContent(value);+ }}+ />+ ) : (+ <div+ className="prose prose-sm dark:prose-invert"+ dangerouslySetInnerHTML={{+ __html: generateHTML(content as JSONContent)+ }}+ />+ );++ if (embedded) return body;++ return (+ <Card>+ <CardHeader>+ <CardTitle>{title}</CardTitle>+ </CardHeader>+ <CardContent>{body}</CardContent>+ </Card>+ );+}++export function ChangeOrderContent({+ id,+ reasonForChange,+ description,+ isDisabled+}: {+ id: string;+ reasonForChange: JSONContent;+ description: JSONContent;+ isDisabled: boolean;+}) {+ const { t } = useLingui();++ if (!id) return null;++ return (+ <>+ <ChangeOrderContentSection+ key={`${id}-reason`}+ id={id}+ title={t`Reason for Change`}+ field="reasonForChange"+ content={reasonForChange}+ isDisabled={isDisabled}+ />+ <ChangeOrderContentSection+ key={`${id}-description`}+ id={id}+ title={t`Description of Change`}+ field="description"+ content={description}+ isDisabled={isDisabled}+ />+ </>+ );+}diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderDiffViewer.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderDiffViewer.tsxnew file mode 100644index 0000000000..32d6eb0289--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderDiffViewer.tsx@@ -0,0 +1,734 @@+import type { TermId } from "@carbon/glossary";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+ cn,+ HStack,+ LabelWithHelp,+ VStack+} from "@carbon/react";+import { getItemReadableId } from "@carbon/utils";+import { Trans } from "@lingui/react/macro";+import type { ReactNode } from "react";+import { LuChevronRight } from "react-icons/lu";+import { useItems, useSuppliers } from "~/stores";+import type {+ ChangeOrderItemDiff,+ MethodDiffEntry,+ MethodDiffStatus,+ OperationDiffEntry+} from "../../items.models";+import { DiffBadge } from "./diff-ui";++// -----------------------------------------------------------------------------+// Read-only Change Order diff viewer (authoring-time). Renders the CO-owned draft+// method vs the base Active method it was copied from as a git-style, tree-shaped+// redline: BOM and BOP as SEPARATE sections plus an Attributes section. Each entry+// is a top-level TREE NODE (a BOM component / a BOP operation) whose children are+// its properties — the FULL property list on an add (all green), the old values on+// a remove (all red), or the changed old→new pairs on a modify. Colors follow the+// audit-log red→green style. Unchanged rows are filtered out; an unchanged+// operation is shown (uncolored) only when its children changed.+//+// This is NOT the release merge UI (ChangeOrderReleaseMerge / ...ConflictResolver,+// which have radio-button choices) — it is purely read-only, no forms, no state.+// -----------------------------------------------------------------------------++type Row = Record<string, unknown>;+type Items = ReturnType<typeof useItems>[0];++// Humanized labels shared with the merge resolver's FIELD_LABELS, extended with+// the item-attribute columns the attribute diff surfaces. The declared order here+// also drives property ordering in the full-property (add/remove) lists.+const FIELD_LABELS: Record<string, string> = {+ quantity: "Quantity",+ unitOfMeasureCode: "Unit",+ order: "Sequence",+ description: "Description",+ processId: "Process",+ workCenterId: "Work center",+ procedureId: "Procedure",+ operationSupplierProcessId: "Supplier process",+ operationLeadTime: "Lead time",+ operationUnitCost: "Unit cost",+ operationMinimumCost: "Minimum cost",+ setupTime: "Setup time",+ laborTime: "Labor time",+ machineTime: "Machine time",+ methodType: "Method",+ workInstruction: "Work instructions",+ name: "Name",+ itemTrackingType: "Tracking",+ replenishmentSystem: "Replenishment",+ sourcingType: "Sourcing",+ requiresInspection: "Requires inspection",+ defaultMethodType: "Default method",+ itemPostingGroupId: "Item group",+ mpn: "MPN",+ thumbnailPath: "Thumbnail",+ key: "Parameter",+ toolId: "Tool",+ supplierPartId: "Part #",+ unitPrice: "Unit price",+ minimumOrderQuantity: "Min order qty",+ orderMultiple: "Order multiple",+ conversionFactor: "Conversion factor",+ supplierUnitOfMeasureCode: "Purchasing unit"+};++// Sort index for a field in the full-property list — known fields keep the order+// declared in FIELD_LABELS, unknown fields sort alphabetically after them.+const FIELD_ORDER: Record<string, number> = Object.fromEntries(+ Object.keys(FIELD_LABELS).map((k, i) => [k, i])+);++// Audit / linkage / tenancy columns never worth showing as a property. Mirrors the+// diff engine's IGNORED_FIELDS plus a few display-only noise columns.+const NOISE_FIELDS = new Set<string>([+ "id",+ "companyId",+ "changeOrderId",+ "affectedItemId",+ "sourceMaterialId",+ "sourceOperationId",+ "sourceId",+ "stagedOperationId",+ "makeMethodId",+ "operationId",+ // Internal linkage id with no user-facing name — never show its raw UUID.+ "assemblyInstructionId",+ "itemType",+ "itemReadableId",+ "toolReadableId",+ "createdAt",+ "createdBy",+ "updatedAt",+ "updatedBy",+ "customFields",+ "externalId"+]);++const EMPTY_SKIP = new Set<string>();++function humanizeField(field: string): string {+ return (+ FIELD_LABELS[field] ??+ field.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase())+ );+}++function formatValue(field: string, value: unknown): string {+ if (value === null || value === undefined || value === "") return "—";+ // JSON columns (workInstruction, etc.) — don't dump raw structure.+ if (field === "workInstruction" || typeof value === "object") return "Set";+ if (typeof value === "boolean") return value ? "Yes" : "No";+ return String(value);+}++// Bill of Process operations pair a time with a rate unit. Show each pair as one+// row (e.g. "Setup time: 10 Total Minutes") instead of separate time + unit rows.+const TIME_UNIT_GROUPS: { time: string; unit: string }[] = [+ { time: "setupTime", unit: "setupUnit" },+ { time: "laborTime", unit: "laborUnit" },+ { time: "machineTime", unit: "machineUnit" }+];++// The group (if any) a field belongs to, matched by its time OR unit member.+function timeUnitGroupFor(field: string) {+ return TIME_UNIT_GROUPS.find((g) => g.time === field || g.unit === field);+}++// Join a time value with its unit into one label (10 + "Total Minutes" →+// "10 Total Minutes"); "—" when both are empty.+function combineTimeUnit(time: unknown, unit: unknown): string {+ const parts = [time, unit]+ .filter((v) => v !== null && v !== undefined && v !== "")+ .map((v) => String(v));+ return parts.length > 0 ? parts.join(" ") : "—";+}++// The Kit flag only distinguishes Kit vs Subassembly on a Make-to-Order+// component; for any other method type it's meaningless, so hide it from the diff.+function hideKit(field: string, methodType: unknown): boolean {+ return field === "kit" && methodType !== "Make to Order";+}++// Every meaningful, non-empty business field of a row, minus the noise set and any+// fields already used as the node label — ordered by FIELD_ORDER.+function meaningfulFields(row: Row, skip: Set<string>): string[] {+ return Object.keys(row)+ .filter(+ (f) =>+ !NOISE_FIELDS.has(f) &&+ !skip.has(f) &&+ row[f] !== null &&+ row[f] !== undefined &&+ row[f] !== ""+ )+ .sort((a, b) => {+ const ia = FIELD_ORDER[a] ?? Number.MAX_SAFE_INTEGER;+ const ib = FIELD_ORDER[b] ?? Number.MAX_SAFE_INTEGER;+ return ia !== ib ? ia - ib : a.localeCompare(b);+ });+}++// The audit-log red/green pill (mirrors AuditLogDrawer's ChangePill).+function Pill({+ variant,+ children,+ title+}: {+ variant: "old" | "new";+ children: ReactNode;+ title?: string;+}) {+ return (+ <span+ title={title}+ className={cn(+ "inline-block max-w-[14rem] truncate rounded px-2 py-0.5 align-bottom text-xs",+ variant === "old"+ ? "bg-red-500/10 text-red-500"+ : "bg-green-500/10 text-green-500"+ )}+ >+ {children}+ </span>+ );+}++// A tree-child region: indented under its parent node with a hierarchy guide line.+function TreeChildren({ children }: { children: ReactNode }) {+ return (+ <div className="w-full border-l border-border/60 pl-3 ml-1">+ <VStack spacing={1} className="w-full">+ {children}+ </VStack>+ </div>+ );+}++// One "label: [old] → [new]" line for a modified field.+function FieldRow({+ field,+ before,+ after+}: {+ field: string;+ before: unknown;+ after: unknown;+}) {+ const beforeText = formatValue(field, before);+ const afterText = formatValue(field, after);+ return (+ <div className="flex min-w-0 items-center gap-2 text-xs">+ <span className="min-w-[6rem] shrink-0 text-muted-foreground">+ {humanizeField(field)}+ </span>+ <Pill variant="old" title={beforeText}>+ {beforeText}+ </Pill>+ <span className="shrink-0 text-muted-foreground">→</span>+ <Pill variant="new" title={afterText}>+ {afterText}+ </Pill>+ </div>+ );+}++// One "label: [value]" line for an added (green) or removed (red) property.+function ValueRow({+ field,+ value,+ variant+}: {+ field: string;+ value: unknown;+ variant: "old" | "new";+}) {+ const text = formatValue(field, value);+ return (+ <div className="flex min-w-0 items-center gap-2 text-xs">+ <span className="min-w-[6rem] shrink-0 text-muted-foreground">+ {humanizeField(field)}+ </span>+ <Pill variant={variant} title={text}>+ {text}+ </Pill>+ </div>+ );+}++// The full property list for an added (all new, green) or removed (all old, red)+// node — "either they are all new, or they are modified" per the diff spec.+function AllPropertyRows({+ row,+ variant,+ skip = EMPTY_SKIP+}: {+ row: Row | null;+ variant: "old" | "new";+ skip?: Set<string>;+}): ReactNode {+ if (!row) return null;+ const fields = meaningfulFields(row, skip);+ if (fields.length === 0) return null;+ const emitted = new Set<string>();+ const rows: ReactNode[] = [];+ for (const f of fields) {+ if (emitted.has(f)) continue;+ if (hideKit(f, row.methodType)) continue;+ const group = timeUnitGroupFor(f);+ if (group) {+ emitted.add(group.time);+ emitted.add(group.unit);+ rows.push(+ <ValueRow+ key={group.time}+ field={group.time}+ value={combineTimeUnit(row[group.time], row[group.unit])}+ variant={variant}+ />+ );+ continue;+ }+ rows.push(<ValueRow key={f} field={f} value={row[f]} variant={variant} />);+ }+ return rows;+}++// The status color for a node title: green (added) / red + strikethrough+// (removed); no color for modified or an unchanged-with-changed-children op.+function statusColor(status: MethodDiffStatus): string | null {+ return status === "added"+ ? "bg-green-500/10 text-green-500"+ : status === "removed"+ ? "bg-red-500/10 text-red-500 line-through"+ : null;+}++// A collapsible tree node: a title line (colored by status, with the Added /+// Modified / Removed badge) over its body, which lives in a collapsible region so+// the user can fold away parts of a large diff. `collapsible` is false for a leaf+// node with no body — then it renders a plain title line (aligned with a chevron+// spacer) and no toggle. Defaults to open so nothing is hidden by default.+function TreeNode({+ label,+ status,+ collapsible,+ children+}: {+ label: ReactNode;+ status: MethodDiffStatus;+ collapsible: boolean;+ children?: ReactNode;+}) {+ const colored = statusColor(status);+ const title = (+ <span+ className={cn(+ "inline-block max-w-full truncate align-bottom text-sm",+ colored && `px-2 py-0.5 rounded ${colored}`+ )}+ title={typeof label === "string" ? label : undefined}+ >+ {label}+ </span>+ );++ if (!collapsible) {+ return (+ <HStack className="justify-between w-full">+ <HStack spacing={1} className="min-w-0">+ <span className="size-3 shrink-0" aria-hidden />+ {title}+ </HStack>+ <DiffBadge status={status} />+ </HStack>+ );+ }++ return (+ <Collapsible defaultOpen className="w-full">+ <HStack className="justify-between w-full">+ <CollapsibleTrigger className="group flex min-w-0 items-center gap-1 text-left">+ <LuChevronRight className="size-3 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-90" />+ {title}+ </CollapsibleTrigger>+ <DiffBadge status={status} />+ </HStack>+ <CollapsibleContent>+ <TreeChildren>{children}</TreeChildren>+ </CollapsibleContent>+ </Collapsible>+ );+}++// Fields used as a node's label — skipped from its property list to avoid echoing+// the header text back as a property row.+const MATERIAL_LABEL_FIELDS = new Set(["itemId"]);+const OPERATION_LABEL_FIELDS = new Set(["description"]);+// supplierId is the supplier-part node's label; itemId/active/tags are noise.+const SUPPLIER_PART_LABEL_FIELDS = new Set([+ "supplierId",+ "itemId",+ "active",+ "tags"+]);++// Sourcing only means anything on a "Buy and Make" item (mirrors+// SourcingTypeProperty, which renders null otherwise) — hide it for everything+// else. Material rows gate on the COMPONENT item; attributes on the draft item.+const MATERIAL_LABEL_AND_SOURCING_FIELDS = new Set([+ ...MATERIAL_LABEL_FIELDS,+ "sourcingType"+]);+const SOURCING_ONLY_FIELDS = new Set(["sourcingType"]);++// The property-skip set for a material row: the label fields, plus sourcingType+// unless the component item is "Buy and Make" (resolved from the items store).+function materialSkipFields(row: Row | null, items: Items): Set<string> {+ const itemId = (row?.itemId as string | undefined) ?? "";+ const isBuyAndMake =+ items.find((i) => i.id === itemId)?.replenishmentSystem === "Buy and Make";+ return isBuyAndMake+ ? MATERIAL_LABEL_FIELDS+ : MATERIAL_LABEL_AND_SOURCING_FIELDS;+}++// Whether an attributes diff entry belongs to a "Buy and Make" item — the+// entry's before/after carry the full item attribute row.+function attributeIsBuyAndMake(entry: MethodDiffEntry<Row>): boolean {+ const row = (entry.after ?? entry.before) as Row | null;+ return row?.replenishmentSystem === "Buy and Make";+}++function modifiedFieldRows(+ entry: MethodDiffEntry<Row>,+ skip: Set<string> = EMPTY_SKIP+): ReactNode {+ const changed = entry.changedFields;+ if (!changed) return null;+ // Full base/target rows carry every value, so a time/unit group can show its+ // companion even when only one of the two members changed.+ const before = (entry.before ?? {}) as Row;+ const after = (entry.after ?? {}) as Row;+ const methodType = after.methodType ?? before.methodType;+ const emitted = new Set<string>();+ const rows: ReactNode[] = [];++ for (const [field, { before: b, after: a }] of Object.entries(changed)) {+ if (skip.has(field) || emitted.has(field)) continue;+ if (hideKit(field, methodType)) continue;+ const group = timeUnitGroupFor(field);+ if (group) {+ emitted.add(group.time);+ emitted.add(group.unit);+ rows.push(+ <FieldRow+ key={group.time}+ field={group.time}+ before={combineTimeUnit(before[group.time], before[group.unit])}+ after={combineTimeUnit(after[group.time], after[group.unit])}+ />+ );+ continue;+ }+ rows.push(<FieldRow key={field} field={field} before={b} after={a} />);+ }+ return rows;+}++// The body of a top-level node (or child node): the changed old→new pairs when+// modified, the full new property list when added, the full old list when removed.+function EntryBody({+ entry,+ skip+}: {+ entry: MethodDiffEntry<Row>;+ skip: Set<string>;+}): ReactNode {+ if (entry.status === "modified") return modifiedFieldRows(entry, skip);+ if (entry.status === "added")+ return (+ <AllPropertyRows row={entry.after as Row} variant="new" skip={skip} />+ );+ if (entry.status === "removed")+ return (+ <AllPropertyRows row={entry.before as Row} variant="old" skip={skip} />+ );+ return null;+}++// Whether an entry has any renderable body (changed fields, or a non-empty+// property list after the noise/label filter) — drives whether the node is+// collapsible or renders as a bare leaf.+function entryHasBody(entry: MethodDiffEntry<Row>, skip: Set<string>): boolean {+ if (entry.status === "modified")+ return Object.keys(entry.changedFields ?? {}).some((f) => !skip.has(f));+ if (entry.status === "added")+ return meaningfulFields((entry.after as Row) ?? {}, skip).length > 0;+ if (entry.status === "removed")+ return meaningfulFields((entry.before as Row) ?? {}, skip).length > 0;+ return false;+}++function MaterialEntry({+ entry,+ items+}: {+ entry: MethodDiffEntry<Row>;+ items: Items;+}) {+ const row = (entry.after ?? entry.before) as Row | null;+ const itemId = (row?.itemId as string | undefined) ?? "";+ // Prefer the server-resolved readable id (store-independent), then the store+ // lookup, then the raw id as a last resort.+ const label =+ (row?.itemReadableId as string | undefined) ||+ getItemReadableId(items, itemId) ||+ itemId ||+ "Material";+ const skip = materialSkipFields(row, items);+ return (+ <TreeNode+ label={label}+ status={entry.status}+ collapsible={entryHasBody(entry, skip)}+ >+ <EntryBody entry={entry} skip={skip} />+ </TreeNode>+ );+}++function SupplierPartEntry({+ entry,+ suppliersById+}: {+ entry: MethodDiffEntry<Row>;+ suppliersById: Map<string, string>;+}) {+ const row = (entry.after ?? entry.before) as Row | null;+ const supplierId = (row?.supplierId as string | undefined) ?? "";+ const label = suppliersById.get(supplierId) || supplierId || "Supplier";+ return (+ <TreeNode+ label={label}+ status={entry.status}+ collapsible={entryHasBody(entry, SUPPLIER_PART_LABEL_FIELDS)}+ >+ <EntryBody entry={entry} skip={SUPPLIER_PART_LABEL_FIELDS} />+ </TreeNode>+ );+}++// The three operation-child buckets, each with a label extractor for its rows and+// the label fields to skip from that row's property list.+const CHILD_BUCKETS: {+ key: "steps" | "parameters" | "tools";+ title: ReactNode;+ labelOf: (row: Row | null) => string;+ skip: Set<string>;+}[] = [+ {+ key: "steps",+ title: <Trans>Steps</Trans>,+ labelOf: (r) => (r?.name as string) || (r?.description as string) || "Step",+ skip: new Set(["name", "description"])+ },+ {+ key: "parameters",+ title: <Trans>Parameters</Trans>,+ labelOf: (r) => (r?.key as string) || "Parameter",+ skip: new Set(["key"])+ },+ {+ key: "tools",+ title: <Trans>Tools</Trans>,+ // Prefer the server-resolved tool readable id over the raw toolId UUID.+ labelOf: (r) =>+ (r?.toolReadableId as string) || (r?.toolId as string) || "Tool",+ skip: new Set(["toolId", "toolReadableId"])+ }+];++function operationHasChildChanges(entry: OperationDiffEntry): boolean {+ const c = entry.children;+ if (!c) return false;+ return [c.steps, c.parameters, c.tools].some((arr) =>+ arr.some((r) => r.status !== "unchanged")+ );+}++function OperationEntry({ entry }: { entry: OperationDiffEntry }) {+ const row = (entry.after ?? entry.before) as Row | null;+ // processId is resolved to the process name server-side; use it as a human+ // fallback label so an operation without a description isn't shown as a number.+ const label =+ (row?.description as string) ||+ (row?.processId as string) ||+ `Operation ${row?.order ?? ""}`.trim();+ const children = entry.children;+ const buckets = children+ ? CHILD_BUCKETS.map((bucket) => ({+ bucket,+ changed: children[bucket.key].filter((c) => c.status !== "unchanged")+ })).filter((b) => b.changed.length > 0)+ : [];+ const collapsible =+ entryHasBody(entry, OPERATION_LABEL_FIELDS) || buckets.length > 0;+ return (+ <TreeNode label={label} status={entry.status} collapsible={collapsible}>+ <EntryBody entry={entry} skip={OPERATION_LABEL_FIELDS} />+ {buckets.map(({ bucket, changed }) => (+ <div key={bucket.key} className="w-full">+ <div className="text-[0.65rem] font-medium uppercase text-muted-foreground pb-0.5">+ {bucket.title}+ </div>+ <TreeChildren>+ {changed.map((child, i) => (+ <TreeNode+ key={`${bucket.key}-${i}`}+ label={bucket.labelOf(+ (child.after ?? child.before) as Row | null+ )}+ status={child.status}+ collapsible={entryHasBody(child, bucket.skip)}+ >+ <EntryBody entry={child} skip={bucket.skip} />+ </TreeNode>+ ))}+ </TreeChildren>+ </div>+ ))}+ </TreeNode>+ );+}++function Section({+ title,+ termId,+ children+}: {+ title: ReactNode;+ termId?: TermId;+ children: ReactNode;+}) {+ return (+ <VStack spacing={2} className="w-full">+ <LabelWithHelp termId={termId} variant="inline">+ <span className="text-xs font-medium text-muted-foreground">+ {title}+ </span>+ </LabelWithHelp>+ {children}+ </VStack>+ );+}++export default function ChangeOrderDiffViewer({+ diff,+ // When `bare`, drop the bordered wrapper + the internal "Changes" label — the+ // caller (the affected-item "Changes" card) supplies the frame + title. The+ // release dialog keeps the default framed look.+ bare = false+}: {+ diff?: ChangeOrderItemDiff;+ bare?: boolean;+}) {+ const [items] = useItems();+ const [suppliers] = useSuppliers();+ const suppliersById = new Map(+ (suppliers ?? []).map((s) => [s.id, s.name] as const)+ );++ const materials = (diff?.materials ?? []).filter((m) => {+ if (m.status === "unchanged") return false;+ // A modified row whose only change is a hidden field (sourcing on a+ // non-Buy-and-Make component) reads as unchanged — drop it entirely.+ if (m.status !== "modified") return true;+ return entryHasBody(+ m,+ materialSkipFields((m.after ?? m.before) as Row | null, items)+ );+ });+ const operations = (diff?.operations ?? []).filter(+ (o) => o.status !== "unchanged" || operationHasChildChanges(o)+ );+ const attributes = (diff?.attributes ?? []).filter((a) => {+ if (a.status === "unchanged") return false;+ const skip = attributeIsBuyAndMake(a) ? EMPTY_SKIP : SOURCING_ONLY_FIELDS;+ return Object.keys(a.changedFields ?? {}).some((f) => !skip.has(f));+ });+ const supplierParts = (diff?.supplierParts ?? []).filter(+ (s) => s.status !== "unchanged"+ );++ const isEmpty =+ materials.length === 0 &&+ operations.length === 0 &&+ attributes.length === 0 &&+ supplierParts.length === 0;++ const body = isEmpty ? (+ <span className="text-sm text-muted-foreground italic">+ <Trans>No changes yet.</Trans>+ </span>+ ) : (+ <VStack spacing={8} className="w-full">+ {attributes.length > 0 && (+ <Section title={<Trans>Properties</Trans>}>+ {attributes.map((a, i) => (+ <VStack key={`attr-${i}`} spacing={1} className="w-full">+ {modifiedFieldRows(+ a,+ attributeIsBuyAndMake(a) ? EMPTY_SKIP : SOURCING_ONLY_FIELDS+ )}+ </VStack>+ ))}+ </Section>+ )}+ {materials.length > 0 && (+ <Section title={<Trans>Bill of Materials</Trans>} termId="bom">+ {materials.map((m, i) => (+ <MaterialEntry key={`mat-${i}`} entry={m} items={items} />+ ))}+ </Section>+ )}+ {operations.length > 0 && (+ <Section title={<Trans>Bill of Process</Trans>} termId="routing">+ {operations.map((o, i) => (+ <OperationEntry key={`op-${i}`} entry={o} />+ ))}+ </Section>+ )}+ {supplierParts.length > 0 && (+ <Section title={<Trans>Supplier Parts</Trans>}>+ {supplierParts.map((s, i) => (+ <SupplierPartEntry+ key={`sp-${i}`}+ entry={s}+ suppliersById={suppliersById}+ />+ ))}+ </Section>+ )}+ </VStack>+ );++ if (bare) return body;++ return (+ <div className="w-full rounded-lg border border-border p-3">+ <div className="pb-2">+ <LabelWithHelp termId="change-order" variant="inline">+ <span className="text-xs font-medium uppercase text-muted-foreground">+ <Trans>Changes</Trans>+ </span>+ </LabelWithHelp>+ </div>+ {body}+ </div>+ );+}diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderExplorer.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderExplorer.tsxnew file mode 100644index 0000000000..6ba1d1779c--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderExplorer.tsx@@ -0,0 +1,220 @@+import {+ Button,+ cn,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuIcon,+ DropdownMenuItem,+ DropdownMenuTrigger,+ HStack,+ IconButton,+ useDisclosure,+ VStack+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { LuCirclePlus, LuEllipsisVertical, LuTrash } from "react-icons/lu";+import { Link, useFetcher, useParams } from "react-router";+import { Empty, ItemThumbnail, MethodItemTypeIcon } from "~/components";+import { useRouteData } from "~/hooks";+import { canEditChangeOrder } from "~/modules/items";+import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";+import type { ItemType } from "~/modules/shared";+import { useItems } from "~/stores";+import { path } from "~/utils/path";+import type { ChangeOrder } from "../../types";+import AffectedItemForm from "./AffectedItemForm";+import type { AffectedItemDraft } from "./affectedItem.types";++// Explorer (left panel) of the change-order workspace — deliberately the same+// layout as the Purchase Order explorer (PurchaseOrderExplorer /+// PurchaseOrderLineItem): a full-bleed list of rows (thumbnail + id ++// description, hover ⋮ menu) over a bottom "Add" button, with the shared `Empty`+// component for the no-items state (mirrors the Sales / Purchase Order explorers).+// Selection lives in the URL (the affectedId route param). Self-contained: reads+// the affected items and lock state from the $id route loader, so ResizablePanels+// can render it with no props (mirrors SalesOrderExplorer).+export default function ChangeOrderExplorer() {+ const { id } = useParams();+ if (!id) throw new Error("id not found");++ const routeData = useRouteData<{+ changeOrder: ChangeOrder;+ affectedItems: AffectedItemDraft[];+ }>(path.to.changeOrder(id));++ const affectedItems = routeData?.affectedItems ?? [];+ const isDisabled = !canEditChangeOrder(routeData?.changeOrder?.status);++ const disclosure = useDisclosure();++ return (+ <>+ <div className="w-full h-full text-sm flex flex-col justify-between">+ <VStack+ spacing={0}+ className="flex-1 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"+ >+ {affectedItems.length === 0 ? (+ <Empty>+ {!isDisabled && (+ <Button+ leftIcon={<LuCirclePlus />}+ variant="secondary"+ onClick={disclosure.onOpen}+ >+ <Trans>Add Affected Item</Trans>+ </Button>+ )}+ </Empty>+ ) : (+ affectedItems.map((affected) => (+ <AffectedItemRow+ key={affected.affectedItem.id}+ changeOrderId={id}+ affected={affected}+ isDisabled={isDisabled}+ />+ ))+ )}+ </VStack>++ {!isDisabled && (+ <div className="w-full flex border-t border-border p-4 gap-2">+ <Button+ className="w-full"+ leftIcon={<LuCirclePlus />}+ variant="secondary"+ onClick={disclosure.onOpen}+ >+ <Trans>Add Affected Item</Trans>+ </Button>+ </div>+ )}+ </div>++ {disclosure.isOpen && (+ <AffectedItemForm+ changeOrderId={id}+ blacklist={affectedItems.map((a) => a.affectedItem.itemId)}+ onClose={disclosure.onClose}+ />+ )}+ </>+ );+}++function AffectedItemRow({+ changeOrderId,+ affected,+ isDisabled+}: {+ changeOrderId: string;+ affected: AffectedItemDraft;+ isDisabled: boolean;+}) {+ const { t } = useLingui();+ const { affectedId } = useParams();+ const deleteFetcher = useFetcher();+ const [items] = useItems();++ const item = affected.affectedItem;+ const label = item.item;+ const type = (label?.type as ItemType) ?? "Part";+ const isSelected = item.id === affectedId;+ // Revision / Replacement Part mint a DISTINCT (hidden, inactive) successor item+ // at add time — surface its number next to the source ("GA-0029 → GA-0030") so+ // the created part/revision is visible top-level, not only inside the line+ // detail. A New Part is net-new (no predecessor: its newItemId IS itemId), so+ // there's nothing to point at — show a single id, not "X → X". The items store+ // includes inactive items, so the minted item resolves.+ const newItemLabel =+ item.newItemId && item.newItemId !== item.itemId+ ? (items.find((i) => i.id === item.newItemId)?.readableIdWithRevision ??+ null)+ : null;++ return (+ <VStack spacing={0} className="border-b">+ <Link+ to={path.to.changeOrderAffectedItem(changeOrderId, item.id)}+ prefetch="intent"+ className="w-full"+ >+ <HStack+ className={cn(+ "group w-full p-2 items-center hover:bg-accent/30 cursor-pointer relative",+ isSelected && "bg-accent/60 hover:bg-accent/50"+ )}+ >+ <HStack spacing={2} className="flex-grow min-w-0 pr-10">+ <ItemThumbnail type={type} />+ <VStack spacing={0} className="min-w-0">+ <span className="font-semibold line-clamp-1">+ {label?.readableIdWithRevision ??+ label?.readableId ??+ item.itemId}+ {newItemLabel && (+ <>+ <span className="text-muted-foreground font-normal">+ {" → "}+ </span>+ {newItemLabel}+ </>+ )}+ </span>+ {label?.name && (+ <span className="text-muted-foreground text-xs truncate line-clamp-1">+ {label.name}+ </span>+ )}+ </VStack>+ </HStack>+ {!isDisabled && (+ <div className="absolute right-2">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label={t`More`}+ className="opacity-0 group-hover:opacity-100 group-active:opacity-100 data-[state=open]:opacity-100"+ icon={<LuEllipsisVertical />}+ variant="solid"+ onClick={(e) => e.stopPropagation()}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent>+ <DropdownMenuItem+ destructive+ onClick={(e) => {+ e.stopPropagation();+ deleteFetcher.submit(+ {},+ {+ method: "post",+ action: path.to.deleteChangeOrderAffected(+ changeOrderId,+ item.id+ )+ }+ );+ }}+ >+ <DropdownMenuIcon icon={<LuTrash />} />+ <Trans>Delete</Trans>+ </DropdownMenuItem>+ <DropdownMenuItem asChild>+ <Link to={getLinkToItemDetails(type, item.itemId)}>+ <DropdownMenuIcon+ icon={<MethodItemTypeIcon type={type} />}+ />+ <Trans>View Item Master</Trans>+ </Link>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ )}+ </HStack>+ </Link>+ </VStack>+ );+}diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderForm.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderForm.tsxnew file mode 100644index 0000000000..ef5f4badba--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderForm.tsx@@ -0,0 +1,212 @@+import {+ Combobox,+ DatePicker,+ Select,+ TextArea,+ ValidatedForm+} from "@carbon/form";+import {+ Button,+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ HStack,+ ModalDrawer,+ ModalDrawerBody,+ ModalDrawerContent,+ ModalDrawerFooter,+ ModalDrawerHeader,+ ModalDrawerProvider,+ ModalDrawerTitle,+ VStack+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import type { FetcherWithComponents } from "react-router";+import type { z } from "zod";+import { Enumerable } from "~/components/Enumerable";+import {+ CustomFormFields,+ Employee,+ Hidden,+ Input,+ Submit+} from "~/components/Form";+import { usePermissions } from "~/hooks";+import type { ListItem } from "~/types";+import { path } from "~/utils/path";+import { changeOrderPriority, changeOrderValidator } from "../../items.models";+import ChangeOrderPriority from "./ChangeOrderPriority";++type ChangeOrderFormValues = z.infer<typeof changeOrderValidator>;++type ChangeOrderFormProps = {+ initialValues: ChangeOrderFormValues;+ types: ListItem[];+ // "page" (default) renders in a Card on the create route; "modal" renders in a+ // ModalDrawer launched from an item detail page (item pre-selected as affected).+ type?: "page" | "modal";+ open?: boolean;+ onClose?: () => void;+ fetcher?: FetcherWithComponents<unknown>;+};++const ChangeOrderForm = ({+ initialValues,+ types,+ type = "page",+ open,+ onClose,+ fetcher+}: ChangeOrderFormProps) => {+ const { t } = useLingui();+ const permissions = usePermissions();+ const isEditing = initialValues.id !== undefined;+ const isModal = type === "modal";++ const fields = (+ <>+ <Hidden name="id" />+ <Hidden name="changeOrderId" />+ {/* Linked NCR is set by the source (e.g. "Create Change Order" from an+ Issue) and carried silently — not a user-editable field. */}+ <Hidden name="nonConformanceId" />+ {/* Affected Parts are added on the CO detail page (top-to-bottom flow), not+ chosen here. The create form only carries any pre-selected item (e.g.+ when opened from a part page via CreateChangeOrderModal) as hidden+ inputs so it's still attached on create. */}+ {!isEditing &&+ (initialValues.affectedItemIds ?? []).map((itemId) => (+ <input+ key={itemId}+ type="hidden"+ name="affectedItemIds"+ value={itemId}+ />+ ))}++ <VStack spacing={4}>+ <div+ className={`grid w-full gap-4 grid-cols-1 ${+ isModal ? "" : "md:grid-cols-2"+ }`}+ >+ <Input name="name" label={t`Name`} />+ <Combobox+ name="changeOrderTypeId"+ label={t`Category`}+ options={types.map((coType) => ({+ label: <Enumerable value={coType.name} />,+ value: coType.id+ }))}+ />+ </div>+ <TextArea name="reasonForChange" label={t`Reason for Change`} />+ <TextArea name="description" label={t`Description of Change`} />+ <div className="grid w-full gap-4 grid-cols-1 md:grid-cols-2">+ <Employee name="assignee" label={t`Owner`} />+ <Select+ name="priority"+ label={t`Priority`}+ options={changeOrderPriority.map((priority) => ({+ label: <ChangeOrderPriority priority={priority} />,+ value: priority+ }))}+ />+ <DatePicker name="openDate" label={t`Open Date`} />+ <DatePicker name="dueDate" label={t`Due Date`} />+ <CustomFormFields table="changeOrder" />+ </div>+ </VStack>+ </>+ );++ const submit = (+ // No unsaved-changes blocker: Save intentionally redirects to the new CO, so+ // the guard would always fire on submit (matches other create forms).+ <Submit+ withBlocker={false}+ isDisabled={+ isEditing+ ? !permissions.can("update", "parts")+ : !permissions.can("create", "parts")+ }+ >+ <Trans>Save</Trans>+ </Submit>+ );++ if (isModal) {+ return (+ <ModalDrawerProvider type="modal">+ <ModalDrawer+ open={open}+ onOpenChange={(o) => {+ if (!o) onClose?.();+ }}+ >+ <ModalDrawerContent>+ <ValidatedForm+ method="post"+ action={path.to.newChangeOrder}+ validator={changeOrderValidator}+ defaultValues={initialValues}+ fetcher={fetcher}+ className="flex flex-col h-full"+ >+ <ModalDrawerHeader>+ <ModalDrawerTitle>+ <Trans>New Change Order</Trans>+ </ModalDrawerTitle>+ </ModalDrawerHeader>+ <ModalDrawerBody>{fields}</ModalDrawerBody>+ <ModalDrawerFooter>+ <HStack>+ {submit}+ <Button size="md" variant="solid" onClick={() => onClose?.()}>+ <Trans>Cancel</Trans>+ </Button>+ </HStack>+ </ModalDrawerFooter>+ </ValidatedForm>+ </ModalDrawerContent>+ </ModalDrawer>+ </ModalDrawerProvider>+ );+ }++ return (+ <Card>+ <ValidatedForm+ method="post"+ validator={changeOrderValidator}+ defaultValues={initialValues}+ className="w-full"+ >+ <CardHeader>+ <CardTitle>+ {isEditing ? (+ <Trans>Change Order</Trans>+ ) : (+ <Trans>New Change Order</Trans>+ )}+ </CardTitle>+ {!isEditing && (+ <CardDescription>+ <Trans>+ A change order tracks a controlled engineering or manufacturing+ change through review and implementation.+ </Trans>+ </CardDescription>+ )}+ </CardHeader>+ <CardContent>{fields}</CardContent>+ <CardFooter>{submit}</CardFooter>+ </ValidatedForm>+ </Card>+ );+};++export default ChangeOrderForm;diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderHeader.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderHeader.tsxnew file mode 100644index 0000000000..24f4c554f3--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderHeader.tsx@@ -0,0 +1,222 @@+import {+ Button,+ Copy,+ cn,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuIcon,+ DropdownMenuItem,+ DropdownMenuTrigger,+ Heading,+ HStack,+ IconButton,+ useDisclosure,+ VStack+} from "@carbon/react";+import { useLingui } from "@lingui/react/macro";+import {+ LuCircleCheck,+ LuCircleStop,+ LuEllipsisVertical,+ LuLoaderCircle,+ LuStepForward,+ LuTrash+} from "react-icons/lu";+import { Link, useFetcher, useParams } from "react-router";+import { useAuditLog } from "~/components/AuditLog";+import Confirm from "~/components/Modals/Confirm/Confirm";+import ConfirmDelete from "~/components/Modals/ConfirmDelete";+import { usePermissions, useRouteData, useUser } from "~/hooks";+import { path } from "~/utils/path";+import {+ type changeOrderStatus,+ changeOrderStatusTransitions,+ isChangeOrderLocked+} from "../../items.models";+import type { ChangeOrder } from "../../types";+import ChangeOrderStatus from "./ChangeOrderStatus";+import { releaseDialogOpenAtom } from "./releaseDialog.store";++const ChangeOrderHeader = () => {+ const { id } = useParams();+ if (!id) throw new Error("id not found");++ const routeData = useRouteData<{ changeOrder: ChangeOrder }>(+ path.to.changeOrder(id)+ );++ const status = routeData?.changeOrder?.status ?? "Draft";+ const { t } = useLingui();+ const permissions = usePermissions();+ const { company } = useUser();+ const statusFetcher = useFetcher<{}>();+ const deleteModal = useDisclosure();+ const cancelModal = useDisclosure();++ const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({+ entityType: "changeOrder",+ entityId: id,+ companyId: company.id,+ variant: "dropdown"+ });++ const isLocked = isChangeOrderLocked(status);+ const nextStatus =+ changeOrderStatusTransitions[+ status as (typeof changeOrderStatus)[number]+ ]?.[0] ?? null;++ return (+ <>+ <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border h-[50px] overflow-x-auto scrollbar-hide dark:border-none dark:shadow-[inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)]">+ <VStack spacing={0}>+ <HStack>+ <Link to={path.to.changeOrderDetails(id)}>+ <Heading size="h4" className="flex items-center gap-2">+ <span>{routeData?.changeOrder?.changeOrderId}</span>+ </Heading>+ </Link>+ <span className={cn(isLocked && "line-through")}>+ <ChangeOrderStatus status={routeData?.changeOrder?.status} />+ </span>+ <Copy text={routeData?.changeOrder?.changeOrderId ?? ""} />+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label={t`More options`}+ icon={<LuEllipsisVertical />}+ variant="secondary"+ size="sm"+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent>+ {auditLogTrigger}+ {status === "Cancelled" && (+ <DropdownMenuItem+ disabled={+ statusFetcher.state !== "idle" ||+ !permissions.can("update", "parts")+ }+ onClick={() => {+ statusFetcher.submit(+ { id, fromStatus: status, status: "Draft" },+ {+ method: "post",+ action: path.to.changeOrderStatus(id)+ }+ );+ }}+ >+ <DropdownMenuIcon icon={<LuLoaderCircle />} />+ {t`Reopen`}+ </DropdownMenuItem>+ )}+ <DropdownMenuItem+ destructive+ disabled={+ !permissions.can("delete", "parts") ||+ !permissions.is("employee")+ }+ onClick={deleteModal.onOpen}+ >+ <DropdownMenuIcon icon={<LuTrash />} />+ {t`Delete Change Order`}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </HStack>+ </VStack>++ <HStack spacing={2}>+ {/* The full stage flow (green-dot progress) lives in the middle pane+ (ChangeOrderStatusFlow); the header keeps only the canonical status+ badge (above) + the advance/release action. */}++ {/* Cancel — a header action (opens the confirm modal) sitting beside the+ advance/release primary action. Reopen (from Cancelled) stays in the+ ⋮ menu. */}+ {status !== "Cancelled" && !isLocked && (+ <Button+ leftIcon={<LuCircleStop />}+ variant="secondary"+ isDisabled={!permissions.can("update", "parts")}+ onClick={cancelModal.onOpen}+ >+ {t`Cancel`}+ </Button>+ )}++ {/* Implementation → Done is a release: it opens the review + confirm+ dialog (which carries the merge resolution), not a one-click stage+ advance. The header only auto-advances the earlier stages. */}+ {nextStatus && nextStatus !== "Done" && !isLocked && (+ <statusFetcher.Form+ method="post"+ action={path.to.changeOrderStatus(id)}+ >+ <input type="hidden" name="id" value={id} />+ <input type="hidden" name="fromStatus" value={status} />+ <input type="hidden" name="status" value={nextStatus} />+ <Button+ type="submit"+ rightIcon={<LuStepForward />}+ variant="primary"+ isDisabled={+ statusFetcher.state !== "idle" ||+ !permissions.can("update", "parts")+ }+ isLoading={statusFetcher.state !== "idle"}+ >+ {t`Advance to ${nextStatus}`}+ </Button>+ </statusFetcher.Form>+ )}++ {status === "Implementation" && !isLocked && (+ <Button+ leftIcon={<LuCircleCheck />}+ variant="primary"+ isDisabled={!permissions.can("update", "parts")}+ onClick={() => releaseDialogOpenAtom.set(true)}+ >+ {t`Release`}+ </Button>+ )}+ </HStack>+ </div>+ {deleteModal.isOpen && (+ <ConfirmDelete+ action={path.to.deleteChangeOrder(id)}+ isOpen={deleteModal.isOpen}+ name={routeData?.changeOrder?.changeOrderId ?? ""}+ text={t`Are you sure you want to delete ${+ routeData?.changeOrder?.changeOrderId ?? ""+ }? This cannot be undone.`}+ onCancel={deleteModal.onClose}+ onSubmit={deleteModal.onClose}+ />+ )}+ {cancelModal.isOpen && (+ <Confirm+ action={path.to.changeOrderStatus(id)}+ title={t`Cancel change order`}+ text={t`Are you sure you want to cancel ${+ routeData?.changeOrder?.changeOrderId ?? ""+ }? It will be closed and read-only until you reopen it.`}+ confirmText={t`Cancel Change Order`}+ cancelText={t`Keep Open`}+ confirmVariant="destructive"+ onCancel={cancelModal.onClose}+ onSubmit={cancelModal.onClose}+ >+ <input type="hidden" name="id" value={id} />+ <input type="hidden" name="fromStatus" value={status} />+ <input type="hidden" name="status" value="Cancelled" />+ </Confirm>+ )}+ {auditLogDrawer}+ </>+ );+};++export default ChangeOrderHeader;diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderPriority.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderPriority.tsxnew file mode 100644index 0000000000..24874d75cf--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderPriority.tsx@@ -0,0 +1,50 @@+import { BsExclamationSquareFill } from "react-icons/bs";+import { HighPriorityIcon } from "~/assets/icons/HighPriorityIcon";+import { LowPriorityIcon } from "~/assets/icons/LowPriorityIcon";+import { MediumPriorityIcon } from "~/assets/icons/MediumPriorityIcon";+import type { changeOrderPriority } from "../../items.models";++type ChangeOrderPriorityProps = {+ priority?: (typeof changeOrderPriority)[number] | null;+ className?: string;+};++function ChangeOrderPriority({+ priority,+ className+}: ChangeOrderPriorityProps) {+ switch (priority) {+ case "Low":+ return (+ <div className={`flex gap-1 items-center ${className ?? ""}`}>+ <LowPriorityIcon />+ <span>{priority}</span>+ </div>+ );+ case "Medium":+ return (+ <div className={`flex gap-1 items-center ${className ?? ""}`}>+ <MediumPriorityIcon />+ <span>{priority}</span>+ </div>+ );+ case "High":+ return (+ <div className={`flex gap-1 items-center ${className ?? ""}`}>+ <HighPriorityIcon />+ <span>{priority}</span>+ </div>+ );+ case "Critical":+ return (+ <div className={`flex gap-1 items-center ${className ?? ""}`}>+ <BsExclamationSquareFill className="text-red-500" />+ <span>{priority}</span>+ </div>+ );+ default:+ return null;+ }+}++export default ChangeOrderPriority;diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderProperties.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderProperties.tsxnew file mode 100644index 0000000000..2e20c741af--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderProperties.tsx@@ -0,0 +1,343 @@+import {+ DatePicker,+ InputControlled,+ Select,+ ValidatedForm+} from "@carbon/form";+import {+ Button,+ HStack,+ Separator,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+ toast,+ VStack+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import type { ReactNode } from "react";+import { useCallback, useEffect } from "react";+import { LuLink } from "react-icons/lu";+import { Link, useFetcher, useParams } from "react-router";+import { z } from "zod";+import { Assignee, EmployeeAvatar } from "~/components";+import { Enumerable } from "~/components/Enumerable";+import { Combobox } from "~/components/Form";+import { usePermissions, useRouteData } from "~/hooks";+import type { action } from "~/routes/x+/items+/change-order+/update";+import type { ListItem } from "~/types";+import { path } from "~/utils/path";+import { copyToClipboard } from "~/utils/string";+import { changeOrderPriority, isChangeOrderLocked } from "../../items.models";+import type { ChangeOrder } from "../../types";+import type { AffectedItemDraft } from "./affectedItem.types";+import ChangeOrderReleaseMerge from "./ChangeOrderReleaseMerge";+import ImpactPanel, { type ChangeOrderImpactItem } from "./ImpactPanel";++// One CO-centric section — the xxs uppercase heading + content used by the+// PurchaseOrder / SalesOrder / Quote property sidebars. Sections are separated by+// the container's VStack spacing (whitespace), matching those sidebars exactly.+function PropertiesSection({+ title,+ accessory,+ children+}: {+ title: ReactNode;+ accessory?: ReactNode;+ children: ReactNode;+}) {+ return (+ <VStack spacing={2} className="w-full">+ <HStack className="w-full justify-between">+ <h3 className="text-xxs text-foreground/70 uppercase font-light tracking-wide">+ {title}+ </h3>+ {accessory}+ </HStack>+ {children}+ </VStack>+ );+}++// Properties panel (right panel) of the change-order workspace: all CO-centric+// content (not tied to any single affected item), as one consistent sidebar —+// Release (at Implementation), the editable property fields, and Impact. (Reason+// for change, description, and the action tasks live on the top-level detail+// route.) Self-contained: reads everything from the $id route loader so+// ResizablePanels can render it with only a `key` (mirrors SalesOrderProperties).+// Owns its own width / scroll / border / padding.+const ChangeOrderProperties = () => {+ const { id } = useParams();+ if (!id) throw new Error("id not found");++ const { t } = useLingui();+ const permissions = usePermissions();++ const routeData = useRouteData<{+ changeOrder: ChangeOrder;+ types: ListItem[];+ affectedItems: AffectedItemDraft[];+ impactUsedIn: ChangeOrderImpactItem[];+ nonConformanceOptions: {+ id: string;+ nonConformanceId: string;+ name: string;+ }[];+ linkedNonConformance: {+ id: string;+ nonConformanceId: string;+ name: string;+ } | null;+ }>(path.to.changeOrder(id));++ const changeOrder = routeData?.changeOrder;+ const types = routeData?.types ?? [];+ const affectedItems = routeData?.affectedItems ?? [];+ const impactUsedIn = routeData?.impactUsedIn ?? [];+ const nonConformanceOptions = routeData?.nonConformanceOptions ?? [];+ const linkedNonConformance = routeData?.linkedNonConformance ?? null;+ const isLocked = isChangeOrderLocked(changeOrder?.status);+ const isImplementation = changeOrder?.status === "Implementation";+ const canUpdate = permissions.can("update", "parts");++ const fetcher = useFetcher<typeof action>();+ useEffect(() => {+ if (fetcher.data?.error) {+ toast.error(fetcher.data.error.message);+ }+ }, [fetcher.data]);++ // biome-ignore lint/correctness/useExhaustiveDependencies: id is stable+ const onUpdate = useCallback(+ (field: string, value: string | null) => {+ const formData = new FormData();+ formData.append("id", id);+ formData.append("field", field);+ formData.append("value", value?.toString() ?? "");+ fetcher.submit(formData, {+ method: "post",+ action: path.to.updateChangeOrder+ });+ },+ [id]+ );++ // The read-only changes shown in the release confirmation dialog.+ const changes = affectedItems.map((a) => ({+ id: a.affectedItem.id,+ label: a.affectedItem.item?.readableIdWithRevision ?? a.affectedItem.itemId,+ changeType: a.affectedItem.changeType,+ version: a.makeMethod?.version,+ diff: a.diff+ }));++ return (+ <VStack+ spacing={4}+ className="w-96 flex-shrink-0 bg-card h-full overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent border-l border-border px-4 pt-2 pb-12 text-sm"+ >+ {/* Release is triggered from the header button (opens this confirmation+ dialog via releaseDialogOpenAtom). The dialog is mounted here — headless+ until opened — so it renders nothing in the panel itself. */}+ {isImplementation && changeOrder && (+ <ChangeOrderReleaseMerge+ changeOrderId={id}+ status={changeOrder.status}+ changes={changes}+ />+ )}++ <VStack spacing={2}>+ <HStack className="w-full justify-between">+ <h3 className="text-xxs text-foreground/70 uppercase font-light tracking-wide">+ <Trans>Properties</Trans>+ </h3>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ aria-label={t`Copy link`}+ size="sm"+ className="p-1"+ onClick={() =>+ copyToClipboard(+ window.location.origin + path.to.changeOrder(id)+ )+ }+ >+ <LuLink className="w-3 h-3" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <Trans>Copy link to change order</Trans>+ </TooltipContent>+ </Tooltip>+ </HStack>+ <VStack spacing={1}>+ <span className="text-sm tracking-tight">+ {changeOrder?.changeOrderId}+ </span>+ <ValidatedForm+ defaultValues={{ name: changeOrder?.name ?? undefined }}+ validator={z.object({ name: z.string() })}+ className="w-full"+ >+ <InputControlled+ label=""+ name="name"+ size="sm"+ inline+ isReadOnly={!canUpdate || isLocked}+ value={changeOrder?.name ?? ""}+ onBlur={(e) => {+ onUpdate("name", e.target.value ?? null);+ }}+ className="text-muted-foreground"+ />+ </ValidatedForm>+ </VStack>+ </VStack>++ <VStack spacing={2}>+ <h3 className="text-xs text-muted-foreground">+ <Trans>Category</Trans>+ </h3>+ <ValidatedForm+ defaultValues={{+ changeOrderTypeId: changeOrder?.changeOrderTypeId ?? ""+ }}+ validator={z.object({ changeOrderTypeId: z.string().optional() })}+ className="w-full"+ >+ <Combobox+ name="changeOrderTypeId"+ label=""+ isReadOnly={!canUpdate || isLocked}+ inline={(value) => (+ <Enumerable+ value={types.find((ty) => ty.id === value)?.name ?? null}+ />+ )}+ options={types.map((ty) => ({ value: ty.id, label: ty.name }))}+ onChange={(value) =>+ onUpdate("changeOrderTypeId", value?.value ?? null)+ }+ />+ </ValidatedForm>+ </VStack>++ <VStack spacing={2}>+ <h3 className="text-xs text-muted-foreground">+ <Trans>Owner</Trans>+ </h3>+ <Assignee+ id={id}+ table="changeOrder"+ size="sm"+ value={changeOrder?.assignee ?? ""}+ isReadOnly={!canUpdate || isLocked}+ />+ </VStack>++ <ValidatedForm+ defaultValues={{ openDate: changeOrder?.openDate ?? "" }}+ validator={z.object({ openDate: z.string().optional() })}+ className="w-full"+ >+ <DatePicker+ name="openDate"+ label={t`Open Date`}+ inline+ isDisabled={!canUpdate || isLocked}+ onChange={(date) => onUpdate("openDate", date)}+ />+ </ValidatedForm>++ <ValidatedForm+ defaultValues={{ priority: changeOrder?.priority ?? "" }}+ validator={z.object({ priority: z.string().optional() })}+ className="w-full"+ >+ <Select+ name="priority"+ label={t`Priority`}+ inline={(value) => <span>{value}</span>}+ isReadOnly={!canUpdate || isLocked}+ options={changeOrderPriority.map((priority) => ({+ value: priority,+ label: priority+ }))}+ onChange={(value) => onUpdate("priority", value?.value ?? null)}+ />+ </ValidatedForm>++ <VStack spacing={2}>+ <h3 className="text-xs text-muted-foreground">+ <Trans>Linked NCR</Trans>+ </h3>+ <ValidatedForm+ defaultValues={{+ nonConformanceId: changeOrder?.nonConformanceId ?? ""+ }}+ validator={z.object({ nonConformanceId: z.string().optional() })}+ className="w-full"+ >+ <Combobox+ name="nonConformanceId"+ label=""+ isReadOnly={!canUpdate || isLocked}+ inline={(value) => {+ // Chip shows just the NCR id/number — the full name is shown in the+ // link below, so repeating it here only overflows the chip.+ const nonConformanceId =+ linkedNonConformance && linkedNonConformance.id === value+ ? linkedNonConformance.nonConformanceId+ : (nonConformanceOptions.find((nc) => nc.id === value)+ ?.nonConformanceId ?? null);+ return (+ <Enumerable+ value={nonConformanceId}+ className="max-w-[140px]"+ />+ );+ }}+ options={nonConformanceOptions.map((nc) => ({+ value: nc.id,+ label: `${nc.nonConformanceId} — ${nc.name}`+ }))}+ onChange={(value) =>+ onUpdate("nonConformanceId", value?.value ?? null)+ }+ />+ </ValidatedForm>+ {changeOrder?.nonConformanceId && (+ <Link+ className="text-xs text-primary hover:underline"+ to={path.to.issue(changeOrder.nonConformanceId)}+ >+ {linkedNonConformance+ ? `${linkedNonConformance.nonConformanceId} — ${linkedNonConformance.name}`+ : changeOrder.nonConformanceId}+ </Link>+ )}+ </VStack>++ <VStack spacing={2}>+ <h3 className="text-xs text-muted-foreground">+ <Trans>Created By</Trans>+ </h3>+ <EmployeeAvatar employeeId={changeOrder?.createdBy ?? ""} size="xxs" />+ </VStack>++ <Separator />++ {/* Reason for change, description, and the action tasks now live on the+ top-level detail route ($id.details), not here. */}+ <PropertiesSection title={<Trans>Impact</Trans>}>+ <ImpactPanel embedded items={impactUsedIn} />+ </PropertiesSection>+ </VStack>+ );+};++export default ChangeOrderProperties;diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderReleaseMerge.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderReleaseMerge.tsxnew file mode 100644index 0000000000..7438c14979--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderReleaseMerge.tsx@@ -0,0 +1,142 @@+import {+ Button,+ HStack,+ Modal,+ ModalBody,+ ModalContent,+ ModalDescription,+ ModalFooter,+ ModalHeader,+ ModalTitle,+ toast,+ VStack+} from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import { useStore } from "@nanostores/react";+import { useEffect } from "react";+import { LuCircleCheck } from "react-icons/lu";+import { useFetcher } from "react-router";+import { path } from "~/utils/path";+import type {+ ChangeOrderChangeType,+ ChangeOrderItemDiff+} from "../../items.models";+import ChangeOrderDiffViewer from "./ChangeOrderDiffViewer";+import { releaseDialogOpenAtom } from "./releaseDialog.store";++// One affected item's read-only changes, shown in the release confirmation.+export type ReleaseChange = {+ id: string;+ label: string;+ // The item's description — rendered under the label by the overview Changes+ // rollup (ChangeOrderChanges); the release dialog doesn't populate it.+ name?: string | null;+ // Change type + draft make-method version, for the ChangeTypeBadge shown in+ // the overview Changes rollup.+ changeType: ChangeOrderChangeType;+ version?: number | null;+ diff?: ChangeOrderItemDiff;+};++// The Implementation → Done release control, rendered as a confirmation dialog+// (opened from the header button or the rail's Release section via+// releaseDialogOpenAtom). Releasing just activates each affected item's edited+// Draft make method as a new Active version and archives the prior one — the+// prior version is kept as history, so there is no merge/conflict step. The user+// reviews each item's changes, then confirms. Release is never a one-click action.+export default function ChangeOrderReleaseMerge({+ changeOrderId,+ status,+ changes+}: {+ changeOrderId: string;+ status: string | null;+ changes: ReleaseChange[];+}) {+ const fetcher = useFetcher<{ success?: boolean }>();+ const open = useStore(releaseDialogOpenAtom);++ useEffect(() => {+ const data = fetcher.data as+ | { error?: { message: string }; success?: boolean }+ | undefined;+ if (data?.error) toast.error(data.error.message);+ if (data?.success) releaseDialogOpenAtom.set(false);+ }, [fetcher.data]);++ // Close the dialog if this control unmounts (e.g. navigating away).+ useEffect(() => () => releaseDialogOpenAtom.set(false), []);++ if (status !== "Implementation") return null;++ const isSubmitting = fetcher.state !== "idle";++ return (+ <Modal open={open} onOpenChange={(v) => releaseDialogOpenAtom.set(v)}>+ <ModalContent className="flex h-[90vh] w-[90vw] flex-col p-0 sm:max-w-3xl">+ <ModalHeader className="px-6 pt-6">+ <ModalTitle>+ <Trans>Release change order</Trans>+ </ModalTitle>+ <ModalDescription>+ <Trans>+ Review each item's changes, then confirm — releasing can't be+ undone.+ </Trans>+ </ModalDescription>+ </ModalHeader>++ <ModalBody className="flex-1 overflow-y-auto px-6 scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">+ <VStack spacing={4} className="w-full">+ {changes.length === 0 ? (+ <span className="text-sm italic text-muted-foreground">+ <Trans>No affected items.</Trans>+ </span>+ ) : (+ changes.map((c) => (+ <VStack key={c.id} spacing={2} className="w-full min-w-0">+ <h3+ className="max-w-full truncate text-sm font-medium text-foreground"+ title={c.label}+ >+ {c.label}+ </h3>+ <ChangeOrderDiffViewer diff={c.diff} />+ </VStack>+ ))+ )}+ </VStack>+ </ModalBody>++ <ModalFooter className="border-t border-border px-6 py-4">+ <HStack spacing={2} className="w-full justify-end">+ <Button+ variant="secondary"+ onClick={() => releaseDialogOpenAtom.set(false)}+ isDisabled={isSubmitting}+ >+ <Trans>Cancel</Trans>+ </Button>+ <fetcher.Form+ method="post"+ action={path.to.changeOrderStatus(changeOrderId)}+ >+ <input type="hidden" name="id" value={changeOrderId} />+ <input type="hidden" name="fromStatus" value="Implementation" />+ <input type="hidden" name="status" value="Done" />+ <Button+ type="submit"+ leftIcon={<LuCircleCheck />}+ variant="primary"+ isDisabled={isSubmitting}+ isLoading={isSubmitting}+ >+ <Trans>Confirm & release</Trans>+ </Button>+ </fetcher.Form>+ </HStack>+ </ModalFooter>+ </ModalContent>+ </Modal>+ );+}diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderStatus.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderStatus.tsxnew file mode 100644index 0000000000..92af9dd90a--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderStatus.tsx@@ -0,0 +1,30 @@+import { Status } from "@carbon/react";+import type { ChangeOrderStatus as ChangeOrderStatusType } from "../../types";++// Stage → badge color. Done is success (green); the open stages step through+// gray → blue → yellow → orange as work progresses; Cancelled is red.+const CHANGE_ORDER_STATUS_COLOR_MAP: Record<+ string,+ "green" | "orange" | "red" | "yellow" | "blue" | "gray" | "purple"+> = {+ Draft: "gray",+ Start: "blue",+ "Engineering Complete": "yellow",+ Implementation: "orange",+ Done: "green",+ Cancelled: "red"+};++type ChangeOrderStatusProps = {+ status?: ChangeOrderStatusType | null;+};++const ChangeOrderStatus = ({ status }: ChangeOrderStatusProps) => {+ if (!status) return null;+ const color = CHANGE_ORDER_STATUS_COLOR_MAP[status];+ if (!color) return null;++ return <Status color={color}>{status}</Status>;+};++export default ChangeOrderStatus;diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderStatusFlow.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderStatusFlow.tsxnew file mode 100644index 0000000000..ecd01c4460--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrderStatusFlow.tsx@@ -0,0 +1,50 @@+import { cn, Menubar } from "@carbon/react";+import { LuCheck, LuCircle, LuCircleDot } from "react-icons/lu";+import { changeOrderStageFlow } from "../../items.models";+import type { ChangeOrderStatus } from "../../types";++// The change-order stage flow, mirroring the sales OpportunityState bar: one+// static label per stage with a progress icon that turns emerald on the active+// (and completed) stages — the "green dot" on the current step. Display-only+// (stage changes go through the header's advance/release action), so each stage+// is a plain <p>, not a button — no hover/click affordance, just the progress bar.+export default function ChangeOrderStatusFlow({+ status+}: {+ status: ChangeOrderStatus;+}) {+ // -1 for a Cancelled CO (not part of the forward flow) — every stage renders+ // inactive, which is the desired "no progress" look.+ const activeIndex = changeOrderStageFlow.indexOf(status);++ return (+ <Menubar>+ {changeOrderStageFlow.map((stage, index) => {+ const isCurrent = index === activeIndex;+ const isCompleted = index < activeIndex;+ const Icon = isCompleted ? LuCheck : isCurrent ? LuCircleDot : LuCircle;+ return (+ <p+ key={stage}+ className={cn(+ "flex items-center gap-2 px-3 py-1.5 text-sm",+ isCurrent+ ? "text-foreground font-semibold"+ : isCompleted+ ? "text-foreground/70"+ : "text-muted-foreground"+ )}+ >+ <Icon+ className={cn(+ (isCurrent || isCompleted) && "text-emerald-500",+ !isCurrent && !isCompleted && "opacity-80"+ )}+ />+ {stage}+ </p>+ );+ })}+ </Menubar>+ );+}diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrdersTable.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrdersTable.tsxnew file mode 100644index 0000000000..2ecf3e47e8--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeOrdersTable.tsx@@ -0,0 +1,340 @@+import { Badge, MenuIcon, MenuItem, useDisclosure } from "@carbon/react";+import { useLingui } from "@lingui/react/macro";+import type { ColumnDef } from "@tanstack/react-table";+import { memo, useCallback, useMemo, useState } from "react";+import { flushSync } from "react-dom";+import {+ LuArrowRight,+ LuBlocks,+ LuBookMarked,+ LuCalendar,+ LuCircleGauge,+ LuGitPullRequestArrow,+ LuPencil,+ LuSignal,+ LuTrash,+ LuUser+} from "react-icons/lu";+import { useNavigate } from "react-router";+import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";+import { Enumerable } from "~/components/Enumerable";+import { ConfirmDelete } from "~/components/Modals";+import { useDateFormatter, usePermissions } from "~/hooks";+import { useCustomColumns } from "~/hooks/useCustomColumns";+import { useRealtime } from "~/hooks/useRealtime";+import { useItems } from "~/stores/items";+import { usePeople } from "~/stores/people";+import type { ListItem } from "~/types";+import { path } from "~/utils/path";+import {+ type ChangeOrderChangeType,+ changeOrderPriority,+ changeOrderStatus+} from "../../items.models";+import type { ChangeOrderListItem } from "../../types";+import ChangeOrderPriority from "./ChangeOrderPriority";+import ChangeOrderStatus from "./ChangeOrderStatus";+import ChangeTypeBadge from "./ChangeTypeBadge";++type ChangeOrdersTableProps = {+ data: ChangeOrderListItem[];+ types: ListItem[];+ count: number;+};++// One entry of the changeOrders view's `affectedItems` jsonb rollup — enough to+// render the expanded row (item label + change type + OLD→NEW), resolving ids to+// readable ids client-side via the items store.+type AffectedItemSummary = {+ id: string;+ itemId: string;+ changeType: ChangeOrderChangeType;+ newItemId: string | null;+};++const ChangeOrdersTable = memo(+ ({ data, types, count }: ChangeOrdersTableProps) => {+ const navigate = useNavigate();+ const { t } = useLingui();+ const { formatDate } = useDateFormatter();+ const permissions = usePermissions();+ const deleteDisclosure = useDisclosure();+ const [selectedChangeOrder, setSelectedChangeOrder] =+ useState<ChangeOrderListItem | null>(null);++ const customColumns = useCustomColumns<ChangeOrderListItem>("changeOrder");+ const [people] = usePeople();+ const [items] = useItems();++ const itemsById = useMemo(+ () => new Map((items ?? []).map((i) => [i.id, i.readableIdWithRevision])),+ [items]+ );+ const resolveItemId = useCallback(+ (id?: string | null) => (id ? (itemsById.get(id) ?? id) : null),+ [itemsById]+ );++ useRealtime("changeOrder");++ const columns = useMemo<ColumnDef<ChangeOrderListItem>[]>(() => {+ const defaultColumns: ColumnDef<ChangeOrderListItem>[] = [+ {+ accessorKey: "changeOrderId",+ header: t`Change Order`,+ cell: ({ row }) => (+ <Hyperlink to={path.to.changeOrder(row.original.id!)}>+ <div className="flex flex-col gap-0">+ <span className="text-sm font-medium">+ {row.original.changeOrderId}+ </span>+ <span className="text-xs text-muted-foreground">+ {row.original.name}+ </span>+ </div>+ </Hyperlink>+ ),+ meta: {+ icon: <LuBookMarked />+ }+ },+ {+ accessorKey: "status",+ header: t`Status`,+ cell: ({ row }) => <ChangeOrderStatus status={row.original.status} />,+ meta: {+ icon: <LuCircleGauge />,+ filter: {+ type: "static",+ options: changeOrderStatus.map((status) => ({+ label: status,+ value: status+ }))+ }+ }+ },+ {+ accessorKey: "changeOrderTypeId",+ header: t`Category`,+ cell: ({ row }) => (+ <Enumerable+ value={+ types.find((type) => type.id === row.original.changeOrderTypeId)+ ?.name ?? null+ }+ />+ ),+ meta: {+ icon: <LuGitPullRequestArrow />,+ filter: {+ type: "static",+ options: types.map((type) => ({+ label: type.name,+ value: type.id+ }))+ }+ }+ },+ {+ accessorKey: "itemIds",+ header: t`Items`,+ cell: ({ row }) => {+ const ids = row.original.itemIds ?? [];+ if (ids.length === 0)+ return <span className="text-muted-foreground">—</span>;+ const shown = ids.slice(0, 2);+ const extra = ids.length - shown.length;+ return (+ <div className="flex items-center gap-1">+ {shown.map((id) => (+ <Badge key={id} variant="outline">+ {resolveItemId(id)}+ </Badge>+ ))}+ {extra > 0 && <Badge variant="secondary">{`+${extra}`}</Badge>}+ </div>+ );+ },+ meta: {+ icon: <LuBlocks />,+ pluralHeader: t`Items`,+ filter: {+ type: "static",+ options: (items ?? []).map((item) => ({+ value: item.id,+ label: item.readableIdWithRevision+ })),+ isArray: true+ },+ exportValue: (row: ChangeOrderListItem) =>+ (row.itemIds ?? []).map((id) => resolveItemId(id)).join(", ")+ }+ },+ {+ accessorKey: "priority",+ header: t`Priority`,+ cell: ({ row }) => (+ <ChangeOrderPriority priority={row.original.priority} />+ ),+ meta: {+ icon: <LuSignal />,+ filter: {+ type: "static",+ options: changeOrderPriority.map((priority) => ({+ label: priority,+ value: priority+ }))+ }+ }+ },+ {+ accessorKey: "assignee",+ header: t`Owner`,+ cell: ({ row }) => (+ <EmployeeAvatar employeeId={row.original.assignee} />+ ),+ meta: {+ icon: <LuUser />,+ filter: {+ type: "static",+ options: people.map((employee) => ({+ value: employee.id,+ label: employee.name+ }))+ }+ }+ },+ {+ accessorKey: "openDate",+ header: t`Open Date`,+ cell: ({ row }) => formatDate(row.original.openDate),+ meta: {+ icon: <LuCalendar />+ }+ }+ ];+ return [...defaultColumns, ...customColumns];+ }, [customColumns, people, items, resolveItemId, types, t, formatDate]);++ const canExpandRow = useCallback(+ (row: ChangeOrderListItem) => (row.itemIds?.length ?? 0) > 0,+ []+ );++ const renderExpandedRow = useCallback(+ (row: ChangeOrderListItem) => {+ const affectedItems =+ (row.affectedItems as AffectedItemSummary[]) ?? [];+ if (affectedItems.length === 0) return null;+ return (+ <div className="pl-[52px] pr-4">+ {affectedItems.map((affected) => {+ // A New Part is net-new (newItemId === itemId) — show a single id,+ // not "X → X". Only Revision/Replacement Part mint a distinct+ // successor worth arrowing to.+ const hasDistinctSuccessor =+ !!affected.newItemId && affected.newItemId !== affected.itemId;+ const newReadableId = hasDistinctSuccessor+ ? resolveItemId(affected.newItemId)+ : null;+ return (+ <div key={affected.id} className="flex gap-3 py-3 text-sm">+ <div+ aria-hidden+ className="w-5 shrink-0 border-l border-border -my-3"+ />+ <div className="flex items-center gap-2">+ <span className="font-medium">+ {resolveItemId(affected.itemId)}+ </span>+ {newReadableId && (+ <span className="flex items-center gap-1 text-muted-foreground">+ <LuArrowRight className="size-3.5 shrink-0" />+ <span>{newReadableId}</span>+ </span>+ )}+ <ChangeTypeBadge changeType={affected.changeType} />+ </div>+ </div>+ );+ })}+ </div>+ );+ },+ [resolveItemId]+ );++ const renderContextMenu = useCallback(+ (row: ChangeOrderListItem) => {+ return (+ <>+ <MenuItem+ disabled={!permissions.can("update", "parts")}+ onClick={() => {+ navigate(path.to.changeOrder(row.id!));+ }}+ >+ <MenuIcon icon={<LuPencil />} />+ {t`Edit Change Order`}+ </MenuItem>+ <MenuItem+ destructive+ disabled={!permissions.can("delete", "parts")}+ onClick={() => {+ flushSync(() => {+ setSelectedChangeOrder(row);+ });+ deleteDisclosure.onOpen();+ }}+ >+ <MenuIcon icon={<LuTrash />} />+ {t`Delete Change Order`}+ </MenuItem>+ </>+ );+ },+ [navigate, permissions, deleteDisclosure, t]+ );++ return (+ <>+ <Table<ChangeOrderListItem>+ data={data}+ columns={columns}+ count={count}+ primaryAction={+ permissions.can("create", "parts") && (+ <New label={t`Change Order`} to={path.to.newChangeOrder} />+ )+ }+ renderContextMenu={renderContextMenu}+ renderExpandedRow={renderExpandedRow}+ canExpandRow={canExpandRow}+ defaultColumnVisibility={{ itemIds: false }}+ title={t`Change Orders`}+ table="changeOrder"+ withSavedView+ />+ {deleteDisclosure.isOpen && selectedChangeOrder && (+ <ConfirmDelete+ action={path.to.deleteChangeOrder(selectedChangeOrder.id!)}+ isOpen+ onCancel={() => {+ setSelectedChangeOrder(null);+ deleteDisclosure.onClose();+ }}+ onSubmit={() => {+ setSelectedChangeOrder(null);+ deleteDisclosure.onClose();+ }}+ name={selectedChangeOrder.name ?? "change order"}+ text={t`Are you sure you want to delete this change order?`}+ />+ )}+ </>+ );+ }+);++ChangeOrdersTable.displayName = "ChangeOrdersTable";+export default ChangeOrdersTable;diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ChangeTypeBadge.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeTypeBadge.tsxnew file mode 100644index 0000000000..d557af95b2--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ChangeTypeBadge.tsx@@ -0,0 +1,48 @@+import type { BadgeProps } from "@carbon/react";+import { Badge } from "@carbon/react";+import type { ChangeOrderChangeType } from "../../items.models";++// A single badge summarizing an affected item's change type:+// Version → "Version 2" Revision → "New Revision"+// Replacement Part → "Replacement" New Part → "New"+// Shown on the line-detail card header and each explorer row so both read+// identically. Only a Version shows a number, and it's the meaningful new+// method version; a Revision/New Part mints a brand-new item whose method+// restarts at v1, so that number is noise — use the plain label instead.+export function changeTypeBadgeLabel(+ changeType: ChangeOrderChangeType,+ version?: number | null+): string {+ if (changeType === "New Part") return "New";+ if (changeType === "Replacement Part") return "Replacement";+ if (changeType === "Revision") return "New Revision";+ return version != null ? `${changeType} ${version}` : changeType;+}++// Color-coded by change type: New Part = green (net-new), Replacement = orange+// (supersedes), Revision = blue, Version = outline.+const changeTypeBadgeVariant: Record<+ ChangeOrderChangeType,+ BadgeProps["variant"]+> = {+ "New Part": "green",+ "Replacement Part": "orange",+ Revision: "blue",+ Version: "outline"+};++export default function ChangeTypeBadge({+ changeType,+ version,+ className+}: {+ changeType: ChangeOrderChangeType;+ version?: number | null;+ className?: string;+}) {+ return (+ <Badge variant={changeTypeBadgeVariant[changeType]} className={className}>+ {changeTypeBadgeLabel(changeType, version)}+ </Badge>+ );+}diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/CreateChangeOrderModal.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/CreateChangeOrderModal.tsxnew file mode 100644index 0000000000..8d9311f26e--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/CreateChangeOrderModal.tsx@@ -0,0 +1,61 @@+import { getLocalTimeZone, today } from "@internationalized/date";+import { useEffect, useRef } from "react";+import { useFetcher } from "react-router";+import { useUser } from "~/hooks";+import type { ListItem } from "~/types";+import { path } from "~/utils/path";+import ChangeOrderForm from "./ChangeOrderForm";++type CreateChangeOrderModalProps = {+ // The Part to pre-select as the first affected item.+ itemId: string;+ onClose: () => void;+};++// Launches the CO create form as a modal from an item detail page, with the+// current item pre-selected as an affected item. Change-order categories are+// loaded on open from the create route's own loader (no extra route or+// layout-loader query), and the form posts to that same route — its action+// creates the CO, attaches the item, then redirects to the CO detail.+const CreateChangeOrderModal = ({+ itemId,+ onClose+}: CreateChangeOrderModalProps) => {+ const typesFetcher = useFetcher<{ types: ListItem[] }>();+ const user = useUser();++ // Load categories once when the modal mounts (it mounts only while open).+ const loadedRef = useRef(false);+ useEffect(() => {+ if (loadedRef.current) return;+ loadedRef.current = true;+ typesFetcher.load(path.to.newChangeOrder);+ }, [typesFetcher]);++ const initialValues = {+ id: undefined,+ changeOrderId: undefined,+ name: "",+ reasonForChange: "",+ description: "",+ changeOrderTypeId: "",+ assignee: user.id,+ priority: "Medium" as const,+ openDate: today(getLocalTimeZone()).toString(),+ dueDate: "",+ nonConformanceId: "",+ affectedItemIds: [itemId]+ };++ return (+ <ChangeOrderForm+ type="modal"+ open+ onClose={onClose}+ initialValues={initialValues}+ types={typesFetcher.data?.types ?? []}+ />+ );+};++export default CreateChangeOrderModal;diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ImpactPanel.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ImpactPanel.tsxnew file mode 100644index 0000000000..874b8dc222--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ImpactPanel.tsx@@ -0,0 +1,211 @@+import {+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ HStack,+ VStack+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { LuCircleCheck } from "react-icons/lu";+import { UsedInItem, type UsedInNode } from "../Item/UsedIn";++type UsedInChild = UsedInNode["children"][number];++// Where an affected item is referenced across the system (jobs, POs, sales,+// receipts, methods, NCRs, …) — the same shape the part detail page's "Used In"+// tree consumes. One entry per affected item on the change order.+export type ChangeOrderImpactItem = {+ itemId: string;+ readableIdWithRevision: string;+ itemName: string | null;+ usedIn: {+ issues: UsedInChild[];+ jobs: UsedInChild[];+ jobMaterials: UsedInChild[];+ maintenanceDispatchItems: UsedInChild[];+ methodMaterials: UsedInChild[];+ purchaseOrderLines: UsedInChild[];+ receiptLines: UsedInChild[];+ quoteLines: UsedInChild[];+ quoteMaterials: UsedInChild[];+ salesOrderLines: UsedInChild[];+ shipmentLines: UsedInChild[];+ supplierQuotes: UsedInChild[];+ assemblyInstructions: UsedInChild[];+ };+};++// One affected item's where-used tree. Categories are built exactly like the+// part detail page's Used In panel (kept in parallel with x+/part+/$itemId), but+// empty categories are dropped — the impact only lists where the item actually+// appears.+function ImpactItem({ item }: { item: ChangeOrderImpactItem }) {+ const { t } = useLingui();+ const u = item.usedIn;++ const tree: UsedInNode[] = [+ { key: "issues", name: t`Issues`, module: "quality", children: u.issues },+ {+ key: "jobs",+ name: t`Jobs`,+ module: "production",+ children: u.jobs.map((job) => ({ ...job, methodType: "Make to Order" }))+ },+ {+ key: "jobMaterials",+ name: t`Job Materials`,+ module: "production",+ children: u.jobMaterials+ },+ {+ key: "maintenanceDispatchItems",+ name: t`Maintenance`,+ module: "resources",+ children: u.maintenanceDispatchItems+ },+ {+ key: "assemblyInstructions",+ name: t`Assembly Instructions`,+ module: "production",+ children: u.assemblyInstructions+ },+ {+ key: "methodMaterials",+ name: t`Method Materials`,+ module: "parts",+ children: u.methodMaterials+ },+ {+ key: "purchaseOrderLines",+ name: t`Purchase Orders`,+ module: "purchasing",+ children: u.purchaseOrderLines.map((po) => ({+ ...po,+ methodType: "Purchase to Order"+ }))+ },+ {+ key: "receiptLines",+ name: t`Receipts`,+ module: "inventory",+ children: u.receiptLines.map((receipt) => ({+ ...receipt,+ methodType: "Pull from Inventory"+ }))+ },+ {+ key: "quoteLines",+ name: t`Quotes`,+ module: "sales",+ children: u.quoteLines+ },+ {+ key: "quoteMaterials",+ name: t`Quote Materials`,+ module: "sales",+ children: u.quoteMaterials+ },+ {+ key: "salesOrderLines",+ name: t`Sales Orders`,+ module: "sales",+ children: u.salesOrderLines+ },+ {+ key: "shipmentLines",+ name: t`Shipments`,+ module: "inventory",+ children: u.shipmentLines.map((shipment) => ({+ ...shipment,+ methodType: "Shipment"+ }))+ },+ {+ key: "supplierQuotes",+ name: t`Supplier Quotes`,+ module: "purchasing",+ children: u.supplierQuotes+ }+ ];++ const referenced = tree.filter((node) => node.children.length > 0);++ return (+ <VStack spacing={1} className="w-full">+ <VStack spacing={0} className="min-w-0 px-1">+ <span className="truncate text-sm font-medium">+ {item.readableIdWithRevision}+ </span>+ {item.itemName && (+ <span className="truncate text-xs text-muted-foreground">+ {item.itemName}+ </span>+ )}+ </VStack>+ {referenced.length === 0 ? (+ <span className="px-1 text-xs text-muted-foreground italic">+ <Trans>Not referenced anywhere yet.</Trans>+ </span>+ ) : (+ <VStack spacing={0}>+ {referenced.map((node) => (+ <UsedInItem+ key={node.key}+ node={node}+ itemReadableIdWithRevision={item.readableIdWithRevision}+ filterText=""+ />+ ))}+ </VStack>+ )}+ </VStack>+ );+}++// Change-order impact = where every affected item is used across the system.+// Read-only, informational — nothing here gates the release. Replaces the old+// jobs/sales/purchasing table with the richer part-page "Used In" tree so a+// single view answers "what does releasing this touch?".+export default function ImpactPanel({+ items,+ embedded = false+}: {+ items: ChangeOrderImpactItem[];+ // When true, render without the Card chrome — the rail supplies the section+ // frame + title.+ embedded?: boolean;+}) {+ const body =+ items.length === 0 ? (+ <HStack spacing={2} className="text-sm text-muted-foreground">+ <LuCircleCheck className="size-4 shrink-0 text-emerald-500" />+ <Trans>No affected items to assess.</Trans>+ </HStack>+ ) : (+ <VStack spacing={4}>+ {items.map((item) => (+ <ImpactItem key={item.itemId} item={item} />+ ))}+ </VStack>+ );++ if (embedded) return body;++ return (+ <Card className="w-full">+ <CardHeader>+ <CardTitle>+ <Trans>Impact</Trans>+ </CardTitle>+ <span className="text-xs text-muted-foreground">+ <Trans>+ Where the affected items are used across the system. Informational —+ nothing here blocks releasing.+ </Trans>+ </span>+ </CardHeader>+ <CardContent>{body}</CardContent>+ </Card>+ );+}diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ItemChangeOrders.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ItemChangeOrders.tsxnew file mode 100644index 0000000000..db77dca92f--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ItemChangeOrders.tsx@@ -0,0 +1,65 @@+import { Card, CardContent, CardHeader, CardTitle, cn } from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import { Link } from "react-router";+import { Enumerable } from "~/components/Enumerable";+import type { ListItem } from "~/types";+import { path } from "~/utils/path";+import { isChangeOrderLocked } from "../../items.models";+import type { ChangeOrderForItem } from "../../items.service";+import ChangeOrderStatus from "./ChangeOrderStatus";++type ItemChangeOrdersProps = {+ changeOrders: ChangeOrderForItem[];+ types: ListItem[];+};++// Part → CO traceability (4b): a history card of every change order that+// references this part (across all its revisions). Newest first (the G6 query+// orders it). Done rows are de-emphasized. Renders nothing when empty.+const ItemChangeOrders = ({ changeOrders, types }: ItemChangeOrdersProps) => {+ if (changeOrders.length === 0) return null;++ return (+ <Card>+ <CardHeader>+ <CardTitle>+ <Trans>Change Orders</Trans>+ </CardTitle>+ </CardHeader>+ <CardContent>+ <div className="flex flex-col divide-y divide-border">+ {changeOrders.map((co) => {+ const isDone = isChangeOrderLocked(co.status);+ const categoryName =+ types.find((ty) => ty.id === co.changeOrderTypeId)?.name ?? null;+ return (+ <Link+ key={co.id}+ to={path.to.changeOrder(co.id)}+ className={cn(+ "flex items-center justify-between gap-4 py-2 hover:bg-accent/50 rounded-md px-2 -mx-2 transition-colors",+ isDone && "opacity-60"+ )}+ >+ <div className="flex flex-col min-w-0">+ <span className="text-sm font-medium tracking-tight truncate">+ {co.changeOrderId}+ </span>+ <span className="text-xs text-muted-foreground truncate">+ {co.name}+ </span>+ </div>+ <div className="flex items-center gap-2 flex-shrink-0">+ {categoryName && <Enumerable value={categoryName} />}+ <ChangeOrderStatus status={co.status} />+ </div>+ </Link>+ );+ })}+ </div>+ </CardContent>+ </Card>+ );+};++export default ItemChangeOrders;diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ItemLink.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ItemLink.tsxnew file mode 100644index 0000000000..d580404fc4--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ItemLink.tsx@@ -0,0 +1,31 @@+import { cn } from "@carbon/react";+import type { ReactNode } from "react";+import { Link } from "react-router";+import { getItemDetailPath } from "~/utils/path";++// Renders an item reference (id/name) as a link to the item's detail page.+// Classic link behavior: a plain click navigates in the same tab; a Cmd/Ctrl+// (or middle) click opens a new tab — React Router's Link handles the modifier+// keys natively. `type` picks the right detail route (defaults to Part for+// assemblies/unknown types).+export default function ItemLink({+ itemId,+ type,+ children,+ className+}: {+ itemId: string;+ type: string | null | undefined;+ children: ReactNode;+ className?: string;+}) {+ return (+ <Link+ to={getItemDetailPath(type, itemId)}+ prefetch="intent"+ className={cn("hover:underline", className)}+ >+ {children}+ </Link>+ );+}diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/ItemOpenChangeOrderAlert.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/ItemOpenChangeOrderAlert.tsxnew file mode 100644index 0000000000..cb6fa240d3--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/ItemOpenChangeOrderAlert.tsx@@ -0,0 +1,54 @@+import { Alert, AlertDescription, AlertTitle } from "@carbon/react";+import { Plural, Trans } from "@lingui/react/macro";+import { LuGitPullRequestArrow } from "react-icons/lu";+import { Link } from "react-router";+import { path } from "~/utils/path";+import { changeOrderOpenStatuses } from "../../items.models";+import type { ChangeOrderForItem } from "../../items.service";++type ItemOpenChangeOrderAlertProps = {+ changeOrders: ChangeOrderForItem[];+};++const openStatusSet = new Set<string>(changeOrderOpenStatuses);++// Part → CO traceability (4b): a subtle heads-up when this part is on one or+// more not-yet-Done change orders. Derived from the same history list. Renders+// nothing when there are no open COs.+const ItemOpenChangeOrderAlert = ({+ changeOrders+}: ItemOpenChangeOrderAlertProps) => {+ const open = changeOrders.filter((co) => openStatusSet.has(co.status));+ if (open.length === 0) return null;++ return (+ <Alert variant="warning">+ <LuGitPullRequestArrow className="h-4 w-4" />+ <AlertTitle>+ <Plural+ value={open.length}+ one="This part is on 1 open change order"+ other="This part is on # open change orders"+ />+ </AlertTitle>+ <AlertDescription>+ <div className="flex flex-wrap gap-x-3 gap-y-1 pt-1">+ {open.map((co) => (+ <Link+ key={co.id}+ to={path.to.changeOrder(co.id)}+ className="text-sm font-medium hover:underline"+ >+ {co.changeOrderId}+ </Link>+ ))}+ <span className="sr-only">+ <Trans>Open change orders affecting this part</Trans>+ </span>+ </div>+ </AlertDescription>+ </Alert>+ );+};++export default ItemOpenChangeOrderAlert;diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/affectedItem.types.ts b/apps/erp/app/modules/items/ui/ChangeOrder/affectedItem.types.tsnew file mode 100644index 0000000000..f5e3be84a1--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/affectedItem.types.ts@@ -0,0 +1,89 @@+import type { JSONContent } from "@carbon/react";+import type { MethodItemType, MethodType } from "../../../shared";+import type { ChangeOrderItemDiff } from "../../items.models";+import type { getRevisionLock } from "../../items.server";+import type {+ ChangeOrderAffectedItemWithLabel,+ getConfigurationParameters,+ getConfigurationRules,+ getMethodMaterialsByMakeMethod,+ getMethodOperationsByMakeMethodId+} from "../../items.service";+import type { MakeMethod } from "../../types";+import type { PartPropertiesData } from "../Parts/PartProperties";++// Shared type for a change-order affected item + its CO-owned Draft make method.+// Lives in this dedicated file (not in a component) so the sidebar, the detail+// pane, the workspace, and the $id route/loader can all import it without a+// component-to-component dependency.++type RevisionLock = Awaited<ReturnType<typeof getRevisionLock>>;++type DraftMaterial = NonNullable<+ Awaited<ReturnType<typeof getMethodMaterialsByMakeMethod>>["data"]+>[number];+type DraftOperation = NonNullable<+ Awaited<ReturnType<typeof getMethodOperationsByMakeMethodId>>["data"]+>[number];+type DraftConfigParameters = Awaited<+ ReturnType<typeof getConfigurationParameters>+>["parameters"];+type DraftConfigRules = Awaited<ReturnType<typeof getConfigurationRules>>;++// The $id loader normalizes the raw rows (adds description, coerces nullable+// ids to undefined) exactly as the part make-method route does — these mapped+// shapes are what the embedded editors consume.+export type DraftMaterialMapped = Omit<+ DraftMaterial,+ "description" | "methodOperationId" | "methodType" | "itemType"+> & {+ description: string;+ methodOperationId: string | undefined;+ methodType: MethodType;+ itemType: MethodItemType;+};+export type DraftOperationMapped = Omit<+ DraftOperation,+ | "description"+ | "procedureId"+ | "operationSupplierProcessId"+ | "operationMinimumCost"+ | "operationLeadTime"+ | "operationUnitCost"+ | "tags"+ | "workCenterId"+ | "workInstruction"+> & {+ description: string;+ procedureId: string | undefined;+ operationSupplierProcessId: string | undefined;+ operationMinimumCost: number;+ operationLeadTime: number;+ operationUnitCost: number;+ tags: string[];+ workCenterId: string | undefined;+ workInstruction: JSONContent | null;+};++// v2: one affected item plus its CO-owned Draft make method (real rows shaped+// for the embedded BillOfMaterial / BillOfProcess editors), the change type, and+// the read-only authoring diff. The $id loader assembles this per affected item.+export type AffectedItemDraft = {+ affectedItem: ChangeOrderAffectedItemWithLabel;+ // The item the draft edits — the same item for a Version, the new item for+ // Revision / New Part.+ draftItemId: string;+ makeMethod: MakeMethod | null;+ methodMaterials: DraftMaterialMapped[];+ methodOperations: DraftOperationMapped[];+ tags: { name: string }[];+ configurable: boolean;+ configurationRules: DraftConfigRules;+ parameters: DraftConfigParameters;+ revisionStatus: RevisionLock["revisionStatus"];+ releaseControl: RevisionLock["releaseControl"] | null;+ // Attribute/file bundle for the embedded PartProperties editor — set for+ // Part-type Revision / New Part affected items, null otherwise.+ partData: PartPropertiesData | null;+ diff?: ChangeOrderItemDiff;+};diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/diff-ui.tsx b/apps/erp/app/modules/items/ui/ChangeOrder/diff-ui.tsxnew file mode 100644index 0000000000..1e25c5b2ee--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/diff-ui.tsx@@ -0,0 +1,97 @@+import { Badge, HStack } from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import type { ReactNode } from "react";+import type { MethodDiffEntry } from "../../items.models";++// -----------------------------------------------------------------------------+// Shared Change Order diff-UI helpers.+//+// The BOM / BOP / BOP-children editors all render staged rows keyed against a+// per-entry diff (added / modified / removed). These helpers centralize the+// three pieces that were previously copied into each editor: building the+// id → diff-entry map, deriving removed-only entries, and the status badge.+// -----------------------------------------------------------------------------++// A diff entry whose before/after payloads may carry an `id`. The diff engine is+// generic over row shape (Record<string, unknown>); we only read `.id`.+type DiffEntry<Row> = MethodDiffEntry<Row>;++function idOf(payload: unknown): string | undefined {+ return (payload as { id?: string } | null)?.id;+}++// Map each staged row id → its diff entry, keyed by `after.id`. A staged row is+// the diff `after`; a removed line only exists as a `before` (no staged row) and+// is surfaced separately via `removedEntries`.+export function buildDiffMap<Row, T extends DiffEntry<Row>>(+ diff?: T[]+): Map<string, T> {+ const map = new Map<string, T>();+ if (!diff) return map;+ for (const entry of diff) {+ const afterId = idOf(entry.after);+ if (afterId) map.set(afterId, entry);+ }+ return map;+}++// Removed lines have a diff `before` but no matching staged (present) row.+export function removedEntries<Row, T extends DiffEntry<Row>>(+ diff: T[] | undefined,+ presentIds: Set<string>+): T[] {+ return (diff ?? []).filter((entry) => {+ if (entry.status !== "removed") return false;+ const beforeId = idOf(entry.before);+ return beforeId ? !presentIds.has(beforeId) : true;+ });+}++export function DiffBadge({+ status+}: {+ status: MethodDiffEntry<unknown>["status"];+}) {+ if (status === "added") {+ return (+ <Badge variant="green">+ <Trans>Added</Trans>+ </Badge>+ );+ }+ if (status === "modified") {+ return (+ <Badge variant="yellow">+ <Trans>Modified</Trans>+ </Badge>+ );+ }+ if (status === "removed") {+ return (+ <Badge variant="red">+ <Trans>Removed</Trans>+ </Badge>+ );+ }+ return null;+}++// The struck-through "removed" row shell used by the BOP operation editor and+// the BOP children (steps / parameters / tools). The BOM editor renders a+// richer removed row (item id + quantity badge) inline and does not use this.+export function RemovedEntryRow({+ label,+ className = "p-2"+}: {+ label: ReactNode;+ className?: string;+}) {+ return (+ <HStack+ className={`w-full justify-between border border-border rounded-lg opacity-60 ${className}`}+ >+ <span className="text-sm line-through">{label}</span>+ <DiffBadge status="removed" />+ </HStack>+ );+}diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/index.ts b/apps/erp/app/modules/items/ui/ChangeOrder/index.tsnew file mode 100644index 0000000000..d081cd72f0--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/index.ts@@ -0,0 +1,18 @@+export { default as AffectedItemDetail } from "./AffectedItemDetail";+export type * from "./affectedItem.types";+export { default as ChangeOrderActions } from "./ChangeOrderActions";+export { default as ChangeOrderChanges } from "./ChangeOrderChanges";+export * from "./ChangeOrderContent";+export { default as ChangeOrderDiffViewer } from "./ChangeOrderDiffViewer";+export { default as ChangeOrderExplorer } from "./ChangeOrderExplorer";+export { default as ChangeOrderForm } from "./ChangeOrderForm";+export { default as ChangeOrderHeader } from "./ChangeOrderHeader";+export { default as ChangeOrderProperties } from "./ChangeOrderProperties";+export { default as ChangeOrderReleaseMerge } from "./ChangeOrderReleaseMerge";+export { default as ChangeOrderStatus } from "./ChangeOrderStatus";+export { default as ChangeOrdersTable } from "./ChangeOrdersTable";+export { default as CreateChangeOrderModal } from "./CreateChangeOrderModal";+export type { ChangeOrderImpactItem } from "./ImpactPanel";+export { default as ImpactPanel } from "./ImpactPanel";+export { default as ItemChangeOrders } from "./ItemChangeOrders";+export { default as ItemOpenChangeOrderAlert } from "./ItemOpenChangeOrderAlert";diff --git a/apps/erp/app/modules/items/ui/ChangeOrder/releaseDialog.store.ts b/apps/erp/app/modules/items/ui/ChangeOrder/releaseDialog.store.tsnew file mode 100644index 0000000000..8e0f642749--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrder/releaseDialog.store.ts@@ -0,0 +1,7 @@+import { atom } from "nanostores";++// Cross-subtree open-state for the Change Order release dialog. The header+// "Release" button and the rail's Release section live in separate React+// subtrees under the $id route, so neither can pass the other a callback; both+// toggle this atom instead. The dialog itself is rendered once (in the rail).+export const releaseDialogOpenAtom = atom(false);diff --git a/apps/erp/app/modules/items/ui/ChangeOrderActions/ChangeOrderRequiredActionForm.tsx b/apps/erp/app/modules/items/ui/ChangeOrderActions/ChangeOrderRequiredActionForm.tsxnew file mode 100644index 0000000000..a59ea373de--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrderActions/ChangeOrderRequiredActionForm.tsx@@ -0,0 +1,113 @@+import { ValidatedForm } from "@carbon/form";+import {+ Button,+ HStack,+ ModalDrawer,+ ModalDrawerBody,+ ModalDrawerContent,+ ModalDrawerFooter,+ ModalDrawerHeader,+ ModalDrawerProvider,+ ModalDrawerTitle,+ toast,+ VStack+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import type { PostgrestResponse } from "@supabase/supabase-js";+import { useEffect } from "react";+import { useFetcher } from "react-router";+import type { z } from "zod";+import { Boolean, Hidden, Input, Submit } from "~/components/Form";+import { usePermissions } from "~/hooks";+import { path } from "~/utils/path";+import { changeOrderRequiredActionValidator } from "../../items.models";++type ChangeOrderRequiredActionFormProps = {+ initialValues: z.infer<typeof changeOrderRequiredActionValidator>;+ type?: "modal" | "drawer";+ open?: boolean;+ onClose: () => void;+};++const ChangeOrderRequiredActionForm = ({+ initialValues,+ open = true,+ type = "drawer",+ onClose+}: ChangeOrderRequiredActionFormProps) => {+ const { t } = useLingui();+ const permissions = usePermissions();+ const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();++ useEffect(() => {+ if (type !== "modal") return;++ if (fetcher.state === "loading" && fetcher.data?.data) {+ onClose?.();+ toast.success(t`Created change order action`);+ } else if (fetcher.state === "idle" && fetcher.data?.error) {+ toast.error(+ `Failed to create change order action: ${fetcher.data.error.message}`+ );+ }+ }, [fetcher.data, fetcher.state, onClose, type, t]);++ const isEditing = initialValues.id !== undefined;+ const isDisabled = isEditing+ ? !permissions.can("update", "parts")+ : !permissions.can("create", "parts");++ return (+ <ModalDrawerProvider type={type}>+ <ModalDrawer+ open={open}+ onOpenChange={(open) => {+ if (!open) onClose?.();+ }}+ >+ <ModalDrawerContent>+ <ValidatedForm+ validator={changeOrderRequiredActionValidator}+ method="post"+ action={+ isEditing+ ? path.to.changeOrderRequiredAction(initialValues.id!)+ : path.to.newChangeOrderRequiredAction+ }+ defaultValues={initialValues}+ fetcher={fetcher}+ className="flex flex-col h-full"+ >+ <ModalDrawerHeader>+ <ModalDrawerTitle>+ {isEditing+ ? t`Edit Change Order Action`+ : t`New Change Order Action`}+ </ModalDrawerTitle>+ </ModalDrawerHeader>+ <ModalDrawerBody>+ <Hidden name="id" />+ <Hidden name="type" value={type} />+ <VStack spacing={4}>+ <Input name="name" label={t`Action`} />+ <Boolean name="active" label={t`Active`} />+ </VStack>+ </ModalDrawerBody>+ <ModalDrawerFooter>+ <HStack>+ <Submit isDisabled={isDisabled}>+ <Trans>Save</Trans>+ </Submit>+ <Button size="md" variant="solid" onClick={() => onClose()}>+ <Trans>Cancel</Trans>+ </Button>+ </HStack>+ </ModalDrawerFooter>+ </ValidatedForm>+ </ModalDrawerContent>+ </ModalDrawer>+ </ModalDrawerProvider>+ );+};++export default ChangeOrderRequiredActionForm;diff --git a/apps/erp/app/modules/items/ui/ChangeOrderActions/ChangeOrderRequiredActionsTable.tsx b/apps/erp/app/modules/items/ui/ChangeOrderActions/ChangeOrderRequiredActionsTable.tsxnew file mode 100644index 0000000000..732e6dc179--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrderActions/ChangeOrderRequiredActionsTable.tsx@@ -0,0 +1,105 @@+import { Checkbox, MenuIcon, MenuItem } from "@carbon/react";+import { useLingui } from "@lingui/react/macro";+import type { ColumnDef } from "@tanstack/react-table";+import { memo, useCallback, useMemo } from "react";+import { LuListChecks, LuPencil, LuTrash } from "react-icons/lu";+import { useNavigate } from "react-router";+import { Hyperlink, New, Table } from "~/components";+import { Enumerable } from "~/components/Enumerable";+import { usePermissions, useUrlParams } from "~/hooks";+import { path } from "~/utils/path";+import type { ChangeOrderRequiredAction } from "../../types";++type ChangeOrderRequiredActionsTableProps = {+ data: ChangeOrderRequiredAction[];+ count: number;+};++const ChangeOrderRequiredActionsTable = memo(+ ({ data, count }: ChangeOrderRequiredActionsTableProps) => {+ const [params] = useUrlParams();+ const navigate = useNavigate();+ const { t } = useLingui();+ const permissions = usePermissions();++ const columns = useMemo<ColumnDef<ChangeOrderRequiredAction>[]>(() => {+ return [+ {+ accessorKey: "name",+ header: t`Action`,+ cell: ({ row }) => (+ <Hyperlink to={row.original.id}>+ <Enumerable value={row.original.name} />+ </Hyperlink>+ ),+ meta: {+ icon: <LuListChecks />+ }+ },+ {+ accessorKey: "active",+ header: t`Active`,+ cell: ({ row }) => <Checkbox checked={row.original.active} />+ }+ ];+ }, [t]);++ const renderContextMenu = useCallback(+ (row: ChangeOrderRequiredAction) => {+ return (+ <>+ <MenuItem+ disabled={!permissions.can("update", "parts")}+ onClick={() => {+ navigate(+ `${path.to.changeOrderRequiredAction(+ row.id+ )}?${params.toString()}`+ );+ }}+ >+ <MenuIcon icon={<LuPencil />} />+ {t`Edit Action`}+ </MenuItem>+ <MenuItem+ destructive+ disabled={!permissions.can("delete", "parts")}+ onClick={() => {+ navigate(+ `${path.to.deleteChangeOrderRequiredAction(+ row.id+ )}?${params.toString()}`+ );+ }}+ >+ <MenuIcon icon={<LuTrash />} />+ {t`Delete Action`}+ </MenuItem>+ </>+ );+ },+ [navigate, params, permissions, t]+ );++ return (+ <Table<ChangeOrderRequiredAction>+ data={data}+ columns={columns}+ count={count}+ primaryAction={+ permissions.can("create", "parts") && (+ <New+ label={t`Action`}+ to={`${path.to.newChangeOrderRequiredAction}?${params.toString()}`}+ />+ )+ }+ renderContextMenu={renderContextMenu}+ title={t`Change Order Actions`}+ />+ );+ }+);++ChangeOrderRequiredActionsTable.displayName = "ChangeOrderRequiredActionsTable";+export default ChangeOrderRequiredActionsTable;diff --git a/apps/erp/app/modules/items/ui/ChangeOrderActions/index.ts b/apps/erp/app/modules/items/ui/ChangeOrderActions/index.tsnew file mode 100644index 0000000000..2ee21aeaf5--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrderActions/index.ts@@ -0,0 +1,2 @@+export { default as ChangeOrderRequiredActionForm } from "./ChangeOrderRequiredActionForm";+export { default as ChangeOrderRequiredActionsTable } from "./ChangeOrderRequiredActionsTable";diff --git a/apps/erp/app/modules/items/ui/ChangeOrderTypes/ChangeOrderTypeForm.tsx b/apps/erp/app/modules/items/ui/ChangeOrderTypes/ChangeOrderTypeForm.tsxnew file mode 100644index 0000000000..1ac99d5d45--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrderTypes/ChangeOrderTypeForm.tsx@@ -0,0 +1,112 @@+import { ValidatedForm } from "@carbon/form";+import {+ Button,+ HStack,+ ModalDrawer,+ ModalDrawerBody,+ ModalDrawerContent,+ ModalDrawerFooter,+ ModalDrawerHeader,+ ModalDrawerProvider,+ ModalDrawerTitle,+ toast,+ VStack+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import type { PostgrestResponse } from "@supabase/supabase-js";+import { useEffect } from "react";+import { useFetcher } from "react-router";+import type { z } from "zod";+import { Hidden, Input, Submit } from "~/components/Form";+import { usePermissions } from "~/hooks";+import { path } from "~/utils/path";+import { changeOrderTypeValidator } from "../../items.models";++type ChangeOrderTypeFormProps = {+ initialValues: z.infer<typeof changeOrderTypeValidator>;+ type?: "modal" | "drawer";+ open?: boolean;+ onClose: () => void;+};++const ChangeOrderTypeForm = ({+ initialValues,+ open = true,+ type = "drawer",+ onClose+}: ChangeOrderTypeFormProps) => {+ const { t } = useLingui();+ const permissions = usePermissions();+ const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();++ useEffect(() => {+ if (type !== "modal") return;++ if (fetcher.state === "loading" && fetcher.data?.data) {+ onClose?.();+ toast.success(t`Created change order type`);+ } else if (fetcher.state === "idle" && fetcher.data?.error) {+ toast.error(+ `Failed to create change order type: ${fetcher.data.error.message}`+ );+ }+ }, [fetcher.data, fetcher.state, onClose, type, t]);++ const isEditing = initialValues.id !== undefined;+ const isDisabled = isEditing+ ? !permissions.can("update", "parts")+ : !permissions.can("create", "parts");++ return (+ <ModalDrawerProvider type={type}>+ <ModalDrawer+ open={open}+ onOpenChange={(open) => {+ if (!open) onClose?.();+ }}+ >+ <ModalDrawerContent>+ <ValidatedForm+ validator={changeOrderTypeValidator}+ method="post"+ action={+ isEditing+ ? path.to.changeOrderType(initialValues.id!)+ : path.to.newChangeOrderType+ }+ defaultValues={initialValues}+ fetcher={fetcher}+ className="flex flex-col h-full"+ >+ <ModalDrawerHeader>+ <ModalDrawerTitle>+ {isEditing+ ? t`Edit Change Order Type`+ : t`New Change Order Type`}+ </ModalDrawerTitle>+ </ModalDrawerHeader>+ <ModalDrawerBody>+ <Hidden name="id" />+ <Hidden name="type" value={type} />+ <VStack spacing={4}>+ <Input name="name" label={t`Type`} />+ </VStack>+ </ModalDrawerBody>+ <ModalDrawerFooter>+ <HStack>+ <Submit isDisabled={isDisabled}>+ <Trans>Save</Trans>+ </Submit>+ <Button size="md" variant="solid" onClick={() => onClose()}>+ <Trans>Cancel</Trans>+ </Button>+ </HStack>+ </ModalDrawerFooter>+ </ValidatedForm>+ </ModalDrawerContent>+ </ModalDrawer>+ </ModalDrawerProvider>+ );+};++export default ChangeOrderTypeForm;diff --git a/apps/erp/app/modules/items/ui/ChangeOrderTypes/ChangeOrderTypesTable.tsx b/apps/erp/app/modules/items/ui/ChangeOrderTypes/ChangeOrderTypesTable.tsxnew file mode 100644index 0000000000..4074af988f--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrderTypes/ChangeOrderTypesTable.tsx@@ -0,0 +1,98 @@+import { MenuIcon, MenuItem } from "@carbon/react";+import { useLingui } from "@lingui/react/macro";+import type { ColumnDef } from "@tanstack/react-table";+import { memo, useCallback, useMemo } from "react";+import { LuGitPullRequestArrow, LuPencil, LuTrash } from "react-icons/lu";+import { useNavigate } from "react-router";+import { Hyperlink, New, Table } from "~/components";+import { Enumerable } from "~/components/Enumerable";+import { usePermissions, useUrlParams } from "~/hooks";+import { path } from "~/utils/path";+import type { ChangeOrderType } from "../../types";++type ChangeOrderTypesTableProps = {+ data: ChangeOrderType[];+ count: number;+};++const ChangeOrderTypesTable = memo(+ ({ data, count }: ChangeOrderTypesTableProps) => {+ const [params] = useUrlParams();+ const navigate = useNavigate();+ const { t } = useLingui();+ const permissions = usePermissions();++ const columns = useMemo<ColumnDef<ChangeOrderType>[]>(() => {+ return [+ {+ accessorKey: "name",+ header: t`Type`,+ cell: ({ row }) => (+ <Hyperlink to={row.original.id}>+ <Enumerable value={row.original.name} />+ </Hyperlink>+ ),+ meta: {+ icon: <LuGitPullRequestArrow />+ }+ }+ ];+ }, [t]);++ const renderContextMenu = useCallback(+ (row: ChangeOrderType) => {+ return (+ <>+ <MenuItem+ disabled={!permissions.can("update", "parts")}+ onClick={() => {+ navigate(+ `${path.to.changeOrderType(row.id)}?${params.toString()}`+ );+ }}+ >+ <MenuIcon icon={<LuPencil />} />+ {t`Edit Type`}+ </MenuItem>+ <MenuItem+ destructive+ disabled={!permissions.can("delete", "parts")}+ onClick={() => {+ navigate(+ `${path.to.deleteChangeOrderType(+ row.id+ )}?${params.toString()}`+ );+ }}+ >+ <MenuIcon icon={<LuTrash />} />+ {t`Delete Type`}+ </MenuItem>+ </>+ );+ },+ [navigate, params, permissions, t]+ );++ return (+ <Table<ChangeOrderType>+ data={data}+ columns={columns}+ count={count}+ primaryAction={+ permissions.can("create", "parts") && (+ <New+ label={t`Type`}+ to={`${path.to.newChangeOrderType}?${params.toString()}`}+ />+ )+ }+ renderContextMenu={renderContextMenu}+ title={t`Change Order Types`}+ />+ );+ }+);++ChangeOrderTypesTable.displayName = "ChangeOrderTypesTable";+export default ChangeOrderTypesTable;diff --git a/apps/erp/app/modules/items/ui/ChangeOrderTypes/index.ts b/apps/erp/app/modules/items/ui/ChangeOrderTypes/index.tsnew file mode 100644index 0000000000..95d1ab1b5d--- /dev/null+++ b/apps/erp/app/modules/items/ui/ChangeOrderTypes/index.ts@@ -0,0 +1,2 @@+export { default as ChangeOrderTypeForm } from "./ChangeOrderTypeForm";+export { default as ChangeOrderTypesTable } from "./ChangeOrderTypesTable";diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsxindex 301c1a787a..85f41945f3 100644--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx@@ -102,6 +102,8 @@ import type {MakeMethod} from "../../types";import { getLinkToItemDetails } from "./ItemForm";+import type { ReleaseLockProps } from "./ReleaseLockAlert";+import ReleaseLockAlert, { getReleaseLockFlags } from "./ReleaseLockAlert";type Material = z.infer<typeof methodMaterialValidator> & {description: string;@@ -128,7 +130,8 @@ type BillOfMaterialProps = {parameters?: ConfigurationParameter[];configurationRules?: ConfigurationRule[];replenishmentSystem?: string;-};+ parentItemId?: string;+} & ReleaseLockProps;type OrderState = {[key: string]: number;@@ -163,13 +166,21 @@ const BillOfMaterial = ({materials: initialMaterials,operations,parameters,- replenishmentSystem+ replenishmentSystem,+ parentItemId,+ revisionStatus,+ releaseControl}: BillOfMaterialProps) => {const permissions = usePermissions();const { t } = useLingui();+ const { isProductionRevision, isReleaseLocked } = getReleaseLockFlags({+ revisionStatus,+ releaseControl+ });const isReadOnly =permissions.can("update", "parts") === false ||- makeMethod.status !== "Draft";+ makeMethod.status !== "Draft" ||+ isReleaseLocked;const addItemButtonRef = useRef<HTMLButtonElement>(null);@@ -467,6 +478,7 @@ const BillOfMaterial = ({rulesByField={rulesByField}onConfigure={onConfigure}replenishmentSystem={replenishmentSystem}+ parentItemId={parentItemId}setOrderState={setOrderState}setSelectedItemId={setSelectedItemId}setTemporaryItems={setTemporaryItems}@@ -575,6 +587,9 @@ const BillOfMaterial = ({</CardAction></HStack><CardContent>+ {isProductionRevision && (+ <ReleaseLockAlert isLocked={isReleaseLocked} className="mb-4" />+ )}<SortableListisReadOnly={isReadOnly}items={materials}@@ -607,6 +622,7 @@ function MaterialForm({rulesByField,onConfigure,replenishmentSystem,+ parentItemId: propParentItemId,setOrderState,setSelectedItemId,setTemporaryItems,@@ -620,6 +636,7 @@ function MaterialForm({temporaryItems: TemporaryItems;rulesByField: Map<string, ConfigurationRule>;replenishmentSystem?: string;+ parentItemId?: string;setSelectedItemId: Dispatch<SetStateAction<string | null>>;setTemporaryItems: Dispatch<SetStateAction<TemporaryItems>>;setOrderState: Dispatch<SetStateAction<OrderState>>;@@ -634,6 +651,7 @@ function MaterialForm({message: string;}>();const params = useParams();+ const parentItemId = propParentItemId ?? params.itemId;const { company, defaults } = useUser();const [locationId, setLocationId] = useState<string | undefined>(defaults.locationId ?? undefined@@ -723,7 +741,7 @@ function MaterialForm({const onItemChange = async (itemId: string) => {if (!carbon) return;- if (itemId === params.itemId) {+ if (itemId === parentItemId) {toast.error(t`An item cannot be added to itself.`);return;}@@ -800,9 +818,9 @@ function MaterialForm({)}</div>- <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 items-start"><Item- blacklist={[params.itemId!]}+ blacklist={[parentItemId!]}name="itemId"label={itemType}includeInactivediff --git a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsxindex 4375465853..a65a8f7655 100644--- a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx+++ b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx@@ -132,6 +132,8 @@ import type {ConfigurationRule,MakeMethod} from "../../types";+import type { ReleaseLockProps } from "./ReleaseLockAlert";+import ReleaseLockAlert, { getReleaseLockFlags } from "./ReleaseLockAlert";type Operation = z.infer<typeof methodOperationValidator> & {workInstruction: JSONContent | null;@@ -158,7 +160,8 @@ type BillOfProcessProps = {})[];parameters?: ConfigurationParameter[];tags: { name: string }[];-};+ selectedMaterialId?: string;+} & ReleaseLockProps;type PendingWorkInstructions = {[key: string]: JSONContent;@@ -206,13 +209,21 @@ const BillOfProcess = ({materials,operations: initialOperations,parameters,- tags+ tags,+ selectedMaterialId,+ revisionStatus,+ releaseControl}: BillOfProcessProps) => {const permissions = usePermissions();const { t } = useLingui();+ const { isProductionRevision, isReleaseLocked } = getReleaseLockFlags({+ revisionStatus,+ releaseControl+ });const isReadOnly =permissions.can("update", "parts") === false ||- makeMethod.status !== "Draft";+ makeMethod.status !== "Draft" ||+ isReleaseLocked;const makeMethodId = makeMethod.id;@@ -808,7 +819,8 @@ const BillOfProcess = ({configuratorDisclosure.onOpen();};- const { materialId } = useParams();+ const { materialId: paramMaterialId } = useParams();+ const materialId = selectedMaterialId ?? paramMaterialId;const rulesByField = new Map(configurationRules?.map((rule) => [rule.field, rule]) ?? []@@ -862,6 +874,9 @@ const BillOfProcess = ({</CardAction></HStack><CardContent>+ {isProductionRevision && (+ <ReleaseLockAlert isLocked={isReleaseLocked} className="mb-4" />+ )}<SortableListisReadOnly={isReadOnly}items={items}diff --git a/apps/erp/app/modules/items/ui/Item/ItemDescription.tsx b/apps/erp/app/modules/items/ui/Item/ItemDescription.tsxindex 63c3103631..815ce0f7bf 100644--- a/apps/erp/app/modules/items/ui/Item/ItemDescription.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemDescription.tsx@@ -17,21 +17,30 @@ const descriptionValidator = z.object({type ItemDescriptionProps = {value: string;onChange: (value: string | null) => void;+ // Match the parent panel's field idiom: `true` (default) = click-to-edit+ // preview for the sidebar; `false` = an always-open textarea for the form.+ inline?: boolean;+ // Read-only: render the value as a static preview, no textarea / edit control.+ isReadOnly?: boolean;};/**- * Inline long description for item Properties panels. Textarea-based so the- * multi-line content reads naturally: while not editing it shows a clamped- * preview (line-clamp-3) that reveals the full text on hover via- * TruncatedTooltipText; clicking the edit button swaps in a textarea that- * persists onBlur through the same bulkUpdateItems path. Controlled `value`- * keeps the field in sync (no stale text).+ * Long description for item Properties panels; persists onBlur through the same+ * bulkUpdateItems path. Sidebar (`inline`) shows a clamped preview+ * (line-clamp-3, full text on hover) that swaps to a textarea on click; the form+ * (`inline={false}`) renders the textarea directly. Controlled `value` keeps the+ * field in sync (no stale text).*/-const ItemDescription = ({ value, onChange }: ItemDescriptionProps) => {+const ItemDescription = ({+ value,+ onChange,+ inline = true,+ isReadOnly = false+}: ItemDescriptionProps) => {const { t } = useLingui();const [isEditing, setIsEditing] = useState(false);- if (isEditing) {+ if (!isReadOnly && (!inline || isEditing)) {return (<ValidatedFormdefaultValues={{ description: value ?? undefined }}@@ -39,14 +48,14 @@ const ItemDescription = ({ value, onChange }: ItemDescriptionProps) => {className="w-full"><TextAreaControlled- autoFocus+ autoFocus={inline}label={t`Long Description`}name="description"rows={3}value={value ?? ""}onBlur={(e) => {onChange(e.target.value ?? null);- setIsEditing(false);+ if (inline) setIsEditing(false);}}className="text-muted-foreground"/>@@ -66,13 +75,15 @@ const ItemDescription = ({ value, onChange }: ItemDescriptionProps) => {{value}</TruncatedTooltipText>)}- <IconButton- icon={value ? <LuSettings2 /> : <LuPlus />}- aria-label={value ? "Edit" : "Add"}- size="sm"- variant="secondary"- onClick={() => setIsEditing(true)}- />+ {!isReadOnly && (+ <IconButton+ icon={value ? <LuSettings2 /> : <LuPlus />}+ aria-label={value ? "Edit" : "Add"}+ size="sm"+ variant="secondary"+ onClick={() => setIsEditing(true)}+ />+ )}</HStack></VStack>);diff --git a/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx b/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsxindex a6242df8b5..0ae125b7af 100644--- a/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx@@ -45,13 +45,18 @@ type ItemDocumentsProps = {itemId: string;modelUpload?: ModelUpload;type: ItemType;+ // Read-only: hide the upload affordances and disable delete. Used when the+ // owning record is closed (e.g. a completed/cancelled change order). Defaults+ // to editable so the part detail page is unchanged.+ isReadOnly?: boolean;};const ItemDocuments = ({files,itemId,modelUpload,- type+ type,+ isReadOnly = false}: ItemDocumentsProps) => {const { t } = useLingui();const { formatDate } = useDateFormatter();@@ -98,9 +103,13 @@ const ItemDocuments = ({<Trans>Files</Trans></CardTitle></CardHeader>- <CardAction>- <ItemDocumentForm type={type} itemId={itemId} />- </CardAction>+ {!isReadOnly && (+ <CardAction>+ <HStack>+ <ItemDocumentForm type={type} itemId={itemId} />+ </HStack>+ </CardAction>+ )}</HStack><CardContent><Table>@@ -160,7 +169,7 @@ const ItemDocuments = ({</DropdownMenuItem><DropdownMenuItemdestructive- disabled={!canDelete}+ disabled={isReadOnly || !canDelete}onClick={() => deleteModel()}>Delete@@ -232,7 +241,7 @@ const ItemDocuments = ({</DropdownMenuItem><DropdownMenuItemdestructive- disabled={!canDelete}+ disabled={isReadOnly || !canDelete}onClick={() => deleteFile(file)}>Delete@@ -256,7 +265,7 @@ const ItemDocuments = ({)}</Tbody></Table>- <FileDropzone onDrop={onDrop} />+ {!isReadOnly && <FileDropzone onDrop={onDrop} />}</CardContent></Card>);diff --git a/apps/erp/app/modules/items/ui/Item/ItemSupersessionForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemSupersessionForm.tsxindex 8d9d165644..7f6d32551a 100644--- a/apps/erp/app/modules/items/ui/Item/ItemSupersessionForm.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemSupersessionForm.tsx@@ -24,38 +24,13 @@ import {Submit} from "~/components/Form";import { usePermissions } from "~/hooks";+import type { SupersessionMode } from "../../items.models";import {itemSupersessionValidator,+ supersessionModeMeta,supersessionModes} from "../../items.models";-type SupersessionMode = (typeof supersessionModes)[number];--// Single source of truth for how each supersession mode is presented — the same-// color is used everywhere the mode shows up (the mode picker options and the-// item lifecycle badge), so the two never drift.-const supersessionModeMeta: Record<- SupersessionMode,- { color: "green" | "blue" | "orange" | "red"; description: string }-> = {- "Consume First": {- color: "green",- description: "Use remaining stock before switching to the successor"- },- "Prefer New": {- color: "blue",- description: "Default to the successor; old part as fallback only"- },- "Stock Only": {- color: "orange",- description: "Hold a minimum reserve for service; no production use"- },- "No Stock": {- color: "red",- description: "Fully obsolete — do not plan or stock"- }-};-// Derived lifecycle status shown on the item header (PRD: Active has no badge).// Labelled with the mode name so it matches the mode picker exactly.export function getItemLifecycleStatus(diff --git a/apps/erp/app/modules/items/ui/Item/MakeMethodTools.tsx b/apps/erp/app/modules/items/ui/Item/MakeMethodTools.tsxindex eebb160ca4..1d88c45f31 100644--- a/apps/erp/app/modules/items/ui/Item/MakeMethodTools.tsx+++ b/apps/erp/app/modules/items/ui/Item/MakeMethodTools.tsx@@ -46,6 +46,7 @@ import {LuGitBranch,LuGitFork,LuGitMerge,+ LuGitPullRequestArrow,LuStar,LuTriangleAlert} from "react-icons/lu";@@ -60,6 +61,7 @@ import {makeMethodVersionValidator} from "../../items.models";import type { MakeMethod } from "../../types";+import { CreateChangeOrderModal } from "../ChangeOrder";import { getPathToMakeMethod } from "../Methods/utils";import { getLinkToItemDetails } from "./ItemForm";import MakeMethodVersionStatus from "./MakeMethodVersionStatus";@@ -102,7 +104,10 @@ const MakeMethodTools = ({const saveMethodModal = useDisclosure();const [hasMethodParts, setHasMethodParts] = useState(true);const newVersionModal = useDisclosure();+ const changeOrderModal = useDisclosure();const activeMethodModal = useDisclosure();+ const canCreateChangeOrder =+ (type === "Part" || type === "Tool") && permissions.can("create", "parts");const itemLink = type && itemId ? getLinkToItemDetails(type, itemId) : null;const activeMethod =@@ -178,7 +183,7 @@ const MakeMethodTools = ({if (!carbon) return;const { data, error } = await carbon.from("makeMethod")- .select("id, version, status")+ .select("id, version, status, changeOrderId").eq("itemId", targetItemId).eq("companyId", companyId).order("version", { ascending: false });@@ -187,9 +192,11 @@ const MakeMethodTools = ({toast.error(error.message);}- // Only Draft versions can be overwritten - Active and Archived are read-only+ // Only Draft versions can be overwritten - Active and Archived are read-only.+ // Exclude CO-owned drafts (changeOrderId set) — a CO's draft is authored via+ // its own BOM/BOP surfaces, not clobbered wholesale by this copy-method tool.const availableVersions =- data?.filter(({ status }) => status === "Draft") ?? [];+ data?.filter((m) => m.status === "Draft" && !m.changeOrderId) ?? [];setTargetMakeMethods(availableVersions.map(({ id, version, status }) => ({@@ -336,6 +343,12 @@ const MakeMethodTools = ({New Version</DropdownMenuItem>)}+ {canCreateChangeOrder && (+ <DropdownMenuItem onClick={changeOrderModal.onOpen}>+ <DropdownMenuIcon icon={<LuGitPullRequestArrow />} />+ New Change Order+ </DropdownMenuItem>+ )}</>)}</DropdownMenuContent>@@ -622,6 +635,13 @@ const MakeMethodTools = ({onCancel={activeMethodModal.onClose}/>)}++ {changeOrderModal.isOpen && (+ <CreateChangeOrderModal+ itemId={itemId}+ onClose={changeOrderModal.onClose}+ />+ )}</Fragment>);};diff --git a/apps/erp/app/modules/items/ui/Item/ReleaseLockAlert.tsx b/apps/erp/app/modules/items/ui/Item/ReleaseLockAlert.tsxnew file mode 100644index 0000000000..789ed9b26d--- /dev/null+++ b/apps/erp/app/modules/items/ui/Item/ReleaseLockAlert.tsx@@ -0,0 +1,58 @@+import { Alert, AlertDescription, AlertTitle } from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import { LuTriangleAlert } from "react-icons/lu";+import type { itemRevisionStatus, plmReleaseControl } from "../../items.models";++// A released (Production) revision should flow changes through a change order.+// Only `enforce` hard-locks editing; `warn` keeps editing enabled and shows an+// advisory; `off` does nothing.+export type ReleaseLockProps = {+ revisionStatus?: (typeof itemRevisionStatus)[number] | null;+ releaseControl?: (typeof plmReleaseControl)[number];+};++export function getReleaseLockFlags({+ revisionStatus,+ releaseControl+}: ReleaseLockProps) {+ const isProduction = revisionStatus === "Production";+ return {+ isProductionRevision: isProduction && releaseControl !== "off",+ isReleaseLocked: isProduction && releaseControl === "enforce"+ };+}++type ReleaseLockAlertProps = {+ isLocked: boolean;+ className?: string;+};++// Banner for BOM/BOP editors on a released (Production) revision. `isLocked`+// (enforce) renders the hard-lock copy; otherwise (warn) a softer advisory.+const ReleaseLockAlert = ({ isLocked, className }: ReleaseLockAlertProps) => (+ <Alert variant="warning" className={className}>+ <LuTriangleAlert />+ <AlertTitle>+ {isLocked ? (+ <Trans>Released revision is locked</Trans>+ ) : (+ <Trans>Released revision</Trans>+ )}+ </AlertTitle>+ <AlertDescription>+ {isLocked ? (+ <Trans>+ This revision is released (Production). Open a change order to modify+ it.+ </Trans>+ ) : (+ <Trans>+ This revision is released (Production). Changes should normally flow+ through a change order.+ </Trans>+ )}+ </AlertDescription>+ </Alert>+);++export default ReleaseLockAlert;diff --git a/apps/erp/app/modules/items/ui/Item/RevisionForm.tsx b/apps/erp/app/modules/items/ui/Item/RevisionForm.tsxindex 559840838e..559564cc49 100644--- a/apps/erp/app/modules/items/ui/Item/RevisionForm.tsx+++ b/apps/erp/app/modules/items/ui/Item/RevisionForm.tsx@@ -13,10 +13,10 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useEffect } from "react";+import { useEffect, useState } from "react";import { useFetcher, useNavigate } from "react-router";import type { z } from "zod";-import { Hidden, Input, Submit } from "~/components/Form";+import { Boolean, Hidden, Input, Submit } from "~/components/Form";import { usePermissions } from "~/hooks";import { path } from "~/utils/path";import { revisionValidator } from "../../items.models";@@ -37,7 +37,8 @@ const RevisionForm = ({const { t } = useLingui();const permissions = usePermissions();const fetcher = useFetcher<- { success: false; message: string } | { success: true; link: string }+ | { success: false; message: string }+ | { success: true; link: string; newItemId?: string }>();const navigate = useNavigate();@@ -46,8 +47,20 @@ const RevisionForm = ({? !permissions.can("update", "parts"): !permissions.can("create", "parts");+ const [openChangeOrder, setOpenChangeOrder] = useState(false);+ // Offer the "open a change order" shortcut only when creating a new revision of+ // a make part/tool (CO affected items are Parts/Tools; the CO route coerces+ // Buy items to a Revision change type).+ const canOpenChangeOrder =+ !isEditing &&+ !hasSizesInsteadOfRevisions &&+ (initialValues.type === "Part" || initialValues.type === "Tool");+// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {+ // The "open a change order" path posts straight to the create+attach route+ // (see the form action below), which redirects to the new CO — so it never+ // returns here. This only handles the plain new-revision submit.if (fetcher.data?.success) {onClose();navigate(fetcher.data.link);@@ -72,7 +85,9 @@ const RevisionForm = ({action={isEditing? path.to.revision(initialValues.id!)- : path.to.newRevision+ : openChangeOrder && initialValues.copyFromId+ ? path.to.newChangeOrderFromItem(initialValues.copyFromId)+ : path.to.newRevision}defaultValues={initialValues}fetcher={fetcher}@@ -111,6 +126,18 @@ const RevisionForm = ({: t`The revision number of the part`}/>+ {canOpenChangeOrder && (+ <Boolean+ name="openChangeOrder"+ label={t`Open a change order`}+ description={t`Create a change order for the new revision and open it`}+ bordered+ onChange={setOpenChangeOrder}+ />+ )}+ {openChangeOrder && (+ <Hidden name="changeType" value="Revision" />+ )}</VStack></ModalDrawerBody><ModalDrawerFooter>diff --git a/apps/erp/app/modules/items/ui/Item/SourcingTypeProperty.tsx b/apps/erp/app/modules/items/ui/Item/SourcingTypeProperty.tsxindex 323209fa5a..1b12c800a1 100644--- a/apps/erp/app/modules/items/ui/Item/SourcingTypeProperty.tsx+++ b/apps/erp/app/modules/items/ui/Item/SourcingTypeProperty.tsx@@ -10,18 +10,24 @@ type SourcingTypePropertyProps = {replenishmentSystem?: string | null;value?: SourcingType | null;onChange: (value: SourcingType | null) => void;+ // Match the parent panel's field idiom: `true` (default) = click-to-edit+ // badge for the sidebar; `false` = a standard labeled control for the form.+ inline?: boolean;+ isReadOnly?: boolean;};/**- * Item-level sourcing selector shown in the Part/Tool Properties sidebar.- * Sourcing only applies to "Buy and Make" items, so it renders nothing- * otherwise. Shared between PartProperties and ToolProperties — keep it here- * rather than duplicating the form block in each.+ * Item-level sourcing selector for the Part/Tool Properties panel. Sourcing only+ * applies to "Buy and Make" items, so it renders nothing otherwise. Shared+ * between PartProperties and ToolProperties — keep it here rather than+ * duplicating the form block in each.*/export function SourcingTypeProperty({replenishmentSystem,value,- onChange+ onChange,+ inline = true,+ isReadOnly = false}: SourcingTypePropertyProps) {const { t } = useLingui();@@ -32,16 +38,21 @@ export function SourcingTypeProperty({defaultValues={{ sourcingType: value ?? undefined }}validator={z.object({ sourcingType: z.enum(sourcingType) })}className="w-full"+ isReadOnly={isReadOnly}><Selectname="sourcingType"label={t`Sourcing`}- inline={(value) => (- <Badge variant="secondary">- <SourcingTypeIcon type={value} className="mr-2" />- <span>{value}</span>- </Badge>- )}+ inline={+ inline+ ? (value) => (+ <Badge variant="secondary">+ <SourcingTypeIcon type={value} className="mr-2" />+ <span>{value}</span>+ </Badge>+ )+ : undefined+ }options={sourcingType.map((type) => ({value: type,label: (diff --git a/apps/erp/app/modules/items/ui/Item/SupplierParts/SupplierParts.tsx b/apps/erp/app/modules/items/ui/Item/SupplierParts/SupplierParts.tsxindex 6972c2a5ba..851fccd367 100644--- a/apps/erp/app/modules/items/ui/Item/SupplierParts/SupplierParts.tsx+++ b/apps/erp/app/modules/items/ui/Item/SupplierParts/SupplierParts.tsx@@ -29,18 +29,22 @@ type SupplierPartsProps = {supplierParts: Part[];compact?: boolean;deleteSupplierPath?: (id: string) => string;+ // Suppresses the add row + delete column regardless of permissions — for+ // read-only contexts like a locked (Done/Cancelled) change order.+ isReadOnly?: boolean;};const SupplierParts = ({supplierParts,compact = false,- deleteSupplierPath+ deleteSupplierPath,+ isReadOnly = false}: SupplierPartsProps) => {const navigate = useNavigate();const { t } = useLingui();const permissions = usePermissions();- const canEdit = permissions.can("update", "parts");- const canDelete = permissions.can("delete", "parts");+ const canEdit = permissions.can("update", "parts") && !isReadOnly;+ const canDelete = permissions.can("delete", "parts") && !isReadOnly;const formatter = useCurrencyFormatter();const customColumns = useCustomColumns<Part>("supplierPart");const [suppliers] = useSuppliers();diff --git a/apps/erp/app/modules/items/ui/Item/UsedIn.tsx b/apps/erp/app/modules/items/ui/Item/UsedIn.tsxindex 95de8026be..3fdacfd13a 100644--- a/apps/erp/app/modules/items/ui/Item/UsedIn.tsx+++ b/apps/erp/app/modules/items/ui/Item/UsedIn.tsx@@ -39,6 +39,7 @@ import { Hyperlink, MethodIcon } from "~/components";import { Confirm } from "~/components/Modals";import { LevelLine } from "~/components/TreeView";import { usePermissions } from "~/hooks";+import { getNextRevision } from "~/modules/items";import type { ItemType } from "~/modules/shared";import { path } from "~/utils/path";import { getReadableIdWithRevision } from "~/utils/string";@@ -371,27 +372,6 @@ export function RevisionsItem({);}-function getNextRevision(maxRevision: string) {- if (/^\d+$/.test(maxRevision)) {- return (parseInt(maxRevision) + 1).toString();- } else if (/^[A-Z]{1,2}$/.test(maxRevision)) {- // Handle single letter case- if (maxRevision.length === 1) {- return maxRevision === "Z"- ? "AA"- : String.fromCharCode(maxRevision.charCodeAt(0) + 1);- }- // Handle double letter case- const firstChar = maxRevision[0];- const secondChar = maxRevision[1];- if (secondChar === "Z") {- return String.fromCharCode(firstChar.charCodeAt(0) + 1) + "A";- }- return firstChar + String.fromCharCode(secondChar.charCodeAt(0) + 1);- }- return maxRevision;-}-export function UsedInItem({node,itemReadableIdWithRevision,diff --git a/apps/erp/app/modules/items/ui/Item/index.ts b/apps/erp/app/modules/items/ui/Item/index.tsindex fdd0cb3f9f..88fc1c6d3a 100644--- a/apps/erp/app/modules/items/ui/Item/index.ts+++ b/apps/erp/app/modules/items/ui/Item/index.ts@@ -16,6 +16,7 @@ import ItemSupersessionForm, {} from "./ItemSupersessionForm";import MakeMethodTools from "./MakeMethodTools";import PickMethodForm from "./PickMethodForm";+import ReleaseLockAlert from "./ReleaseLockAlert";import { SelectedItemProperties } from "./SelectedItemProperties";import { SourcingTypeProperty } from "./SourcingTypeProperty";import SupplierPartForm from "./SupplierPartForm";@@ -40,6 +41,7 @@ export {ItemSalePriceForm,MakeMethodTools,PickMethodForm,+ ReleaseLockAlert,SelectedItemProperties,SourcingTypeProperty,SupplierPartForm,diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsxindex 369803f9be..2ddade2a75 100644--- a/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx+++ b/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx@@ -645,7 +645,7 @@ const MaterialsTable = memo(({ data, tags, count }: MaterialsTableProps) => {<MenuSub><MenuSubTrigger><MenuIcon icon={<LuGitPullRequestArrow />} />- <Trans>Versions</Trans>+ <Trans>Revisions</Trans></MenuSubTrigger><MenuSubContent>{revisions.map((revision) => (diff --git a/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx b/apps/erp/app/modules/items/ui/Parts/PartHeader.tsxindex 5a3df53512..05424190b5 100644--- a/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx+++ b/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx@@ -14,7 +14,11 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { LuEllipsisVertical, LuTrash } from "react-icons/lu";+import {+ LuEllipsisVertical,+ LuGitPullRequestArrow,+ LuTrash+} from "react-icons/lu";import { Link, useParams } from "react-router";import { useAuditLog } from "~/components/AuditLog";import { DetailsTopbar } from "~/components/Layout";@@ -22,6 +26,7 @@ import ConfirmDelete from "~/components/Modals/ConfirmDelete";import { usePermissions, useRouteData, useUser } from "~/hooks";import { path } from "~/utils/path";import type { PartSummary } from "../../types";+import { CreateChangeOrderModal } from "../ChangeOrder";import { getItemLifecycleStatus } from "../Item/ItemSupersessionForm";import { usePartNavigation } from "./usePartNavigation";@@ -34,6 +39,7 @@ const PartHeader = () => {const { company } = useUser();const permissions = usePermissions();const deleteModal = useDisclosure();+ const changeOrderModal = useDisclosure();const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({entityType: "item",entityId: itemId,@@ -85,6 +91,14 @@ const PartHeader = () => {<DropdownMenuContent>{auditLogTrigger}<DropdownMenuSeparator />+ <DropdownMenuItem+ disabled={!permissions.can("create", "parts")}+ onClick={changeOrderModal.onOpen}+ >+ <DropdownMenuIcon icon={<LuGitPullRequestArrow />} />+ <Trans>Create Change Order</Trans>+ </DropdownMenuItem>+ <DropdownMenuSeparator /><DropdownMenuItemdisabled={!permissions.can("delete", "parts") ||@@ -118,6 +132,12 @@ const PartHeader = () => {/>)}</div>+ {changeOrderModal.isOpen && (+ <CreateChangeOrderModal+ itemId={itemId}+ onClose={changeOrderModal.onClose}+ />+ )}{auditLogDrawer}</>);diff --git a/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx b/apps/erp/app/modules/items/ui/Parts/PartProperties.tsxindex c6f7456ba5..208399903b 100644--- a/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx+++ b/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx@@ -3,6 +3,7 @@ import { InputControlled, Select, ValidatedForm } from "@carbon/form";import {Badge,Button,+ cn,HStack,Tooltip,TooltipContent,@@ -41,6 +42,7 @@ import type { ListItem } from "~/types";import { path } from "~/utils/path";import { copyToClipboard } from "~/utils/string";import {+ type ChangeOrderChangeType,itemReplenishmentSystems,itemTrackingTypes} from "../../items.models";@@ -53,20 +55,53 @@ import type {} from "../../types";import { FileBadge, ItemDescription, SourcingTypeProperty } from "../Item";+export type PartPropertiesData = {+ itemId: string;+ locations: ListItem[];+ partSummary: PartSummary;+ files: Promise<ItemFile[]>;+ supplierParts: SupplierPart[];+ pickMethods: PickMethod[];+ makeMethods: Promise<PostgrestResponse<MakeMethod>>;+ tags: { name: string }[];+};+type PartPropertiesProps = {- data?: {- itemId: string;- locations: ListItem[];- partSummary: PartSummary;- files: Promise<ItemFile[]>;- supplierParts: SupplierPart[];- pickMethods: PickMethod[];- makeMethods: Promise<PostgrestResponse<MakeMethod>>;- tags: { name: string }[];- };+ data?: PartPropertiesData;+ // When embedded (e.g. inside a change-order affected-item card) drop the+ // fixed-width sidebar chrome and flow with the parent container.+ embedded?: boolean;+ // Which slice to render. "all" (default, the part sidebar) shows everything;+ // "properties" omits the image + files. Lets a caller (the CO card) render+ // just the attribute fields and delegate files/CAD to ItemDocuments + CadModel.+ section?: "all" | "properties";+ // Field presentation. "sidebar" (default) = the compact inline click-to-edit+ // rows of the part detail sidebar. "form" = standard labeled form fields (used+ // by the CO card). Only affects presentation — persistence is unchanged.+ layout?: "sidebar" | "form";+ // Read-only: every field/control is non-editable (used when the change order+ // is released/locked). Defaults to editable.+ isReadOnly?: boolean;+ // The change-order change type this card is embedded for (a CO line). A+ // `Revision` keeps the source part number, so the Part Number field is locked+ // (Name + the other attributes stay editable); `New Part` gets a fresh number+ // and stays editable.+ changeType?: ChangeOrderChangeType;};-const PartProperties = ({ data }: PartPropertiesProps) => {+const PartProperties = ({+ data,+ embedded,+ section = "all",+ layout = "sidebar",+ isReadOnly = false,+ changeType+}: PartPropertiesProps) => {+ // Inline click-to-edit only in the sidebar layout; the form layout renders+ // each field as a standard labeled control.+ const inlineLayout = layout === "sidebar";+ // A revision keeps the source part number — lock that field (only) for it.+ const lockPartNumber = changeType === "Revision";const { t } = useLingui();const params = useParams();const itemId = data?.itemId ?? params.itemId;@@ -196,137 +231,215 @@ const PartProperties = ({ data }: PartPropertiesProps) => {const [suppliers] = useSuppliers();+ // Image + files, factored so they can render inline ("all") or as the sole+ // content of the "files" section without duplicating the markup.+ const thumbnail = (+ <ItemThumbnailUpload+ path={routeData?.partSummary?.thumbnailPath}+ itemId={itemId}+ modelId={routeData?.partSummary?.modelId}+ isReadOnly={isReadOnly}+ />+ );+ const filesBlock = (+ <VStack spacing={2}>+ <HStack className="w-full justify-between">+ <h3 className="text-xs text-muted-foreground">+ <Trans>Files</Trans>+ </h3>+ </HStack>+ {routeData?.partSummary?.modelId && (+ <Link+ className="group flex items-center gap-1"+ to={path.to.file.cadModel(routeData?.partSummary.modelId)}+ target="_blank"+ >+ <Badge variant="secondary">+ <LuMove3D className="w-3 h-3 mr-1 text-emerald-500" />+ <Trans>3D Model</Trans>+ </Badge>+ <span className="group-hover:opacity-100 opacity-0 transition-opacity duration-200 w-4 h-4 text-foreground">+ <LuExternalLink />+ </span>+ </Link>+ )}+ <Suspense fallback={null}>+ <Await resolve={routeData?.files}>+ {(files) =>+ files?.map((file) => (+ <FileBadge+ key={file.id}+ file={file}+ itemId={itemId}+ itemType="Part"+ />+ ))+ }+ </Await>+ </Suspense>+ </VStack>+ );++ const formLayout = layout === "form";+ // Blocks that hold a wide control (textarea / badge list / custom fields)+ // shouldn't be squeezed into a single grid column — span the full row.+ const spanFull = formLayout ? "sm:col-span-2" : undefined;++ // Part ID (readable id) + name — both editable inline, same as the part+ // detail page. On the CO card these edit the draft item. Extracted so the+ // form + sidebar layouts share the same fields.+ const partIdField = (+ <ValidatedForm+ defaultValues={{+ partId: routeData?.partSummary?.readableIdWithRevision ?? undefined+ }}+ validator={z.object({+ partId: z.string()+ })}+ className={cn("w-full", !formLayout && "-mt-2")}+ isReadOnly={isReadOnly || lockPartNumber}+ >+ <span className="text-sm">+ <InputControlled+ label={formLayout ? t`Part Number` : ""}+ name="partId"+ inline={inlineLayout}+ value={routeData?.partSummary?.readableId ?? ""}+ onBlur={(e) => {+ onUpdate("partId", e.target.value ?? null);+ }}+ className="text-muted-foreground"+ />+ </span>+ </ValidatedForm>+ );+ const nameField = (+ <ValidatedForm+ defaultValues={{+ name: routeData?.partSummary?.name ?? undefined+ }}+ validator={z.object({+ name: z.string()+ })}+ className={cn("w-full", !formLayout && "-mt-2")}+ isReadOnly={isReadOnly}+ >+ <span className="text-xs text-muted-foreground">+ <InputControlled+ label={formLayout ? t`Name` : ""}+ name="name"+ inline={inlineLayout}+ characterLimit={40}+ value={routeData?.partSummary?.name ?? ""}+ onBlur={(e) => {+ onUpdate("name", e.target.value ?? null);+ }}+ className="text-muted-foreground"+ />+ </span>+ </ValidatedForm>+ );+return (- <VStack- spacing={4}- className="w-96 bg-card h-full overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent border-l border-border px-4 py-2 text-sm"+ <div+ className={cn(+ "text-sm w-full",+ formLayout+ ? "grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4 items-start"+ : "flex flex-col items-start space-y-4",+ embedded+ ? "px-1 py-2"+ : "w-96 bg-card h-full overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent border-l border-border px-4 py-2"+ )}>- <VStack spacing={2}>- <HStack className="w-full justify-between">- <h3 className="text-xxs text-foreground/70 uppercase font-light tracking-wide">- <Trans>Properties</Trans>- </h3>- <HStack spacing={1}>- <Tooltip>- <TooltipTrigger asChild>- <Button- variant="ghost"- aria-label={t`Link`}- size="sm"- className="p-1"- onClick={() =>- copyToClipboard(- window.location.origin + path.to.part(itemId)- )- }- >- <LuLink className="w-3 h-3" />- </Button>- </TooltipTrigger>- <TooltipContent>- <span>- <Trans>Copy link to part</Trans>- </span>- </TooltipContent>- </Tooltip>- <Tooltip>- <TooltipTrigger asChild>- <Button- variant="ghost"- aria-label={t`Copy`}- size="sm"- className="p-1"- onClick={() => copyToClipboard(itemId)}- >- <LuKeySquare className="w-3 h-3" />- </Button>- </TooltipTrigger>- <TooltipContent>- <span>- <Trans>Copy part unique identifier</Trans>- </span>- </TooltipContent>- </Tooltip>- <Tooltip>- <TooltipTrigger asChild>- <Button- variant="ghost"- aria-label={t`Copy`}- size="sm"- className="p-1"- onClick={() =>- copyToClipboard(- routeData?.partSummary?.readableIdWithRevision ?? ""- )- }- >- <LuCopy className="w-3 h-3" />- </Button>- </TooltipTrigger>- <TooltipContent>- <span>- <Trans>Copy part number</Trans>- </span>- </TooltipContent>- </Tooltip>- </HStack>- </HStack>- <VStack spacing={1} className="pt-2">- <ValidatedForm- defaultValues={{- partId:- routeData?.partSummary?.readableIdWithRevision ?? undefined- }}- validator={z.object({- partId: z.string()- })}- className="w-full -mt-2"- >- <span className="text-sm">- <InputControlled- label=""- name="partId"- inline- size="sm"- value={routeData?.partSummary?.readableId ?? ""}- onBlur={(e) => {- onUpdate("partId", e.target.value ?? null);- }}- className="text-muted-foreground"- />- </span>- </ValidatedForm>- <ValidatedForm- defaultValues={{- name: routeData?.partSummary?.name ?? undefined- }}- validator={z.object({- name: z.string()- })}- className="w-full -mt-2"- >- <span className="text-xs text-muted-foreground">- <InputControlled- label=""- name="name"- inline- size="sm"- characterLimit={40}- value={routeData?.partSummary?.name ?? ""}- onBlur={(e) => {- onUpdate("name", e.target.value ?? null);- }}- className="text-muted-foreground"- />- </span>- </ValidatedForm>+ {formLayout ? (+ <>+ {partIdField}+ {nameField}+ </>+ ) : (+ <VStack spacing={2}>+ {/* On the CO affected-item card the tab already reads "Properties" and+ the card title carries the item id — so drop the redundant heading ++ copy affordances there. Part page (non-embedded) is unchanged. */}+ {!embedded && (+ <HStack className="w-full justify-between">+ <h3 className="text-xxs text-foreground/70 uppercase font-light tracking-wide">+ <Trans>Properties</Trans>+ </h3>+ <HStack spacing={1}>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ aria-label={t`Link`}+ size="sm"+ className="p-1"+ onClick={() =>+ copyToClipboard(+ window.location.origin + path.to.part(itemId)+ )+ }+ >+ <LuLink className="w-3 h-3" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <span>+ <Trans>Copy link to part</Trans>+ </span>+ </TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ aria-label={t`Copy`}+ size="sm"+ className="p-1"+ onClick={() => copyToClipboard(itemId)}+ >+ <LuKeySquare className="w-3 h-3" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <span>+ <Trans>Copy part unique identifier</Trans>+ </span>+ </TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ aria-label={t`Copy`}+ size="sm"+ className="p-1"+ onClick={() =>+ copyToClipboard(+ routeData?.partSummary?.readableIdWithRevision ?? ""+ )+ }+ >+ <LuCopy className="w-3 h-3" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <span>+ <Trans>Copy part number</Trans>+ </span>+ </TooltipContent>+ </Tooltip>+ </HStack>+ </HStack>+ )}+ <VStack spacing={1} className="pt-2">+ {partIdField}+ {nameField}+ </VStack>+ {section === "all" && thumbnail}</VStack>- <ItemThumbnailUpload- path={routeData?.partSummary?.thumbnailPath}- itemId={itemId}- modelId={routeData?.partSummary?.modelId}- />- </VStack>+ )}{/* <VStack spacing={2}><h3 className="text-xs text-muted-foreground">Assignee</h3>@@ -347,11 +460,12 @@ const PartProperties = ({ data }: PartPropertiesProps) => {itemPostingGroupId: z.string().nullable().optional()})}className="w-full"+ isReadOnly={isReadOnly}><ItemPostingGrouplabel={t`Item Group`}name="itemPostingGroupId"- inline+ inline={inlineLayout}isClearableonChange={(value) => {onUpdate("itemPostingGroupId", value?.value ?? null);@@ -368,23 +482,28 @@ const PartProperties = ({ data }: PartPropertiesProps) => {replenishmentSystem: z.string()})}className="w-full"+ isReadOnly={isReadOnly}><Selectname="replenishmentSystem"label={t`Replenishment`}termId="replenishment-system"- inline={(value) => (- <Badge variant="secondary">- <ReplenishmentSystemIcon type={value} className="mr-2" />- <span>- {value === "Buy"- ? t`Buy`- : value === "Make"- ? t`Make`- : t`Buy and Make`}- </span>- </Badge>- )}+ inline={+ inlineLayout+ ? (value) => (+ <Badge variant="secondary">+ <ReplenishmentSystemIcon type={value} className="mr-2" />+ <span>+ {value === "Buy"+ ? t`Buy`+ : value === "Make"+ ? t`Make`+ : t`Buy and Make`}+ </span>+ </Badge>+ )+ : undefined+ }options={itemReplenishmentSystems.map((system) => ({value: system,label: (@@ -413,25 +532,30 @@ const PartProperties = ({ data }: PartPropertiesProps) => {itemTrackingType: z.string()})}className="w-full"+ isReadOnly={isReadOnly}><Selectname="itemTrackingType"label={t`Tracking Type`}termId="item-tracking-type"- inline={(value) => (- <Badge variant="secondary">- <TrackingTypeIcon type={value} className="mr-2" />- <span>- {value === "Inventory"- ? t`Inventory`- : value === "Non-Inventory"- ? t`Non-Inventory`- : value === "Serial"- ? t`Serial`- : t`Batch`}- </span>- </Badge>- )}+ inline={+ inlineLayout+ ? (value) => (+ <Badge variant="secondary">+ <TrackingTypeIcon type={value} className="mr-2" />+ <span>+ {value === "Inventory"+ ? t`Inventory`+ : value === "Non-Inventory"+ ? t`Non-Inventory`+ : value === "Serial"+ ? t`Serial`+ : t`Batch`}+ </span>+ </Badge>+ )+ : undefined+ }options={itemTrackingTypes.map((type) => ({value: type,label: (@@ -462,23 +586,28 @@ const PartProperties = ({ data }: PartPropertiesProps) => {defaultMethodType: z.string()})}className="w-full"+ isReadOnly={isReadOnly}><Selectname="defaultMethodType"label={t`Default Method Type`}termId="item-default-method-type"- inline={(value) => (- <Badge variant="secondary">- <MethodIcon type={value} className="mr-2" />- <span>- {value === "Purchase to Order"- ? t`Purchase to Order`- : value === "Pull from Inventory"- ? t`Pull from Inventory`- : t`Make to Order`}- </span>- </Badge>- )}+ inline={+ inlineLayout+ ? (value) => (+ <Badge variant="secondary">+ <MethodIcon type={value} className="mr-2" />+ <span>+ {value === "Purchase to Order"+ ? t`Purchase to Order`+ : value === "Pull from Inventory"+ ? t`Pull from Inventory`+ : t`Make to Order`}+ </span>+ </Badge>+ )+ : undefined+ }options={methodType.filter((type) => {const replenishment = routeData?.partSummary?.replenishmentSystem;@@ -508,6 +637,8 @@ const PartProperties = ({ data }: PartPropertiesProps) => {<SourcingTypePropertyreplenishmentSystem={routeData?.partSummary?.replenishmentSystem}value={routeData?.partSummary?.sourcingType}+ inline={inlineLayout}+ isReadOnly={isReadOnly}onChange={(value) => onUpdate("sourcingType", value)}/>@@ -522,23 +653,28 @@ const PartProperties = ({ data }: PartPropertiesProps) => {.min(1, { message: "Unit of Measure is required" })})}className="w-full"+ isReadOnly={isReadOnly}><UnitOfMeasurelabel={t`Unit of Measure`}name="unitOfMeasureCode"- inline+ inline={inlineLayout}onChange={(value) => {onUpdate("unitOfMeasureCode", value?.value ?? null);}}/></ValidatedForm>- <ItemDescription- value={routeData?.partSummary?.description ?? ""}- onChange={(value) => onUpdate("description", value)}- />+ <div className={cn("w-full", spanFull)}>+ <ItemDescription+ value={routeData?.partSummary?.description ?? ""}+ inline={inlineLayout}+ isReadOnly={isReadOnly}+ onChange={(value) => onUpdate("description", value)}+ />+ </div>- <VStack spacing={2}>+ <VStack spacing={2} className={spanFull}><HStack className="w-full justify-between"><h3 className="text-xs text-muted-foreground"><Trans>Methods</Trans>@@ -588,67 +724,79 @@ const PartProperties = ({ data }: PartPropertiesProps) => {/>))}</VStack>- <ValidatedForm- defaultValues={{- active: routeData?.partSummary?.active ?? undefined- }}- validator={z.object({- active: zfd.checkbox()- })}- className="w-full"- >- <Boolean- label={t`Active`}- name="active"- variant="small"- onChange={(value) => {- onUpdate("active", value ? "on" : "off");- }}- />- </ValidatedForm>- {routeData?.partSummary?.replenishmentSystem?.includes("Buy") && (+ {/* Active is a lifecycle flag the change order controls at release — not a+ user-editable attribute in the CO card. Keep it on the part page only. */}+ {!embedded && (<ValidatedFormdefaultValues={{- requiresInspection:- routeData?.partSummary?.requiresInspection ?? false+ active: routeData?.partSummary?.active ?? undefined}}validator={z.object({- requiresInspection: zfd.checkbox()+ active: zfd.checkbox()})}className="w-full"+ isReadOnly={isReadOnly}><Boolean- label={t`Requires Inspection`}- name="requiresInspection"+ label={t`Active`}+ name="active"variant="small"onChange={(value) => {- onUpdate("requiresInspection", value ? "on" : "off");+ onUpdate("active", value ? "on" : "off");}}/></ValidatedForm>)}- {routeData?.partSummary?.replenishmentSystem?.includes("Buy") && (- <ValidatedForm- defaultValues={{- mpn: routeData?.partSummary?.mpn ?? undefined- }}- validator={z.object({- mpn: z.string().optional()- })}- className="w-full"- >- <InputControlled- label={t`Manufacturer Part Number`}- name="mpn"- inline- size="sm"- value={routeData?.partSummary?.mpn ?? ""}- onBlur={(e) => {- onUpdate("mpn", e.target.value ?? null);+ {/* Requires Inspection + Manufacturer Part Number are purchasing+ attributes — hidden on the CO affected-item card; they stay editable on+ the part page (non-embedded), same as Active/Tags above. */}+ {!embedded &&+ routeData?.partSummary?.replenishmentSystem?.includes("Buy") && (+ <ValidatedForm+ defaultValues={{+ requiresInspection:+ routeData?.partSummary?.requiresInspection ?? false}}- />- </ValidatedForm>- )}+ validator={z.object({+ requiresInspection: zfd.checkbox()+ })}+ className="w-full"+ isReadOnly={isReadOnly}+ >+ <Boolean+ label={t`Requires Inspection`}+ name="requiresInspection"+ variant="small"+ onChange={(value) => {+ onUpdate("requiresInspection", value ? "on" : "off");+ }}+ />+ </ValidatedForm>+ )}+ {!embedded &&+ routeData?.partSummary?.replenishmentSystem?.includes("Buy") && (+ <ValidatedForm+ defaultValues={{+ mpn: routeData?.partSummary?.mpn ?? undefined+ }}+ validator={z.object({+ mpn: z.string().optional()+ })}+ className="w-full"+ isReadOnly={isReadOnly}+ >+ <InputControlled+ label={t`Manufacturer Part Number`}+ name="mpn"+ inline={inlineLayout}+ size="sm"+ value={routeData?.partSummary?.mpn ?? ""}+ onBlur={(e) => {+ onUpdate("mpn", e.target.value ?? null);+ }}+ />+ </ValidatedForm>+ )}{routeDataFromRoute?.supersession?.successor && (<div className="w-full"><h3 className="text-xs text-muted-foreground mb-1">@@ -688,72 +836,46 @@ const PartProperties = ({ data }: PartPropertiesProps) => {)}</div>)}- <ValidatedForm- defaultValues={{- tags: routeData?.partSummary?.tags ?? []- }}- validator={z.object({- tags: z.array(z.string()).optional()- })}- className="w-full"- >- <Tags- availableTags={routeData?.tags ?? []}- label={t`Tags`}- name="tags"+ {/* Tags live on the part row, keyed by readableId — shared across all+ revisions. Editing them on a CO draft isn't isolated (it'd change the+ live part now) and can't be diffed per-revision, so hide them here.+ They remain editable on the part page. */}+ {!embedded && (+ <ValidatedForm+ defaultValues={{+ tags: routeData?.partSummary?.tags ?? []+ }}+ validator={z.object({+ tags: z.array(z.string()).optional()+ })}+ className="w-full"+ isReadOnly={isReadOnly}+ >+ <Tags+ availableTags={routeData?.tags ?? []}+ label={t`Tags`}+ name="tags"+ table="part"+ inline+ onChange={onUpdateTags}+ />+ </ValidatedForm>+ )}++ <div className={cn("w-full", spanFull)}>+ <CustomFormInlineFields+ customFields={+ (routeData?.partSummary?.customFields ?? {}) as Record<string, Json>+ }table="part"- inline- onChange={onUpdateTags}+ tags={routeData?.partSummary?.tags ?? []}+ isDisabled={isReadOnly}+ onUpdate={onUpdateCustomFields}/>- </ValidatedForm>+ </div>- <CustomFormInlineFields- customFields={- (routeData?.partSummary?.customFields ?? {}) as Record<string, Json>- }- table="part"- tags={routeData?.partSummary?.tags ?? []}- onUpdate={onUpdateCustomFields}- />-- <VStack spacing={2}>- <HStack className="w-full justify-between">- <h3 className="text-xs text-muted-foreground">- <Trans>Files</Trans>- </h3>- </HStack>- {routeData?.partSummary?.modelId && (- <Link- className="group flex items-center gap-1"- to={path.to.file.cadModel(routeData?.partSummary.modelId)}- target="_blank"- >- <Badge variant="secondary">- <LuMove3D className="w-3 h-3 mr-1 text-emerald-500" />- <Trans>3D Model</Trans>- </Badge>- <span className="group-hover:opacity-100 opacity-0 transition-opacity duration-200 w-4 h-4 text-foreground">- <LuExternalLink />- </span>- </Link>- )}-- <Suspense fallback={null}>- <Await resolve={routeData?.files}>- {(files) =>- files?.map((file) => (- <FileBadge- key={file.id}- file={file}- itemId={itemId}- itemType="Part"- />- ))- }- </Await>- </Suspense>- </VStack>- </VStack>+ {section === "all" && filesBlock}+ </div>);};diff --git a/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx b/apps/erp/app/modules/items/ui/Parts/PartsTable.tsxindex f7e60a2941..22828a9949 100644--- a/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx+++ b/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx@@ -574,7 +574,7 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {<MenuSub><MenuSubTrigger><MenuIcon icon={<LuGitPullRequestArrow />} />- <Trans>Versions</Trans>+ <Trans>Revisions</Trans></MenuSubTrigger><MenuSubContent>{revisions.map((revision) => (@@ -589,6 +589,18 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {</MenuSubContent></MenuSub>)}+ <MenuItem+ disabled={!permissions.can("create", "parts")}+ onClick={() =>+ fetcher.submit(null, {+ method: "post",+ action: path.to.newChangeOrderFromItem(row.id!)+ })+ }+ >+ <MenuIcon icon={<LuGitPullRequestArrow />} />+ <Trans>Create Change Order</Trans>+ </MenuItem><MenuItemdestructivedisabled={!permissions.can("delete", "parts")}@@ -603,7 +615,7 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {</>);};- }, [deleteItemModal, navigate, permissions, t]);+ }, [deleteItemModal, fetcher, navigate, permissions, t]);return (<>diff --git a/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx b/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsxindex 383c14a4c3..5586389a02 100644--- a/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx+++ b/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx@@ -14,7 +14,11 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { LuEllipsisVertical, LuTrash } from "react-icons/lu";+import {+ LuEllipsisVertical,+ LuGitPullRequestArrow,+ LuTrash+} from "react-icons/lu";import { Link, useParams } from "react-router";import { useAuditLog } from "~/components/AuditLog";import { DetailsTopbar } from "~/components/Layout";@@ -22,6 +26,7 @@ import ConfirmDelete from "~/components/Modals/ConfirmDelete";import { usePermissions, useRouteData, useUser } from "~/hooks";import { path } from "~/utils/path";import type { Tool } from "../../types";+import { CreateChangeOrderModal } from "../ChangeOrder";import { getItemLifecycleStatus } from "../Item/ItemSupersessionForm";import { useToolNavigation } from "./useToolNavigation";@@ -34,6 +39,7 @@ const ToolHeader = () => {const { company } = useUser();const permissions = usePermissions();const deleteModal = useDisclosure();+ const changeOrderModal = useDisclosure();const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({entityType: "item",entityId: itemId,@@ -85,6 +91,14 @@ const ToolHeader = () => {<DropdownMenuContent>{auditLogTrigger}<DropdownMenuSeparator />+ <DropdownMenuItem+ disabled={!permissions.can("create", "parts")}+ onClick={changeOrderModal.onOpen}+ >+ <DropdownMenuIcon icon={<LuGitPullRequestArrow />} />+ <Trans>Create Change Order</Trans>+ </DropdownMenuItem>+ <DropdownMenuSeparator /><DropdownMenuItemdisabled={!permissions.can("delete", "parts") ||@@ -118,6 +132,12 @@ const ToolHeader = () => {/>)}</div>+ {changeOrderModal.isOpen && (+ <CreateChangeOrderModal+ itemId={itemId}+ onClose={changeOrderModal.onClose}+ />+ )}{auditLogDrawer}</>);diff --git a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsxindex 11fa678370..5d6165305a 100644--- a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx+++ b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx@@ -562,7 +562,7 @@ const ToolsTable = memo(({ data, tags, count }: ToolsTableProps) => {<MenuSub><MenuSubTrigger><MenuIcon icon={<LuGitPullRequestArrow />} />- <Trans>Versions</Trans>+ <Trans>Revisions</Trans></MenuSubTrigger><MenuSubContent>{revisions.map((revision) => (diff --git a/apps/erp/app/modules/items/ui/useItemsSubmodules.tsx b/apps/erp/app/modules/items/ui/useItemsSubmodules.tsxindex 0ee673f335..fdf20e79f4 100644--- a/apps/erp/app/modules/items/ui/useItemsSubmodules.tsx+++ b/apps/erp/app/modules/items/ui/useItemsSubmodules.tsx@@ -5,14 +5,17 @@ import {LuAxis3D,LuBeef,LuDessert,+ LuGitPullRequestArrow,LuGlassWater,LuGroup,LuHammer,LuHeadphones,+ LuListChecks,LuPizza,LuPuzzle,LuRuler,- LuShapes+ LuShapes,+ LuTags} from "react-icons/lu";import { usePermissions } from "~/hooks";import { useSavedViews } from "~/hooks/useSavedViews";@@ -25,7 +28,7 @@ export default function useItemsSubmodules() {const { addSavedViewsToRoutes } = useSavedViews();const itemsRoutes: AuthenticatedRouteGroup[] = [{- name: t`Manage`,+ name: t`Items`,routes: [{name: t`Parts`,@@ -59,6 +62,29 @@ export default function useItemsSubmodules() {}]},+ {+ name: t`Change Orders`,+ routes: [+ {+ name: t`Change Orders`,+ to: path.to.changeOrders,+ icon: <LuGitPullRequestArrow />,+ table: "changeOrder"+ },+ {+ name: t`Change Order Types`,+ to: path.to.changeOrderTypes,+ icon: <LuTags />,+ role: "employee"+ },+ {+ name: t`Change Order Actions`,+ to: path.to.changeOrderRequiredActions,+ icon: <LuListChecks />,+ role: "employee"+ }+ ]+ },{name: t`Material Properties`,routes: [diff --git a/apps/erp/app/modules/quality/ui/Issue/ActionTasksList.tsx b/apps/erp/app/modules/quality/ui/Issue/ActionTasksList.tsxindex 38b63dd7cc..485c8b9299 100644--- a/apps/erp/app/modules/quality/ui/Issue/ActionTasksList.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/ActionTasksList.tsx@@ -1,64 +1,15 @@-import {- Button,- Card,- CardContent,- CardHeader,- CardTitle,- Checkbox,- HStack,- Modal,- ModalBody,- ModalContent,- ModalFooter,- ModalHeader,- ModalOverlay,- ModalTitle,- useDebounce,- VStack-} from "@carbon/react";-import { Trans } from "@lingui/react/macro";-import { Reorder, useDragControls } from "framer-motion";-import { useCallback, useEffect, useState } from "react";-import { LuCirclePlus } from "react-icons/lu";+import { useCallback } from "react";import { useFetcher, useParams } from "react-router";+import { ActionTaskList } from "~/components/ActionTasks/ActionTaskList";import { useRouteData } from "~/hooks";import type { IssueActionTask } from "~/modules/quality";import type { ListItem } from "~/types";import { path } from "~/utils/path";-import { TaskItem, TaskProgress } from "./IssueTask";--function ReorderableTaskItem({- taskId,- task,- suppliers,- isDisabled-}: {- taskId: string;- task: IssueActionTask;- suppliers: { supplierId: string; externalLinkId: string | null }[];- isDisabled: boolean;-}) {- const dragControls = useDragControls();-- return (- <Reorder.Item- key={taskId}- value={taskId}- dragListener={false}- dragControls={dragControls}- >- <TaskItem- task={task}- type="action"- suppliers={suppliers}- isDisabled={isDisabled}- showDragHandle={true}- dragControls={dragControls}- />- </Reorder.Item>- );-}+import { TaskItem } from "./IssueTask";+// Issue actions — a thin wrapper over the shared ActionTaskList. Each row is an+// issue TaskItem (Linear/Jira, processes, supplier, notes); adding picks from the+// issue's required actions and writes back via bulkUpdateIssue.export function ActionTasksList({tasks,suppliers,@@ -68,200 +19,46 @@ export function ActionTasksList({suppliers: { supplierId: string; externalLinkId: string | null }[];isDisabled: boolean;}) {- const sortOrderFetcher = useFetcher<{}>();+ const { id } = useParams();+ if (!id) throw new Error("id not found");- // Initialize sort order state based on existing tasks- const [sortOrder, setSortOrder] = useState<string[]>(() =>- [...tasks]- .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))- .map((task) => task.id)+ const routeData = useRouteData<{ requiredActions: ListItem[] }>(+ path.to.issue(id));-- // Update sort order when tasks change- useEffect(() => {- if (tasks && tasks.length > 0) {- const sorted = [...tasks]- .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))- .map((task) => task.id);- setSortOrder(sorted);- }- }, [tasks]);-- const onReorder = (newOrder: string[]) => {- if (isDisabled) return;-- const updates: Record<string, number> = {};- newOrder.forEach((id, index) => {- updates[id] = index + 1;- });- setSortOrder(newOrder);- updateSortOrder(updates);- };-- const updateSortOrder = useDebounce(- (updates: Record<string, number>) => {- let formData = new FormData();- formData.append("updates", JSON.stringify(updates));- sortOrderFetcher.submit(formData, {+ const addFetcher = useFetcher();++ const onAdd = useCallback(+ (selectedIds: string[]) => {+ const formData = new FormData();+ formData.append("ids", id);+ formData.append("field", "requiredActionIds");+ formData.append("value", selectedIds.join(","));+ addFetcher.submit(formData, {method: "post",- action: path.to.issueActionTasksOrder+ action: path.to.bulkUpdateIssue});},- 1000,- true+ [id, addFetcher]);- if (tasks.length === 0) return <NewAction isDisabled={isDisabled} />;-return (- <Card className="w-full" isCollapsible>- <HStack className="justify-between w-full">- <CardHeader>- <CardTitle className="flex items-center gap-2">- <Trans>Actions</Trans>- </CardTitle>- </CardHeader>- <TaskProgress tasks={tasks} />- </HStack>- <CardContent>- <Reorder.Group- axis="y"- values={sortOrder}- onReorder={onReorder}- className="w-full space-y-3"- >- {sortOrder.map((taskId) => {- const task = tasks.find((t) => t.id === taskId);- if (!task) return null;- return (- <ReorderableTaskItem- key={taskId}- taskId={taskId}- task={task}- suppliers={suppliers}- isDisabled={isDisabled}- />- );- })}- </Reorder.Group>- </CardContent>- </Card>- );-}--function NewAction({ isDisabled }: { isDisabled: boolean }) {- const { id } = useParams();- if (!id) throw new Error("id not found");-- const [isOpen, setIsOpen] = useState(false);- const [selectedActionIds, setSelectedActionIds] = useState<string[]>([]);-- const routeData = useRouteData<{- requiredActions: ListItem[];- }>(path.to.issue(id));-- const fetcher = useFetcher();-- useEffect(() => {- if (fetcher.state === "idle" && fetcher.data) {- setIsOpen(false);- setSelectedActionIds([]);- }- }, [fetcher.state, fetcher.data]);-- const handleSubmit = useCallback(() => {- const formData = new FormData();- formData.append("ids", id);- formData.append("field", "requiredActionIds");- formData.append("value", selectedActionIds.join(","));-- fetcher.submit(formData, {- method: "post",- action: path.to.bulkUpdateIssue- });- }, [id, selectedActionIds, fetcher]);-- const handleCheckboxChange = useCallback(- (actionId: string, checked: boolean) => {- setSelectedActionIds((prev) =>- checked ? [...prev, actionId] : prev.filter((id) => id !== actionId)- );- },- []- );-- return (- <>- <button- className="flex items-center justify-start bg-card border-2 border-dashed border-background w-full hover:bg-background/80 rounded-lg px-10 py-6 text-muted-foreground hover:text-foreground gap-2 transition-colors duration-200 text-sm cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"- onClick={() => setIsOpen(true)}- disabled={isDisabled}- >- <LuCirclePlus size={16} /> <span>Add Actions</span>- </button>-- <Modal- open={isOpen}- onOpenChange={(open) => {- if (!open) {- setIsOpen(false);- setSelectedActionIds([]);- }- }}- >- <ModalOverlay />- <ModalContent>- <ModalHeader>- <ModalTitle>- <Trans>Add Required Actions</Trans>- </ModalTitle>- </ModalHeader>- <ModalBody>- <VStack spacing={2}>- {routeData?.requiredActions.map((action) => (- <label- key={action.id}- htmlFor={action.id}- className="flex items-center gap-2 w-full px-4 py-3 rounded-lg hover:bg-accent hover:text-accent-foreground border border-border cursor-pointer"- >- <Checkbox- id={action.id}- isChecked={selectedActionIds.includes(action.id)}- onCheckedChange={(checked) =>- handleCheckboxChange(action.id, !!checked)- }- />- <span className="text-sm font-medium">{action.name}</span>- </label>- ))}- </VStack>- </ModalBody>- <ModalFooter>- <Button- variant="secondary"- onClick={() => {- setIsOpen(false);- setSelectedActionIds([]);- }}- >- <Trans>Cancel</Trans>- </Button>- <Button- onClick={handleSubmit}- disabled={- selectedActionIds.length === 0 || fetcher.state !== "idle"- }- isLoading={fetcher.state === "submitting"}- >- {fetcher.state !== "idle" ? (- <Trans>Adding...</Trans>- ) : (- <Trans>Add Actions</Trans>- )}- </Button>- </ModalFooter>- </ModalContent>- </Modal>- </>+ <ActionTaskList+ tasks={tasks}+ reorderAction={path.to.issueActionTasksOrder}+ templates={routeData?.requiredActions ?? []}+ onAdd={onAdd}+ isAddSubmitting={addFetcher.state !== "idle"}+ isDisabled={isDisabled}+ renderItem={(task, dragControls) => (+ <TaskItem+ task={task}+ type="action"+ suppliers={suppliers}+ isDisabled={isDisabled}+ showDragHandle+ dragControls={dragControls}+ />+ )}+ />);}diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueHeader.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueHeader.tsxindex adebffe12c..06f79ac37e 100644--- a/apps/erp/app/modules/quality/ui/Issue/IssueHeader.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/IssueHeader.tsx@@ -20,6 +20,7 @@ import {LuEllipsisVertical,LuExternalLink,LuFile,+ LuGitPullRequestArrow,LuLoaderCircle,LuTrash} from "react-icons/lu";@@ -71,6 +72,21 @@ const IssueHeader = () => {/></DropdownMenuTrigger><DropdownMenuContent>+ <DropdownMenuItem+ disabled={!permissions.can("create", "parts")}+ asChild+ >+ <Link+ to={`${+ path.to.newChangeOrder+ }?sourceType=nonConformance&sourceId=${id}&name=${encodeURIComponent(+ routeData?.nonConformance?.nonConformanceId ?? ""+ )}`}+ >+ <DropdownMenuIcon icon={<LuGitPullRequestArrow />} />+ <Trans>Create Change Order</Trans>+ </Link>+ </DropdownMenuItem><DropdownMenuItemdisabled={!["In Progress", "Closed"].includes(status ?? "") ||diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsxindex 1b805de8b0..9a7ddd0125 100644--- a/apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsx@@ -18,7 +18,7 @@ import {import { Trans, useLingui } from "@lingui/react/macro";import { useCallback, useEffect } from "react";import { LuCopy, LuKeySquare, LuLink } from "react-icons/lu";-import { useFetcher, useParams } from "react-router";+import { Link, useFetcher, useParams } from "react-router";import { z } from "zod";import {Assignee,@@ -29,6 +29,8 @@ import { Enumerable } from "~/components/Enumerable";import { Tags } from "~/components/Form";import CustomFormInlineFields from "~/components/Form/CustomFormInlineFields";import { usePermissions, useRouteData } from "~/hooks";+import type { ChangeOrderStatus as ChangeOrderStatusType } from "~/modules/items";+import { ChangeOrderStatus } from "~/modules/items/ui/ChangeOrder";import type { action } from "~/routes/x+/items+/update";import type { ListItem, StorageItem } from "~/types";import { path } from "~/utils/path";@@ -56,8 +58,16 @@ const IssueProperties = () => {requiredActions: ListItem[];files: Promise<StorageItem[]>;tags: { name: string }[];+ changeOrders: {+ id: string;+ changeOrderId: string;+ name: string;+ status: ChangeOrderStatusType;+ }[];}>(path.to.issue(id));+ const changeOrders = routeData?.changeOrders ?? [];+const optimisticAssignment = useOptimisticAssignment({id: id,table: "nonConformance"@@ -543,6 +553,28 @@ const IssueProperties = () => {tags={routeData?.nonConformance?.tags ?? []}onUpdate={onUpdateCustomFields}/>++ {changeOrders.length > 0 && (+ <VStack spacing={2}>+ <h3 className="text-xs text-muted-foreground">+ <Trans>Change Orders</Trans>+ </h3>+ <VStack spacing={1}>+ {changeOrders.map((co) => (+ <Link+ key={co.id}+ to={path.to.changeOrder(co.id)}+ className="flex items-center justify-between gap-2 w-full hover:bg-accent/50 rounded-md px-2 -mx-2 py-1 transition-colors"+ >+ <span className="text-sm text-primary hover:underline truncate">+ {co.changeOrderId}+ </span>+ <ChangeOrderStatus status={co.status} />+ </Link>+ ))}+ </VStack>+ </VStack>+ )}</VStack>);};diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsxindex fb444bdfba..0e6b48f0b9 100644--- a/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx@@ -11,43 +11,26 @@ import {CommandItem,cn,DatePicker,- DropdownMenu,- DropdownMenuContent,- DropdownMenuIcon,- DropdownMenuRadioGroup,- DropdownMenuRadioItem,- DropdownMenuTrigger,- generateHTML,- HStack,- IconButton,Popover,PopoverContent,PopoverTrigger,toast,- useDebounce,- useDisclosure+ useDebounce} from "@carbon/react";-import { Editor } from "@carbon/react/Editor";import { parseDate } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";import type { DragControls } from "framer-motion";import { nanoid } from "nanoid";import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import {- LuCalendar,- LuChevronRight,- LuCircleCheck,- LuCirclePlay,- LuCog,- LuContainer,- LuGripVertical,- LuLoaderCircle-} from "react-icons/lu";+import { LuCalendar, LuCog, LuContainer } from "react-icons/lu";import { RxCheck } from "react-icons/rx";import { useFetchers, useParams, useSubmit } from "react-router";-import { Assignee } from "~/components";+import {+ ActionTaskCard,+ type ActionTaskStatus+} from "~/components/ActionTasks/ActionTaskCard";+import { ActionTaskStatusButton } from "~/components/ActionTasks/ActionTaskStatusButton";import { useProcesses } from "~/components/Form/Process";-import { IssueTaskStatusIcon } from "~/components/Icons";import SupplierAvatar from "~/components/SupplierAvatar";import {useDateFormatter,@@ -63,7 +46,6 @@ import type {IssueItem,IssueReviewer} from "~/modules/quality";-import { nonConformanceTaskStatus } from "~/modules/quality";import { useSuppliers } from "~/stores";import { getPrivateUrl, path } from "~/utils/path";import { JiraIssueDialog } from "./Jira/IssueDialog";@@ -71,33 +53,9 @@ import { LinearIssueDialog } from "./Linear/IssueDialog";const logger = getLogger("erp", "issuetask");-export function TaskProgress({- tasks,- className-}: {- tasks: { status: IssueActionTask["status"] }[];- className?: string;-}) {- const completedOrSkippedTasks = tasks.filter(- (task) => task.status === "Completed" || task.status === "Skipped"- ).length;- const progressPercentage = (completedOrSkippedTasks / tasks.length) * 100;-- return (- <div- className={cn(- "flex flex-col items-end gap-2 py-3 pr-14 w-[120px]",- className- )}- >- <BarProgress- gradient- progress={progressPercentage}- value={`${completedOrSkippedTasks}/${tasks.length}`}- />- </div>- );-}+// TaskProgress moved to the shared ActionTasks folder (SSOT with Change Orders);+// re-exported here so existing `~/modules/quality/ui/Issue` importers keep working.+export { ActionTaskProgress as TaskProgress } from "~/components/ActionTasks/ActionTaskProgress";export function ItemProgress({ items }: { items: IssueItem[] }) {const completedOrSkippedItems = items.filter(@@ -116,29 +74,6 @@ export function ItemProgress({ items }: { items: IssueItem[] }) {);}-export const statusActions = {- Completed: {- action: "Reopen",- icon: <LuLoaderCircle />,- status: "Pending"- },- Pending: {- action: "Start",- icon: <LuCirclePlay />,- status: "In Progress"- },- Skipped: {- action: "Reopen",- icon: <LuLoaderCircle />,- status: "Pending"- },- "In Progress": {- action: "Complete",- icon: <LuCircleCheck />,- status: "Completed"- }-} as const;-function SupplierAssignment({task,type,@@ -283,20 +218,18 @@ export function TaskItem({}) {useRealtime("nonConformanceActionTask", `id=eq.${task.id}`);- const { t } = useLingui();const integrations = useIntegrations();const permissions = usePermissions();- const disclosure = useDisclosure({- defaultIsOpen: true- });- const { currentStatus, onOperationStatusChange } = useTaskStatus({+ const {+ currentStatus,+ onOperationStatusChange,+ isDisabled: statusDisabled+ } = useTaskStatus({task,type,disabled: isDisabled});- const statusAction =- statusActions[currentStatus as keyof typeof statusActions];// Check if this action task has a linked Linear or Jira issueconst hasLinearLink =@@ -327,92 +260,57 @@ export function TaskItem({}return (- <div className="rounded-lg border w-full flex flex-col bg-card">- <div className="flex w-full justify-between px-4 py-2 items-center">- <div className="flex flex-col flex-1">- <span className="text-base font-semibold tracking-tight">- {taskTitle}- </span>- </div>- <div className="flex items-center gap-1">- {showDragHandle && !isDisabled && dragControls && (- <button- className="cursor-grab active:cursor-grabbing text-muted-foreground hover:text-foreground transition-colors p-1"- onPointerDown={(e) => dragControls.start(e)}- >- <LuGripVertical size={16} />- </button>- )}-+ <ActionTaskCard+ title={taskTitle ?? ""}+ status={currentStatus as ActionTaskStatus}+ notes={content as JSONContent}+ canEditNotes={permissions.can("update", "quality") && !isDisabled}+ onNotesChange={(value) => {+ setContent(value);+ onUpdateContent(value);++ // Auto-start issue when typing in task if issue status is "Registered"+ if (+ routeData?.nonConformance?.status === "Registered" &&+ !hasStartedRef.current &&+ value?.content?.some((node: any) => node.content?.length > 0)+ ) {+ hasStartedRef.current = true;+ submit(+ { status: "In Progress" },+ {+ method: "post",+ action: path.to.issueStatus(id!),+ navigate: false+ }+ );+ }+ }}+ onUploadImage={onUploadImage}+ onStatusChange={(next) => onOperationStatusChange(task.id!, next)}+ assigneeTable={getTable(type)}+ assigneeId={task.id!}+ assignee={task.assignee ?? undefined}+ isDisabled={statusDisabled}+ showDragHandle={showDragHandle}+ dragControls={dragControls}+ statusBadge={+ <IssueTaskStatus+ task={task}+ type="investigation"+ isDisabled={isDisabled}+ />+ }+ headerExtras={+ <>{/* @ts-expect-error TS2322 */}{integrations.has("linear") && <LinearIssueDialog task={task} />}{/* @ts-expect-error TS2322 */}{integrations.has("jira") && <JiraIssueDialog task={task} />}-- <IconButton- icon={<LuChevronRight />}- variant="ghost"- onClick={disclosure.onToggle}- aria-label={t`Open task details`}- className={cn(disclosure.isOpen && "rotate-90")}- />- </div>- </div>-- {disclosure.isOpen && (- <div className="px-4 py-2 rounded">- {permissions.can("update", "quality") && !isDisabled ? (- <Editor- className="w-full min-h-[100px]"- initialValue={content}- onUpload={onUploadImage}- onChange={(value) => {- setContent(value);- onUpdateContent(value);-- // Auto-start issue when typing in task if issue status is "Registered"- if (- routeData?.nonConformance?.status === "Registered" &&- !hasStartedRef.current &&- value?.content?.some((node: any) => node.content?.length > 0)- ) {- hasStartedRef.current = true;- submit(- { status: "In Progress" },- {- method: "post",- action: path.to.issueStatus(id!),- navigate: false- }- );- }- }}- />- ) : (- <div- className="prose dark:prose-invert"- dangerouslySetInnerHTML={{- __html: generateHTML(content as JSONContent)- }}- />- )}- </div>- )}-- <div className="bg-muted/30 border-t px-4 py-2 flex justify-between w-full">- <HStack>- <IssueTaskStatus- task={task}- type="investigation"- isDisabled={isDisabled}- />- <Assignee- table={getTable(type)}- id={task.id}- size="sm"- value={task.assignee ?? undefined}- disabled={isDisabled}- />+ </>+ }+ footerExtras={+ <>{type === "action" && (<><TaskDueDate@@ -433,22 +331,9 @@ export function TaskItem({isDisabled={isDisabled}/>)}- </HStack>- <HStack>- <Button- isDisabled={isDisabled}- leftIcon={statusAction.icon}- variant="secondary"- size="sm"- onClick={() => {- onOperationStatusChange(task.id!, statusAction.status);- }}- >- {statusAction.action}- </Button>- </HStack>- </div>- </div>+ </>+ }+ />);}@@ -632,8 +517,11 @@ export function IssueTaskStatus({onChange?: (status: IssueActionTask["status"]) => void;isDisabled?: boolean;}) {- const { t } = useLingui();- const { currentStatus, onOperationStatusChange } = useTaskStatus({+ const {+ currentStatus,+ onOperationStatusChange,+ isDisabled: statusDisabled+ } = useTaskStatus({task,type,onChange,@@ -641,40 +529,12 @@ export function IssueTaskStatus({});return (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- size="sm"- variant="ghost"- className={className}- aria-label={t`Change status`}- icon={<IssueTaskStatusIcon status={currentStatus} />}- isDisabled={isDisabled}- />- </DropdownMenuTrigger>- {!isDisabled && (- <DropdownMenuContent align="start">- <DropdownMenuRadioGroup- value={currentStatus}- onValueChange={(status) =>- onOperationStatusChange(- task.id!,- status as IssueActionTask["status"]- )- }- >- {nonConformanceTaskStatus.map((status) => (- <DropdownMenuRadioItem key={status} value={status}>- <DropdownMenuIcon- icon={<IssueTaskStatusIcon status={status} />}- />- <span>{status}</span>- </DropdownMenuRadioItem>- ))}- </DropdownMenuRadioGroup>- </DropdownMenuContent>- )}- </DropdownMenu>+ <ActionTaskStatusButton+ status={currentStatus as ActionTaskStatus}+ onChange={(next) => onOperationStatusChange(task.id!, next)}+ isDisabled={statusDisabled}+ className={className}+ />);}diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.tsindex a9c298d831..cfac4e18f4 100644--- a/apps/erp/app/modules/settings/settings.models.ts+++ b/apps/erp/app/modules/settings/settings.models.ts@@ -9,6 +9,7 @@ import {import { labelSizes } from "@carbon/utils";import { z } from "zod";import { zfd } from "zod-form-data";+import { plmReleaseControl } from "~/modules/items/items.models";import { DataType } from "~/modules/shared";export const modulesType = [@@ -147,6 +148,10 @@ export const kanbanOutputValidator = z.object({kanbanOutput: z.enum(kanbanOutputTypes)});+export const plmReleaseControlValidator = z.object({+ plmReleaseControl: z.enum(plmReleaseControl)+});+export const purchasePriceUpdateTimingValidator = z.object({purchasePriceUpdateTiming: z.enum(purchasePriceUpdateTimingTypes)});diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex c0fa68bf7d..f1d7793ef3 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -18,6 +18,7 @@ import {import type { JSONContent } from "@carbon/react";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";+import type { plmReleaseControl as plmReleaseControlOptions } from "~/modules/items/items.models";import type { GenericQueryFilters } from "~/utils/query";import { setGenericQueryFilters } from "~/utils/query";import { interpolateSequenceDate } from "~/utils/string";@@ -1010,6 +1011,17 @@ export async function updateMetricSettings(.eq("id", companyId);}+export async function updatePlmReleaseControlSetting(+ client: SupabaseClient<Database>,+ companyId: string,+ plmReleaseControl: (typeof plmReleaseControlOptions)[number]+) {+ return client+ .from("companySettings")+ .update(sanitize({ plmReleaseControl }))+ .eq("id", companyId);+}+export async function updateProductLabelSize(client: SupabaseClient<Database>,companyId: string,diff --git a/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsx b/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsxindex dcf393d6ce..779acb5bdf 100644--- a/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsx+++ b/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsx@@ -66,6 +66,7 @@ function getEntityPath(entityId: string): string | null {quote: path.to.quote,emp: path.to.employeeAccount,nc: path.to.issue,+ co: path.to.changeOrder,sh: path.to.shipment,rec: path.to.receipt,ic: path.to.inventoryCount,diff --git a/apps/erp/app/modules/users/types.ts b/apps/erp/app/modules/users/types.tsindex 691fe0460c..b6fa3f6f7c 100644--- a/apps/erp/app/modules/users/types.ts+++ b/apps/erp/app/modules/users/types.ts@@ -44,6 +44,8 @@ export type Group = {isSupplierTypeGroup: boolean;name: string;users: User[];+ // Transitive member count, attached by the groups API when `counts=true`.+ memberCount?: number;};children: Group[];};diff --git a/apps/erp/app/routes/api+/items.$itemId.make-method-status.ts b/apps/erp/app/routes/api+/items.$itemId.make-method-status.tsnew file mode 100644index 0000000000..1eaa3b2eaf--- /dev/null+++ b/apps/erp/app/routes/api+/items.$itemId.make-method-status.ts@@ -0,0 +1,24 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import type { LoaderFunctionArgs } from "react-router";+import { getMakeMethods } from "~/modules/items";++// Lightweight status check for the "Add Affected Item" modal: does this item have+// an Active make method? When it doesn't (its current method is still an+// un-activated Draft — the common case), adding a Version change promotes that+// Draft to Active, which the modal warns about before the user commits.+export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "parts"+ });++ const { itemId } = params;+ if (!itemId) return { hasActiveMethod: false, hasAnyMethod: false };++ const methods = await getMakeMethods(client, itemId, companyId);+ const rows = methods.data ?? [];++ return {+ hasAnyMethod: rows.length > 0,+ hasActiveMethod: rows.some((m) => m.status === "Active")+ };+}diff --git a/apps/erp/app/routes/api+/link.ts b/apps/erp/app/routes/api+/link.tsindex fabc9ff41e..1c34db3ec3 100644--- a/apps/erp/app/routes/api+/link.ts+++ b/apps/erp/app/routes/api+/link.ts@@ -63,6 +63,11 @@ function resolve(return path.to.gauge(documentId);case NotificationEvent.NonConformanceAssignment:return path.to.issue(documentId);+ case NotificationEvent.ChangeOrderApproved:+ case NotificationEvent.ChangeOrderRejected:+ case NotificationEvent.ChangeOrderReleased:+ case NotificationEvent.ChangeOrderSubmittedForReview:+ return path.to.changeOrderDetails(documentId);case NotificationEvent.RiskAssignment:return path.to.risk(documentId);case NotificationEvent.ProcedureAssignment:diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex af2ed66f86..f415c7e268 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,6 +1,6 @@{- "generated": "2026-07-17T03:40:11.270Z",- "totalTools": 1335,+ "generated": "2026-07-20T01:28:23.555Z",+ "totalTools": 1374,"modules": 15,"tools": [{@@ -427,7 +427,7 @@"null"]},- "// Balance sheet only: append a computed \"Net Income\" equity line.\n includeCurrentYearEarnings": {+ "includeCurrentYearEarnings": {"type": "boolean"}},@@ -6437,7 +6437,7 @@"type": "string"},"status": {},- "// When set, the transition only applies if the row is still in this status.\n // The `.eq(\"status\", expectedStatus)` makes the read-then-write atomic, so a\n // concurrent transition can't be clobbered (0 rows matched → `.single()`\n // errors and the caller surfaces a failure).\n expectedStatus": {}+ "expectedStatus": {}},"required": ["id",@@ -9298,7 +9298,7 @@"null"]},- "// Combined counterparty filter (customer OR supplier ids) from the table's\n // \"Counterparty\" filter, which sources options from both stores.\n counterpartyIds": {+ "counterpartyIds": {"type": ["array","null"@@ -10204,10 +10204,10 @@}},{- "name": "items_createRevision",+ "name": "items_copyItemPostingGroup","module": "items","classification": "WRITE",- "description": "create revision",+ "description": "copy item posting group","paramCount": 2,"serviceParams": ["client",@@ -10221,108 +10221,59 @@"schema": {"type": "object","properties": {- "item": {},- "revision": {- "type": "string"- }- },- "required": [- "item",- "revision"- ]- }- },- {- "name": "items_deleteConfigurationParameter",- "module": "items",- "classification": "DESTRUCTIVE",- "description": "delete configuration parameter",- "paramCount": 1,- "serviceParams": [- "client",- "id"- ],- "injectAuth": [- "companyId"- ],- "schema": {- "type": "object",- "properties": {- "id": {- "type": "string"- }- },- "required": [- "id"- ]- }- },- {- "name": "items_deleteConfigurationRule",- "module": "items",- "classification": "DESTRUCTIVE",- "description": "delete configuration rule",- "paramCount": 2,- "serviceParams": [- "client",- "field",- "itemId"- ],- "injectAuth": [- "companyId"- ],- "schema": {- "type": "object",- "properties": {- "field": {+ "sourceItemId": {"type": "string"},- "itemId": {+ "targetItemId": {"type": "string"}},"required": [- "field",- "itemId"+ "sourceItemId",+ "targetItemId"]}},{- "name": "items_deleteItemCustomerPart",+ "name": "items_createRevision","module": "items",- "classification": "DESTRUCTIVE",- "description": "delete item customer part",- "paramCount": 1,+ "classification": "WRITE",+ "description": "create revision",+ "paramCount": 3,"serviceParams": ["client",- "id",- "companyId"+ "args"],"injectAuth": [- "companyId"+ "companyId",+ "createdBy",+ "updatedBy"],"schema": {"type": "object","properties": {- "id": {+ "item": {},+ "revision": {"type": "string"+ },+ "active": {+ "type": "boolean"}},"required": [- "id"+ "item",+ "revision"]}},{- "name": "items_deleteSupplierPart",+ "name": "items_getNextRevision","module": "items",- "classification": "DESTRUCTIVE",- "description": "delete supplier part",+ "classification": "READ",+ "description": "get next revision","paramCount": 1,"serviceParams": [- "client",- "id",- "companyId"+ "maxRevision"],"injectAuth": ["companyId"@@ -10330,20 +10281,20 @@"schema": {"type": "object","properties": {- "id": {+ "maxRevision": {"type": "string"}},"required": [- "id"+ "maxRevision"]}},{- "name": "items_deleteConfigurationParameterGroup",+ "name": "items_deleteConfigurationParameter","module": "items","classification": "DESTRUCTIVE",- "description": "delete configuration parameter group",+ "description": "delete configuration parameter","paramCount": 1,"serviceParams": ["client",@@ -10365,14 +10316,15 @@}},{- "name": "items_deleteItem",+ "name": "items_deleteConfigurationRule","module": "items","classification": "DESTRUCTIVE",- "description": "delete item",- "paramCount": 1,+ "description": "delete configuration rule",+ "paramCount": 2,"serviceParams": ["client",- "id"+ "field",+ "itemId"],"injectAuth": ["companyId"@@ -10380,75 +10332,30 @@"schema": {"type": "object","properties": {- "id": {+ "field": {"type": "string"- }- },- "required": [- "id"- ]- }- },- {- "name": "items_deleteItemPostingGroup",- "module": "items",- "classification": "DESTRUCTIVE",- "description": "delete item posting group",- "paramCount": 1,- "serviceParams": [- "client",- "id"- ],- "injectAuth": [- "companyId"- ],- "schema": {- "type": "object",- "properties": {- "id": {+ },+ "itemId": {"type": "string"}},"required": [- "id"+ "field",+ "itemId"]}},{- "name": "items_deleteMaterialDimension",+ "name": "items_deleteItemCustomerPart","module": "items","classification": "DESTRUCTIVE",- "description": "delete material dimension",+ "description": "delete item customer part","paramCount": 1,"serviceParams": ["client",- "id"- ],- "injectAuth": [+ "id","companyId"],- "schema": {- "type": "object",- "properties": {- "id": {- "type": "string"- }- },- "required": [- "id"- ]- }- },- {- "name": "items_deleteMaterialFinish",- "module": "items",- "classification": "DESTRUCTIVE",- "description": "delete material finish",- "paramCount": 1,- "serviceParams": [- "client",- "id"- ],"injectAuth": ["companyId"],@@ -10465,40 +10372,16 @@}},{- "name": "items_deleteMaterialForm",+ "name": "items_deleteSupplierPart","module": "items","classification": "DESTRUCTIVE",- "description": "delete material form",+ "description": "delete supplier part","paramCount": 1,"serviceParams": ["client",- "id"- ],- "injectAuth": [+ "id","companyId"],- "schema": {- "type": "object",- "properties": {- "id": {- "type": "string"- }- },- "required": [- "id"- ]- }- },- {- "name": "items_deleteMaterialGrade",- "module": "items",- "classification": "DESTRUCTIVE",- "description": "delete material grade",- "paramCount": 1,- "serviceParams": [- "client",- "id"- ],"injectAuth": ["companyId"],@@ -10515,10 +10398,10 @@}},{- "name": "items_deleteMaterialSubstance",+ "name": "items_deleteConfigurationParameterGroup","module": "items","classification": "DESTRUCTIVE",- "description": "delete material substance",+ "description": "delete configuration parameter group","paramCount": 1,"serviceParams": ["client",@@ -10540,10 +10423,10 @@}},{- "name": "items_deleteMethodMaterial",+ "name": "items_deleteItem","module": "items","classification": "DESTRUCTIVE",- "description": "delete method material",+ "description": "delete item","paramCount": 1,"serviceParams": ["client",@@ -10565,60 +10448,10 @@}},{- "name": "items_assertMethodOperationIsDraft",- "module": "items",- "classification": "WRITE",- "description": "assert method operation is draft",- "paramCount": 1,- "serviceParams": [- "client",- "operationId"- ],- "injectAuth": [- "companyId"- ],- "schema": {- "type": "object",- "properties": {- "operationId": {- "type": "string"- }- },- "required": [- "operationId"- ]- }- },- {- "name": "items_deleteMethodOperation",- "module": "items",- "classification": "DESTRUCTIVE",- "description": "delete method operation",- "paramCount": 1,- "serviceParams": [- "client",- "methodOperationId"- ],- "injectAuth": [- "companyId"- ],- "schema": {- "type": "object",- "properties": {- "methodOperationId": {- "type": "string"- }- },- "required": [- "methodOperationId"- ]- }- },- {- "name": "items_deleteMethodOperationStep",+ "name": "items_deleteItemPostingGroup","module": "items","classification": "DESTRUCTIVE",- "description": "delete method operation step",+ "description": "delete item posting group","paramCount": 1,"serviceParams": ["client",@@ -10640,10 +10473,235 @@}},{- "name": "items_deleteMethodOperationParameter",+ "name": "items_deleteMaterialDimension","module": "items","classification": "DESTRUCTIVE",- "description": "delete method operation parameter",+ "description": "delete material dimension",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "items_deleteMaterialFinish",+ "module": "items",+ "classification": "DESTRUCTIVE",+ "description": "delete material finish",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "items_deleteMaterialForm",+ "module": "items",+ "classification": "DESTRUCTIVE",+ "description": "delete material form",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "items_deleteMaterialGrade",+ "module": "items",+ "classification": "DESTRUCTIVE",+ "description": "delete material grade",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "items_deleteMaterialSubstance",+ "module": "items",+ "classification": "DESTRUCTIVE",+ "description": "delete material substance",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "items_deleteMethodMaterial",+ "module": "items",+ "classification": "DESTRUCTIVE",+ "description": "delete method material",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "items_assertMethodOperationIsDraft",+ "module": "items",+ "classification": "WRITE",+ "description": "assert method operation is draft",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "operationId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "operationId": {+ "type": "string"+ }+ },+ "required": [+ "operationId"+ ]+ }+ },+ {+ "name": "items_deleteMethodOperation",+ "module": "items",+ "classification": "DESTRUCTIVE",+ "description": "delete method operation",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "methodOperationId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "methodOperationId": {+ "type": "string"+ }+ },+ "required": [+ "methodOperationId"+ ]+ }+ },+ {+ "name": "items_deleteMethodOperationStep",+ "module": "items",+ "classification": "DESTRUCTIVE",+ "description": "delete method operation step",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "items_deleteMethodOperationParameter",+ "module": "items",+ "classification": "DESTRUCTIVE",+ "description": "delete method operation parameter","paramCount": 1,"serviceParams": ["client",@@ -14288,299 +14346,1414 @@}},{- "name": "items_getMaterialTypes",- "module": "items",- "classification": "READ",- "description": "get material types",- "paramCount": 3,- "serviceParams": [- "client",- "companyId",- "args"- ],- "injectAuth": [- "companyId"- ],- "schema": {- "type": "object",- "properties": {- "args": {- "type": "object",- "properties": {- "limit": {- "type": "integer",- "default": 100- },- "offset": {- "type": "integer",- "default": 0- },- "search": {- "type": [- "string",- "null"- ]- }- }- }- }- }- },- {- "name": "items_getMaterialType",- "module": "items",- "classification": "READ",- "description": "get material type",- "paramCount": 1,- "serviceParams": [- "client",- "id"- ],- "injectAuth": [- "companyId"- ],- "schema": {- "type": "object",- "properties": {- "id": {- "type": "string"- }- },- "required": [- "id"- ]- }- },- {- "name": "items_getMaterialTypeList",- "module": "items",- "classification": "READ",- "description": "get material type list",- "paramCount": 2,- "serviceParams": [- "client",- "materialSubstanceId",- "materialFormId",- "companyId"- ],- "injectAuth": [- "companyId"- ],- "schema": {- "type": "object",- "properties": {- "materialSubstanceId": {- "type": "string"- },- "materialFormId": {- "type": "string"- }- },- "required": [- "materialSubstanceId",- "materialFormId"- ]- }- },- {- "name": "items_upsertMaterialType",+ "name": "items_getMaterialTypes",+ "module": "items",+ "classification": "READ",+ "description": "get material types",+ "paramCount": 3,+ "serviceParams": [+ "client",+ "companyId",+ "args"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "args": {+ "type": "object",+ "properties": {+ "limit": {+ "type": "integer",+ "default": 100+ },+ "offset": {+ "type": "integer",+ "default": 0+ },+ "search": {+ "type": [+ "string",+ "null"+ ]+ }+ }+ }+ }+ }+ },+ {+ "name": "items_getMaterialType",+ "module": "items",+ "classification": "READ",+ "description": "get material type",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "items_getMaterialTypeList",+ "module": "items",+ "classification": "READ",+ "description": "get material type list",+ "paramCount": 2,+ "serviceParams": [+ "client",+ "materialSubstanceId",+ "materialFormId",+ "companyId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "materialSubstanceId": {+ "type": "string"+ },+ "materialFormId": {+ "type": "string"+ }+ },+ "required": [+ "materialSubstanceId",+ "materialFormId"+ ]+ }+ },+ {+ "name": "items_upsertMaterialType",+ "module": "items",+ "classification": "WRITE",+ "description": "upsert material type",+ "paramCount": 5,+ "serviceParams": [+ "client",+ "materialType"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "materialSubstanceId": {+ "type": "string"+ },+ "materialFormId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "code": {+ "type": "string"+ }+ },+ "required": [+ "materialSubstanceId",+ "materialFormId",+ "name",+ "code"+ ]+ }+ },+ {+ "name": "items_upsertMaterialSubstance",+ "module": "items",+ "classification": "WRITE",+ "description": "upsert material substance",+ "paramCount": 3,+ "serviceParams": [+ "client",+ "materialSubstance"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "code": {+ "type": "string"+ }+ },+ "required": [+ "name",+ "code"+ ]+ }+ },+ {+ "name": "items_upsertService",+ "module": "items",+ "classification": "WRITE",+ "description": "upsert service",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "service"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "service": {}+ },+ "required": [+ "service"+ ]+ }+ },+ {+ "name": "items_upsertUnitOfMeasure",+ "module": "items",+ "classification": "WRITE",+ "description": "upsert unit of measure",+ "paramCount": 3,+ "serviceParams": [+ "client",+ "unitOfMeasure"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "code": {+ "type": "string"+ },+ "name": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "name"+ ]+ }+ },+ {+ "name": "items_upsertTool",+ "module": "items",+ "classification": "WRITE",+ "description": "upsert tool",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "tool"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "tool": {}+ },+ "required": [+ "tool"+ ]+ }+ },+ {+ "name": "items_getSupplierPriceBreaksForItems",+ "module": "items",+ "classification": "READ",+ "description": "get supplier price breaks for items",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "itemIds"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "itemIds": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "itemIds"+ ]+ }+ },+ {+ "name": "items_lookupBuyPrice",+ "module": "items",+ "classification": "WRITE",+ "description": "lookup buy price",+ "paramCount": 3,+ "serviceParams": [+ "client",+ "itemId",+ "qty",+ "fallbackCost"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "itemId": {+ "type": "string"+ },+ "qty": {+ "type": "number"+ },+ "fallbackCost": {+ "type": "number"+ }+ },+ "required": [+ "itemId",+ "qty",+ "fallbackCost"+ ]+ }+ },+ {+ "name": "items_getSupplierPartPriceBreaks",+ "module": "items",+ "classification": "READ",+ "description": "get supplier part price breaks",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "supplierPartId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "supplierPartId": {+ "type": "string"+ }+ },+ "required": [+ "supplierPartId"+ ]+ }+ },+ {+ "name": "items_getChangeOrder",+ "module": "items",+ "classification": "READ",+ "description": "get change order",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "changeOrderId",+ "companyId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "changeOrderId": {+ "type": "string"+ }+ },+ "required": [+ "changeOrderId"+ ]+ }+ },+ {+ "name": "items_getChangeOrders",+ "module": "items",+ "classification": "READ",+ "description": "get change orders",+ "paramCount": 3,+ "serviceParams": [+ "client",+ "companyId",+ "args"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "args": {+ "type": "object",+ "properties": {+ "limit": {+ "type": "integer",+ "default": 100+ },+ "offset": {+ "type": "integer",+ "default": 0+ },+ "search": {+ "type": [+ "string",+ "null"+ ]+ }+ }+ }+ }+ }+ },+ {+ "name": "items_insertChangeOrder",+ "module": "items",+ "classification": "WRITE",+ "description": "insert change order",+ "paramCount": 12,+ "serviceParams": [+ "client",+ "input"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "changeOrderId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "type": {+ "type": "string"+ },+ "priority": {+ "type": "string"+ },+ "changeOrderTypeId": {+ "type": "string"+ },+ "nonConformanceId": {+ "type": "string"+ },+ "openDate": {+ "type": "string"+ },+ "reasonForChange": {},+ "description": {},+ "dueDate": {+ "type": "string"+ },+ "assignee": {+ "type": "string"+ },+ "customFields": {}+ },+ "required": [+ "name",+ "openDate"+ ]+ }+ },+ {+ "name": "items_updateChangeOrder",+ "module": "items",+ "classification": "WRITE",+ "description": "update change order",+ "paramCount": 13,+ "serviceParams": [+ "client",+ "input"+ ],+ "injectAuth": [+ "companyId",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "changeOrderId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "type": {+ "type": "string"+ },+ "priority": {+ "type": [+ "string",+ "null"+ ]+ },+ "changeOrderTypeId": {+ "type": [+ "string",+ "null"+ ]+ },+ "nonConformanceId": {+ "type": [+ "string",+ "null"+ ]+ },+ "openDate": {+ "type": "string"+ },+ "reasonForChange": {},+ "description": {},+ "dueDate": {+ "type": [+ "string",+ "null"+ ]+ },+ "assignee": {+ "type": [+ "string",+ "null"+ ]+ },+ "customFields": {}+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "items_deleteChangeOrder",+ "module": "items",+ "classification": "DESTRUCTIVE",+ "description": "delete change order",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "changeOrderId",+ "companyId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "changeOrderId": {+ "type": "string"+ }+ },+ "required": [+ "changeOrderId"+ ]+ }+ },+ {+ "name": "items_updateChangeOrderStatus",+ "module": "items",+ "classification": "WRITE",+ "description": "update change order status",+ "paramCount": 4,+ "serviceParams": [+ "client",+ "update"+ ],+ "injectAuth": [+ "companyId",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "fromStatus": {+ "type": "string"+ },+ "toStatus": {+ "type": "string"+ },+ "assignee": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "id",+ "fromStatus",+ "toStatus"+ ]+ }+ },+ {+ "name": "items_getChangeOrderTypes",+ "module": "items",+ "classification": "READ",+ "description": "get change order types",+ "paramCount": 3,+ "serviceParams": [+ "client",+ "companyId",+ "args"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "args": {+ "type": "object",+ "properties": {+ "limit": {+ "type": "integer",+ "default": 100+ },+ "offset": {+ "type": "integer",+ "default": 0+ },+ "search": {+ "type": [+ "string",+ "null"+ ]+ }+ }+ }+ }+ }+ },+ {+ "name": "items_getChangeOrderTypesList",+ "module": "items",+ "classification": "READ",+ "description": "get change order types list",+ "paramCount": 0,+ "serviceParams": [+ "client",+ "companyId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {}+ }+ },+ {+ "name": "items_getChangeOrderType",+ "module": "items",+ "classification": "READ",+ "description": "get change order type",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "items_upsertChangeOrderType",+ "module": "items",+ "classification": "WRITE",+ "description": "upsert change order type",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "changeOrderType"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "changeOrderType": {}+ },+ "required": [+ "changeOrderType"+ ]+ }+ },+ {+ "name": "items_deleteChangeOrderType",+ "module": "items",+ "classification": "DESTRUCTIVE",+ "description": "delete change order type",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "items_getTopLevelProductsForItems",+ "module": "items",+ "classification": "READ",+ "description": "get top level products for items",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "itemIds",+ "companyId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "itemIds": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "itemIds"+ ]+ }+ },+ {+ "name": "items_mintPlaceholderPart",+ "module": "items",+ "classification": "WRITE",+ "description": "mint placeholder part",+ "paramCount": 3,+ "serviceParams": [+ "client",+ "input"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "readableId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "unitOfMeasureCode": {+ "type": "string"+ }+ },+ "required": [+ "readableId",+ "name"+ ]+ }+ },+ {+ "name": "items_createChangeOrderDraftMethod",+ "module": "items",+ "classification": "WRITE",+ "description": "create change order draft method",+ "paramCount": 4,+ "serviceParams": [+ "client",+ "input"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "changeOrderId": {+ "type": "string"+ },+ "itemId": {+ "type": "string"+ },+ "changeType": {},+ "revision": {+ "type": "string"+ }+ },+ "required": [+ "changeOrderId",+ "itemId",+ "changeType"+ ]+ }+ },+ {+ "name": "items_addChangeOrderAffectedItem",+ "module": "items",+ "classification": "WRITE",+ "description": "add change order affected item",+ "paramCount": 5,+ "serviceParams": [+ "client",+ "input"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "changeOrderId": {+ "type": "string"+ },+ "itemId": {+ "type": "string"+ },+ "changeType": {},+ "revision": {+ "type": "string"+ },+ "newPart": {+ "type": "string"+ }+ },+ "required": [+ "changeOrderId",+ "changeType"+ ]+ }+ },+ {+ "name": "items_updateChangeOrderAffectedItemChangeType",+ "module": "items",+ "classification": "WRITE",+ "description": "update change order affected item change type",+ "paramCount": 2,+ "serviceParams": [+ "client",+ "input"+ ],+ "injectAuth": [+ "companyId",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "changeType": {}+ },+ "required": [+ "id",+ "changeType"+ ]+ }+ },+ {+ "name": "items_updateChangeOrderAffectedItemCutover",+ "module": "items",+ "classification": "WRITE",+ "description": "update change order affected item cutover",+ "paramCount": 4,+ "serviceParams": [+ "client",+ "input"+ ],+ "injectAuth": [+ "companyId",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "supersessionMode": {},+ "discontinuationDate": {+ "type": "string"+ },+ "successorEffectivityDate": {+ "type": "string"+ }+ },+ "required": [+ "id",+ "supersessionMode"+ ]+ }+ },+ {+ "name": "items_getChangeOrderAffectedItems",+ "module": "items",+ "classification": "READ",+ "description": "get change order affected items",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "changeOrderId",+ "companyId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "changeOrderId": {+ "type": "string"+ }+ },+ "required": [+ "changeOrderId"+ ]+ }+ },+ {+ "name": "items_removeChangeOrderAffectedItem",+ "module": "items",+ "classification": "WRITE",+ "description": "remove change order affected item",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id",+ "companyId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "items_findChangeOrdersForItem",+ "module": "items",+ "classification": "READ",+ "description": "find change orders for item",+ "paramCount": 2,+ "serviceParams": [+ "client",+ "args"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "itemId": {+ "type": "string"+ },+ "statuses": {+ "type": "array",+ "items": {}+ }+ },+ "required": [+ "itemId"+ ]+ }+ },+ {+ "name": "items_getChangeOrdersForNonConformance",+ "module": "items",+ "classification": "READ",+ "description": "get change orders for non conformance",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "nonConformanceId",+ "companyId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "nonConformanceId": {+ "type": "string"+ }+ },+ "required": [+ "nonConformanceId"+ ]+ }+ },+ {+ "name": "items_findOtherOpenChangeOrdersForItem",+ "module": "items",+ "classification": "READ",+ "description": "find other open change orders for item",+ "paramCount": 2,+ "serviceParams": [+ "client",+ "args"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "itemId": {+ "type": "string"+ },+ "excludeChangeOrderId": {+ "type": "string"+ }+ },+ "required": [+ "itemId",+ "excludeChangeOrderId"+ ]+ }+ },+ {+ "name": "items_getItemChangeOrderData",+ "module": "items",+ "classification": "READ",+ "description": "get item change order data",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "itemId",+ "companyId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "itemId": {+ "type": "string"+ }+ },+ "required": [+ "itemId"+ ]+ }+ },+ {+ "name": "items_getChangeOrderActions",+ "module": "items",+ "classification": "READ",+ "description": "get change order actions",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "changeOrderId",+ "companyId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "changeOrderId": {+ "type": "string"+ }+ },+ "required": [+ "changeOrderId"+ ]+ }+ },+ {+ "name": "items_updateChangeOrderActionStatus",+ "module": "items",+ "classification": "WRITE",+ "description": "update change order action status",+ "paramCount": 2,+ "serviceParams": [+ "client",+ "input"+ ],+ "injectAuth": [+ "companyId",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "status": {+ "type": "string"+ }+ },+ "required": [+ "id",+ "status"+ ]+ }+ },+ {+ "name": "items_deleteChangeOrderAction",+ "module": "items",+ "classification": "DESTRUCTIVE",+ "description": "delete change order action",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "items_updateChangeOrderActionOrder",+ "module": "items",+ "classification": "WRITE",+ "description": "update change order action order",+ "paramCount": 2,+ "serviceParams": [+ "db",+ "updates"+ ],+ "injectAuth": [+ "companyId",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "sortOrder": {+ "type": "number"+ }+ },+ "required": [+ "id",+ "sortOrder"+ ]+ }+ },+ {+ "name": "items_getChangeOrderRequiredActions",+ "module": "items",+ "classification": "READ",+ "description": "get change order required actions",+ "paramCount": 3,+ "serviceParams": [+ "client",+ "companyId",+ "args"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "args": {+ "type": "object",+ "properties": {+ "limit": {+ "type": "integer",+ "default": 100+ },+ "offset": {+ "type": "integer",+ "default": 0+ },+ "search": {+ "type": [+ "string",+ "null"+ ]+ }+ }+ }+ }+ }+ },+ {+ "name": "items_getChangeOrderRequiredActionsList",+ "module": "items",+ "classification": "READ",+ "description": "get change order required actions list",+ "paramCount": 0,+ "serviceParams": [+ "client",+ "companyId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {}+ }+ },+ {+ "name": "items_getChangeOrderRequiredAction",+ "module": "items",+ "classification": "READ",+ "description": "get change order required action",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "items_upsertChangeOrderRequiredAction",+ "module": "items",+ "classification": "WRITE",+ "description": "upsert change order required action",+ "paramCount": 3,+ "serviceParams": [+ "client",+ "input"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "active": {+ "type": "boolean"+ }+ },+ "required": [+ "name",+ "active"+ ]+ }+ },+ {+ "name": "items_deleteChangeOrderRequiredAction",+ "module": "items",+ "classification": "DESTRUCTIVE",+ "description": "delete change order required action",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "items_setChangeOrderActionTasks","module": "items","classification": "WRITE",- "description": "upsert material type",- "paramCount": 5,- "serviceParams": [- "client",- "materialType"- ],- "injectAuth": [- "companyId",- "createdBy",- "updatedBy"- ],- "schema": {- "type": "object",- "properties": {- "id": {- "type": "string"- },- "materialSubstanceId": {- "type": "string"- },- "materialFormId": {- "type": "string"- },- "name": {- "type": "string"- },- "code": {- "type": "string"- }- },- "required": [- "materialSubstanceId",- "materialFormId",- "name",- "code"- ]- }- },- {- "name": "items_upsertMaterialSubstance",- "module": "items",- "classification": "WRITE",- "description": "upsert material substance",- "paramCount": 3,+ "description": "set change order action tasks",+ "paramCount": 2,"serviceParams": ["client",- "materialSubstance"+ "input"],"injectAuth": ["companyId",- "createdBy","updatedBy"],"schema": {"type": "object","properties": {- "id": {+ "changeOrderId": {"type": "string"},- "name": {- "type": "string"- },- "code": {- "type": "string"+ "requiredActionIds": {+ "type": "array",+ "items": {+ "type": "string"+ }}},"required": [- "name",- "code"+ "changeOrderId",+ "requiredActionIds"]}},{- "name": "items_upsertService",+ "name": "items_seedDefaultChangeOrderActions","module": "items","classification": "WRITE",- "description": "upsert service",+ "description": "seed default change order actions","paramCount": 1,"serviceParams": ["client",- "service"- ],- "injectAuth": [- "companyId",- "createdBy",- "updatedBy"- ],- "schema": {- "type": "object",- "properties": {- "service": {}- },- "required": [- "service"- ]- }- },- {- "name": "items_upsertUnitOfMeasure",- "module": "items",- "classification": "WRITE",- "description": "upsert unit of measure",- "paramCount": 3,- "serviceParams": [- "client",- "unitOfMeasure"+ "input"],"injectAuth": [- "companyId",- "createdBy",- "updatedBy"+ "companyId"],"schema": {"type": "object","properties": {- "id": {- "type": "string"- },- "code": {- "type": "string"- },- "name": {+ "changeOrderId": {"type": "string"}},"required": [- "code",- "name"+ "changeOrderId"]}},{- "name": "items_upsertTool",+ "name": "items_diffMethod","module": "items","classification": "WRITE",- "description": "upsert tool",+ "description": "diff method","paramCount": 1,"serviceParams": [- "client",- "tool"- ],- "injectAuth": [- "companyId",- "createdBy",- "updatedBy"- ],- "schema": {- "type": "object",- "properties": {- "tool": {}- },- "required": [- "tool"- ]- }- },- {- "name": "items_getSupplierPriceBreaksForItems",- "module": "items",- "classification": "READ",- "description": "get supplier price breaks for items",- "paramCount": 1,- "serviceParams": [- "client",- "itemIds"- ],- "injectAuth": [- "companyId"- ],- "schema": {- "type": "object",- "properties": {- "itemIds": {- "type": "array",- "items": {- "type": "string"- }- }- },- "required": [- "itemIds"- ]- }- },- {- "name": "items_lookupBuyPrice",- "module": "items",- "classification": "WRITE",- "description": "lookup buy price",- "paramCount": 3,- "serviceParams": [- "client",- "itemId",- "qty",- "fallbackCost"+ "input"],"injectAuth": ["companyId"@@ -14588,32 +15761,23 @@"schema": {"type": "object","properties": {- "itemId": {- "type": "string"- },- "qty": {- "type": "number"- },- "fallbackCost": {- "type": "number"- }+ "input": {}},"required": [- "itemId",- "qty",- "fallbackCost"+ "input"]}},{- "name": "items_getSupplierPartPriceBreaks",+ "name": "items_getChangeOrderDiff","module": "items","classification": "READ",- "description": "get supplier part price breaks",+ "description": "get change order diff","paramCount": 1,"serviceParams": ["client",- "supplierPartId"+ "changeOrderId",+ "companyId"],"injectAuth": ["companyId"@@ -14621,12 +15785,12 @@"schema": {"type": "object","properties": {- "supplierPartId": {+ "changeOrderId": {"type": "string"}},"required": [- "supplierPartId"+ "changeOrderId"]}},@@ -16057,7 +17221,7 @@"jobId": {"type": "string"},- "// Optional - if updating an existing job\n dueDate": {+ "dueDate": {"type": ["string","null"@@ -16071,7 +17235,7 @@}},"required": [- "// Optional - if updating an existing job\n dueDate",+ "dueDate","deadlineType","locationId"]@@ -18679,7 +19843,7 @@"module": "production","classification": "WRITE","description": "recalculate job requirements",- "paramCount": 2,+ "paramCount": 1,"serviceParams": ["client","params"@@ -18693,14 +19857,10 @@"properties": {"id": {"type": "string"- },- "// job id\n companyId": {- "type": "string"}},"required": [- "id",- "// job id\n companyId"+ "id"]}},@@ -18709,7 +19869,7 @@"module": "production","classification": "WRITE","description": "recalculate job make method requirements",- "paramCount": 2,+ "paramCount": 1,"serviceParams": ["client","params"@@ -18723,14 +19883,10 @@"properties": {"id": {"type": "string"- },- "// job make method id\n companyId": {- "type": "string"}},"required": [- "id",- "// job make method id\n companyId"+ "id"]}},@@ -26477,7 +27633,7 @@},"status": {},"source": {},- "// might be needed later for filtering by assignee\n assignee": {+ "assignee": {"type": "array","items": {"type": "string"@@ -38558,6 +39714,33 @@]}},+ {+ "name": "settings_updatePlmReleaseControlSetting",+ "module": "settings",+ "classification": "WRITE",+ "description": "update plm release control setting",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "plmReleaseControl"+ ],+ "injectAuth": [+ "companyId",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "plmReleaseControl": {+ "type": "string"+ }+ },+ "required": [+ "plmReleaseControl"+ ]+ }+ },{"name": "settings_updateProductLabelSize","module": "settings",diff --git a/apps/erp/app/routes/share+/scar.$id.tsx b/apps/erp/app/routes/share+/scar.$id.tsxindex cc921dbf06..a226fda9b1 100644--- a/apps/erp/app/routes/share+/scar.$id.tsx+++ b/apps/erp/app/routes/share+/scar.$id.tsx@@ -32,6 +32,7 @@ import {} from "react-router";import z from "zod";import { zfd } from "zod-form-data";+import { actionTaskStatusActions } from "~/components/ActionTasks/ActionTaskCard";import { getSupplier } from "~/modules/purchasing";import type { IssueActionTask } from "~/modules/quality";import {@@ -41,7 +42,7 @@ import {updateIssueTaskContent,updateIssueTaskStatus} from "~/modules/quality";-import { statusActions, TaskProgress } from "~/modules/quality/ui/Issue";+import { TaskProgress } from "~/modules/quality/ui/Issue";import IssueStatus from "~/modules/quality/ui/Issue/IssueStatus";import { getCompany } from "~/modules/settings";import { getExternalLink } from "~/modules/shared";@@ -361,7 +362,7 @@ export function TaskItem({task,type});- const statusAction = statusActions[currentStatus];+ const statusAction = actionTaskStatusActions[currentStatus];const { content, setContent, onUpdateContent } = useTaskNotes({initialContent: (task.notes ?? {}) as JSONContent,taskId: task.id!,@@ -429,7 +430,7 @@ export function TaskItem({variant="secondary"size="sm"onClick={() => {- onOperationStatusChange(task.id!, statusAction.status);+ onOperationStatusChange(task.id!, statusAction.next);}}>{statusAction.action}diff --git a/apps/erp/app/routes/x+/change-order+/_layout.tsx b/apps/erp/app/routes/x+/change-order+/_layout.tsxnew file mode 100644index 0000000000..9b7be5b8c1--- /dev/null+++ b/apps/erp/app/routes/x+/change-order+/_layout.tsx@@ -0,0 +1,19 @@+import { msg } from "@lingui/core/macro";+import type { MetaFunction } from "react-router";+import { Outlet } from "react-router";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const meta: MetaFunction = () => {+ return [{ title: "Carbon | Change Order" }];+};++export const handle: Handle = {+ breadcrumb: msg`Items`,+ to: path.to.items,+ module: "items"+};++export default function ChangeOrderRoute() {+ return <Outlet />;+}diff --git a/apps/erp/app/routes/x+/change-order+/new.tsx b/apps/erp/app/routes/x+/change-order+/new.tsxnew file mode 100644index 0000000000..62f691ea89--- /dev/null+++ b/apps/erp/app/routes/x+/change-order+/new.tsx@@ -0,0 +1,162 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { Json } from "@carbon/database";+import { validationError, validator } from "@carbon/form";+import { getLocalTimeZone, today } from "@internationalized/date";+import { msg } from "@lingui/core/macro";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { redirect, useLoaderData } from "react-router";+import { useUser } from "~/hooks";+import {+ addChangeOrderAffectedItem,+ changeOrderValidator,+ getChangeOrderTypesList,+ insertChangeOrder+} from "~/modules/items";+import { ChangeOrderForm } from "~/modules/items/ui/ChangeOrder";+import { setCustomFields } from "~/utils/form";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const handle: Handle = {+ breadcrumb: msg`Change Orders`,+ to: path.to.changeOrders,+ module: "items"+};++// The reason/description form fields arrive as plain text; the columns are+// tiptap JSON, so wrap non-empty text into a minimal doc (the inline Editor on+// the detail page then edits it as rich text). Empty stays undefined.+function toRichText(value: string | undefined): Json | undefined {+ if (!value) return undefined;+ return {+ type: "doc",+ content: [{ type: "paragraph", content: [{ type: "text", text: value }] }]+ } as unknown as Json;+}++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "parts"+ });++ const types = await getChangeOrderTypesList(client, companyId);++ // "Create Change Order" from an Issue (NCR) links here with the source in the+ // query string. Pre-link the non-conformance so the created CO references it+ // (changeOrder.nonConformanceId) — the create action reads this off the form.+ const url = new URL(request.url);+ const sourceType = url.searchParams.get("sourceType");+ const sourceId = url.searchParams.get("sourceId") ?? undefined;+ const name = url.searchParams.get("name") ?? undefined;++ const nonConformanceId =+ sourceType === "nonConformance" ? sourceId : undefined;++ return {+ types: types.data ?? [],+ nonConformanceId: nonConformanceId ?? "",+ name: name ?? ""+ };+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "parts"+ });++ const formData = await request.formData();+ const validation = await validator(changeOrderValidator).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const d = validation.data;++ const createResult = await insertChangeOrder(client, {+ changeOrderId: d.changeOrderId || undefined,+ name: d.name,+ reasonForChange: toRichText(d.reasonForChange),+ description: toRichText(d.description),+ priority: d.priority,+ changeOrderTypeId: d.changeOrderTypeId || undefined,+ nonConformanceId: d.nonConformanceId || undefined,+ openDate: d.openDate || today(getLocalTimeZone()).toString(),+ dueDate: d.dueDate || undefined,+ assignee: d.assignee || undefined,+ companyId,+ createdBy: userId,+ customFields: setCustomFields(formData)+ });++ if (createResult.error || !createResult.data) {+ throw redirect(+ path.to.changeOrders,+ await flash(+ request,+ error(createResult.error, "Failed to create change order")+ )+ );+ }++ // Attach any affected Parts/Tools picked at create time. Each is added as a+ // Version change (the service coerces Buy items to Revision). Best-effort: the+ // CO already exists, so a per-item failure lands the user on the detail page+ // with a warning rather than losing the CO.+ const affectedItemIds = [...new Set(d.affectedItemIds ?? [])];+ let affectedError: Parameters<typeof error>[0] = null;+ for (const itemId of affectedItemIds) {+ const add = await addChangeOrderAffectedItem(client, {+ changeOrderId: createResult.data.id,+ itemId,+ changeType: "Version",+ companyId,+ userId+ });+ if (add.error) affectedError = add.error;+ }++ if (affectedError) {+ throw redirect(+ path.to.changeOrderDetails(createResult.data.id),+ await flash(+ request,+ error(+ affectedError,+ "Change order created, but some items could not be added"+ )+ )+ );+ }++ throw redirect(path.to.changeOrderDetails(createResult.data.id));+}++export default function ChangeOrderNewRoute() {+ const { types, nonConformanceId, name } = useLoaderData<typeof loader>();+ const user = useUser();++ const initialValues = {+ id: undefined,+ changeOrderId: undefined,+ name,+ reasonForChange: "",+ description: "",+ changeOrderTypeId: "",+ assignee: user.id,+ priority: "Medium" as const,+ openDate: today(getLocalTimeZone()).toString(),+ dueDate: "",+ nonConformanceId,+ affectedItemIds: []+ };++ return (+ <div className="max-w-4xl w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">+ <ChangeOrderForm initialValues={initialValues} types={types} />+ </div>+ );+}diff --git a/apps/erp/app/routes/x+/issue+/$id.tsx b/apps/erp/app/routes/x+/issue+/$id.tsxindex 6364634b5f..99cadd1ff9 100644--- a/apps/erp/app/routes/x+/issue+/$id.tsx+++ b/apps/erp/app/routes/x+/issue+/$id.tsx@@ -14,7 +14,10 @@ import {useParams} from "react-router";import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";-import { getItemFiles } from "~/modules/items";+import {+ getChangeOrdersForNonConformance,+ getItemFiles+} from "~/modules/items";import {getIssue,getIssueAssociations,@@ -55,13 +58,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {nonConformanceTypes,requiredActions,suppliers,- tags+ tags,+ changeOrders] = await Promise.all([getIssue(client, id),getIssueTypesList(client, companyId),getRequiredActionsList(client, companyId),getIssueSuppliers(client, id, companyId),- getTagsList(client, companyId, "nonConformance")+ getTagsList(client, companyId, "nonConformance"),+ // Reverse Linked-NCR cross-link (4a): COs referencing this issue.+ getChangeOrdersForNonConformance(client, id, companyId)]);if (nonConformance.error) {@@ -78,7 +84,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {nonConformanceTypes: nonConformanceTypes.data ?? [],requiredActions: requiredActions.data ?? [],suppliers: suppliers.data ?? [],- tags: tags.data ?? []+ tags: tags.data ?? [],+ changeOrders: changeOrders.data ?? []};}diff --git a/apps/erp/app/routes/x+/items+/_layout.tsx b/apps/erp/app/routes/x+/items+/_layout.tsxindex 949a9f8695..b96adf44a9 100644--- a/apps/erp/app/routes/x+/items+/_layout.tsx+++ b/apps/erp/app/routes/x+/items+/_layout.tsx@@ -1,7 +1,7 @@import { VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { MetaFunction } from "react-router";-import { Outlet } from "react-router";+import { Outlet, useMatches } from "react-router";import { GroupedContentSidebar } from "~/components/Layout";import { CollapsibleSidebarProvider } from "~/components/Layout/Navigation";import useItemsSubmodules from "~/modules/items/ui/useItemsSubmodules";@@ -20,11 +20,23 @@ export const handle: Handle = {export default function PartsRoute() {const { groups } = useItemsSubmodules();+ // A full-screen detail view (the change-order workspace) can opt out of the+ // module sidebar via its route handle so we don't stack two left sidebars.+ const matches = useMatches();+ const hideSidebar = matches.some(+ (m) => (m.handle as Handle | undefined)?.hideModuleSidebar+ );return (<CollapsibleSidebarProvider>- <div className="grid grid-cols-[auto_1fr] w-full h-full">- <GroupedContentSidebar groups={groups} />+ <div+ className={+ hideSidebar+ ? "w-full h-full"+ : "grid grid-cols-[auto_1fr] w-full h-full"+ }+ >+ {!hideSidebar && <GroupedContentSidebar groups={groups} />}<VStack spacing={0} className="h-full"><Outlet /></VStack>diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.$affectedId.details.$supplierPartId.delete.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.$affectedId.details.$supplierPartId.delete.tsxnew file mode 100644index 0000000000..b6cb017fb5--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.$affectedId.details.$supplierPartId.delete.tsx@@ -0,0 +1,41 @@+import { error, notFound, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs } from "react-router";+import { redirect } from "react-router";+import { deleteSupplierPart } from "~/modules/items";+import { path } from "~/utils/path";++// Delete action for a supplier part managed on a CO line. Action-only: the+// ConfirmDelete modal is rendered inline by the embedded Supplier Parts grid+// (deleteSupplierPath), so there is no default export. Redirecting back to the+// CO line detail revalidates the $id loader (refreshing the grid) and carries+// the flash — mirroring the part purchasing delete route's shape.+export async function action({ request, params }: ActionFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ delete: "parts"+ });++ const { id, affectedId, supplierPartId } = params;+ if (!id) throw notFound("Could not find id");+ if (!affectedId) throw notFound("Could not find affectedId");+ if (!supplierPartId) throw notFound("Could not find supplierPartId");++ const { error: deleteError } = await deleteSupplierPart(+ client,+ supplierPartId,+ companyId+ );++ if (deleteError) {+ throw redirect(+ path.to.changeOrderAffectedItem(id, affectedId),+ await flash(request, error(deleteError, "Failed to delete supplier part"))+ );+ }++ throw redirect(+ path.to.changeOrderAffectedItem(id, affectedId),+ await flash(request, success("Supplier part deleted"))+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.$affectedId.details.$supplierPartId.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.$affectedId.details.$supplierPartId.tsxnew file mode 100644index 0000000000..53e8c4a35c--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.$affectedId.details.$supplierPartId.tsx@@ -0,0 +1,103 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import type { LoaderFunctionArgs } from "react-router";+import { useLoaderData, useNavigate, useParams } from "react-router";+import { useRouteData } from "~/hooks";+import type { AffectedItemDraft } from "~/modules/items/ui/ChangeOrder";+import { SupplierPartForm } from "~/modules/items/ui/Item";+import { path } from "~/utils/path";++// Edit drawer for a supplier part on a CO line's draft item — reached+// relatively from the embedded Supplier Parts grid. The loader mirrors the part+// purchasing edit route ($itemId.purchasing.$supplierPartId): the supplier part+// row + its price breaks (the form re-posts the full price-break set, so they+// MUST be seeded or saving would wipe them) + purchase history. No action here:+// the form posts to the part edit action (path.to.partSupplier), which returns+// { success } so the CO stays put.+export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "parts"+ });++ const { supplierPartId } = params;+ if (!supplierPartId) throw new Error("Could not find supplierPartId");++ const [supplierPartResult, priceBreaksResult] = await Promise.all([+ client+ .from("supplierPart")+ .select("*")+ .eq("id", supplierPartId)+ .eq("companyId", companyId)+ .single(),+ client+ .from("supplierPartPrice")+ .select("quantity, unitPrice, sourceType, sourceDocumentId, createdAt")+ .eq("supplierPartId", supplierPartId)+ .order("quantity", { ascending: true })+ ]);++ if (!supplierPartResult?.data)+ throw new Error("Could not find supplier part");++ const supplierPart = supplierPartResult.data;++ const purchasingHistory = await client+ .from("purchaseOrderLine")+ .select(+ "id, purchaseQuantity, unitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate)"+ )+ .eq("itemId", supplierPart.itemId)+ .eq("purchaseOrder.supplierId", supplierPart.supplierId)+ .order("createdAt", { ascending: false })+ .limit(10);++ return {+ supplierPart,+ priceBreaks: priceBreaksResult.data ?? [],+ purchasingHistory: purchasingHistory.data ?? []+ };+}++export default function ChangeOrderEditSupplierPartRoute() {+ const { id, affectedId } = useParams();+ if (!id) throw new Error("Could not find id");+ if (!affectedId) throw new Error("Could not find affectedId");++ const { supplierPart, priceBreaks, purchasingHistory } =+ useLoaderData<typeof loader>();++ const routeData = useRouteData<{ affectedItems: AffectedItemDraft[] }>(+ path.to.changeOrder(id)+ );+ const affected =+ routeData?.affectedItems.find((a) => a.affectedItem.id === affectedId) ??+ null;++ const navigate = useNavigate();+ const onClose = () =>+ navigate(path.to.changeOrderAffectedItem(id, affectedId));++ const initialValues = {+ id: supplierPart.id,+ itemId: supplierPart.itemId,+ supplierId: supplierPart.supplierId,+ supplierPartId: supplierPart.supplierPartId ?? "",+ unitPrice: supplierPart.unitPrice ?? 0,+ supplierUnitOfMeasureCode: supplierPart.supplierUnitOfMeasureCode ?? "EA",+ minimumOrderQuantity: supplierPart.minimumOrderQuantity ?? 1,+ orderMultiple: supplierPart.orderMultiple ?? 1,+ conversionFactor: supplierPart.conversionFactor ?? 1+ };++ return (+ <SupplierPartForm+ type="Part"+ initialValues={initialValues}+ unitOfMeasureCode={+ affected?.partData?.partSummary?.unitOfMeasureCode ?? ""+ }+ priceBreaks={priceBreaks}+ purchasingHistory={purchasingHistory}+ onClose={onClose}+ />+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.$affectedId.details.new.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.$affectedId.details.new.tsxnew file mode 100644index 0000000000..c05f582fe0--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.$affectedId.details.new.tsx@@ -0,0 +1,51 @@+import { useNavigate, useParams } from "react-router";+import { useRouteData } from "~/hooks";+import type { AffectedItemDraft } from "~/modules/items/ui/ChangeOrder";+import { SupplierPartForm } from "~/modules/items/ui/Item";+import { path } from "~/utils/path";++// Create drawer for a supplier part on a CO line's draft item (Buy Revision /+// New Part) — reached relatively from the Supplier Parts grid embedded in+// AffectedItemDetail. No action here: the form posts to the part purchasing+// create action (path.to.newPartSupplier(draftItemId)), which returns+// { success } without redirecting, so the CO stays put and loader revalidation+// refreshes the grid in place.+export default function ChangeOrderNewSupplierPartRoute() {+ const { id, affectedId } = useParams();+ if (!id) throw new Error("Could not find id");+ if (!affectedId) throw new Error("Could not find affectedId");++ const routeData = useRouteData<{ affectedItems: AffectedItemDraft[] }>(+ path.to.changeOrder(id)+ );+ const affected =+ routeData?.affectedItems.find((a) => a.affectedItem.id === affectedId) ??+ null;++ const navigate = useNavigate();+ const onClose = () =>+ navigate(path.to.changeOrderAffectedItem(id, affectedId));++ // The grid only renders (and links here) for Part-type lines with partData.+ if (!affected?.partData) return null;++ const initialValues = {+ itemId: affected.draftItemId,+ supplierId: "",+ supplierPartId: "",+ unitPrice: 0,+ supplierUnitOfMeasureCode: "EA",+ minimumOrderQuantity: 1,+ orderMultiple: 1,+ conversionFactor: 1+ };++ return (+ <SupplierPartForm+ type="Part"+ initialValues={initialValues}+ unitOfMeasureCode={affected.partData.partSummary?.unitOfMeasureCode ?? ""}+ onClose={onClose}+ />+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.$affectedId.details.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.$affectedId.details.tsxnew file mode 100644index 0000000000..b1bbdb2c1d--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.$affectedId.details.tsx@@ -0,0 +1,51 @@+import { VStack } from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import { useParams } from "react-router";+import { useRouteData } from "~/hooks";+import type { ChangeOrder } from "~/modules/items";+import { canEditChangeOrder } from "~/modules/items";+import type { AffectedItemDraft } from "~/modules/items/ui/ChangeOrder";+import AffectedItemDetail from "~/modules/items/ui/ChangeOrder/AffectedItemDetail";+import { path } from "~/utils/path";++// The selected affected item's line detail, addressed by the URL (not client+// state) — mirrors the sales order line route `$orderId.$lineId.details`. Its+// data comes from the parent $id loader (useRouteData); the URL only decides+// which affected item to show, so refresh + back/forward reselect it.+export default function ChangeOrderAffectedItemRoute() {+ const { id, affectedId } = useParams();+ if (!id) throw new Error("Could not find id");++ const routeData = useRouteData<{+ changeOrder: ChangeOrder;+ affectedItems: AffectedItemDraft[];+ }>(path.to.changeOrder(id));++ const changeOrder = routeData?.changeOrder;+ if (!changeOrder) throw new Error("Could not find change order data");++ const affected =+ routeData?.affectedItems.find((a) => a.affectedItem.id === affectedId) ??+ null;++ if (!affected) {+ return (+ <div className="flex items-center justify-center h-full text-sm text-muted-foreground">+ <Trans>Affected item not found.</Trans>+ </div>+ );+ }++ const isDisabled = !canEditChangeOrder(changeOrder.status);++ return (+ <VStack spacing={2} className="p-2">+ <AffectedItemDetail+ key={affected.affectedItem.id}+ changeOrderId={id}+ affected={affected}+ isDisabled={isDisabled}+ />+ </VStack>+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id._index.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id._index.tsxnew file mode 100644index 0000000000..9b7c32d28e--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/$id._index.tsx@@ -0,0 +1,9 @@+import type { LoaderFunctionArgs } from "react-router";+import { redirect } from "react-router";+import { path } from "~/utils/path";++export async function loader({ params }: LoaderFunctionArgs) {+ const { id } = params;+ if (!id) throw new Error("Could not find id");+ throw redirect(path.to.changeOrderDetails(id));+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.action.$actionId.status.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.action.$actionId.status.tsxnew file mode 100644index 0000000000..a10b1d7daa--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.action.$actionId.status.tsx@@ -0,0 +1,49 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import type { ActionFunctionArgs } from "react-router";+import { data } from "react-router";+import {+ changeOrderActionStatusValidator,+ updateChangeOrderActionStatus+} from "~/modules/items";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "parts"+ });++ const formData = await request.formData();+ const validation = await validator(changeOrderActionStatusValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, status } = validation.data;+ if (id !== params.actionId) {+ return data(+ { success: false },+ await flash(request, error("Invalid action ID", "Invalid action ID"))+ );+ }++ const update = await updateChangeOrderActionStatus(client, {+ id,+ status,+ userId+ });++ if (update.error) {+ return data(+ { success: false },+ await flash(request, error(update.error, "Failed to update status"))+ );+ }++ return { success: true };+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.action.delete.$actionId.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.action.delete.$actionId.tsxnew file mode 100644index 0000000000..f462e56e03--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.action.delete.$actionId.tsx@@ -0,0 +1,27 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs } from "react-router";+import { data } from "react-router";+import { deleteChangeOrderAction } from "~/modules/items";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client } = await requirePermissions(request, {+ delete: "parts"+ });++ const { actionId } = params;+ if (!actionId) throw new Error("Could not find actionId");++ const remove = await deleteChangeOrderAction(client, actionId);++ if (remove.error) {+ return data(+ { success: false },+ await flash(request, error(remove.error, "Failed to remove action"))+ );+ }++ return { success: true };+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.action.order.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.action.order.tsxnew file mode 100644index 0000000000..53906b1262--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.action.order.tsx@@ -0,0 +1,41 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs } from "react-router";+import { data } from "react-router";+import { updateChangeOrderActionOrder } from "~/modules/items";+import { getDatabaseClient } from "~/services/database.server";++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { userId } = await requirePermissions(request, {+ update: "parts"+ });++ const updateMap = (await request.formData()).get("updates") as string;+ if (!updateMap) {+ return data(+ { success: false },+ await flash(request, error(null, "Failed to receive a new sort order"))+ );+ }++ const updates = Object.entries(+ JSON.parse(updateMap) as Record<string, number>+ ).map(([id, sortOrder]) => ({+ id,+ sortOrder: Number(sortOrder),+ updatedBy: userId+ }));++ try {+ await updateChangeOrderActionOrder(getDatabaseClient(), updates);+ } catch (err) {+ return data(+ { success: false },+ await flash(request, error(err, "Failed to update sort order"))+ );+ }++ return { success: true };+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.action.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.action.tsxnew file mode 100644index 0000000000..0edd81af67--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.action.tsx@@ -0,0 +1,40 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs } from "react-router";+import { data } from "react-router";+import { setChangeOrderActionTasks } from "~/modules/items";++// Reconcile a change order's action tasks to the set chosen in the sidebar's+// "Required Actions" multiselect (mirrors Quality's requiredActionIds field):+// selected templates are instantiated, deselected ones removed.+export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "parts"+ });++ const { id } = params;+ if (!id) throw new Error("id not found");++ const formData = await request.formData();+ const requiredActionIds = String(formData.get("actionIds") ?? "")+ .split(",")+ .filter(Boolean);++ const result = await setChangeOrderActionTasks(client, {+ changeOrderId: id,+ requiredActionIds,+ companyId,+ userId+ });++ if (result.error) {+ return data(+ { success: false },+ await flash(request, error(result.error, "Failed to update actions"))+ );+ }++ return { success: true };+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.affected.$affectedId.change-type.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.affected.$affectedId.change-type.tsxnew file mode 100644index 0000000000..9540919502--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.affected.$affectedId.change-type.tsx@@ -0,0 +1,56 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import type { ActionFunctionArgs } from "react-router";+import { data } from "react-router";+import {+ changeOrderAffectedItemChangeTypeValidator,+ updateChangeOrderAffectedItemChangeType+} from "~/modules/items";++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "parts"+ });++ const formData = await request.formData();+ const validation = await validator(+ changeOrderAffectedItemChangeTypeValidator+ ).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, changeType } = validation.data;++ // A New Part is net-new by construction — it can't be switched to (or away+ // from) another type. Belt-and-suspenders with the service-level guard.+ if (changeType === "New Part") {+ return data(+ { success: false },+ await flash(+ request,+ error(null, "New Part change type cannot be switched")+ )+ );+ }++ const update = await updateChangeOrderAffectedItemChangeType(client, {+ id,+ changeType,+ companyId,+ userId+ });++ if (update.error) {+ return data(+ { success: false },+ await flash(request, error(update.error, "Failed to change type"))+ );+ }++ return { success: true, id: update.data?.id };+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.affected.$affectedId.cutover.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.affected.$affectedId.cutover.tsxnew file mode 100644index 0000000000..7b229d0048--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.affected.$affectedId.cutover.tsx@@ -0,0 +1,50 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import type { ActionFunctionArgs } from "react-router";+import { data } from "react-router";+import {+ changeOrderAffectedItemCutoverValidator,+ updateChangeOrderAffectedItemCutover+} from "~/modules/items";++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "parts"+ });++ const formData = await request.formData();+ const validation = await validator(+ changeOrderAffectedItemCutoverValidator+ ).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const {+ id,+ supersessionMode,+ discontinuationDate,+ successorEffectivityDate+ } = validation.data;++ const update = await updateChangeOrderAffectedItemCutover(client, {+ id,+ supersessionMode,+ discontinuationDate,+ successorEffectivityDate,+ userId+ });++ if (update.error) {+ return data(+ { success: false },+ await flash(request, error(update.error, "Failed to update cutover"))+ );+ }++ return { success: true, id: update.data?.id };+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.affected.delete.$affectedId.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.affected.delete.$affectedId.tsxnew file mode 100644index 0000000000..d705a29ab0--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.affected.delete.$affectedId.tsx@@ -0,0 +1,34 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs } from "react-router";+import { data } from "react-router";+import { removeChangeOrderAffectedItem } from "~/modules/items";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId } = await requirePermissions(request, {+ delete: "parts"+ });++ const { affectedId } = params;+ if (!affectedId) throw new Error("Could not find affectedId");++ const remove = await removeChangeOrderAffectedItem(+ client,+ affectedId,+ companyId+ );++ if (remove.error) {+ return data(+ { success: false },+ await flash(+ request,+ error(remove.error, "Failed to remove affected item")+ )+ );+ }++ return { success: true };+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.affected.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.affected.tsxnew file mode 100644index 0000000000..8cf3ea52aa--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.affected.tsx@@ -0,0 +1,94 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import type { ActionFunctionArgs } from "react-router";+import { data } from "react-router";+import {+ addChangeOrderAffectedItem,+ changeOrderAffectedItemValidator,+ changeOrderNewPartValidator+} from "~/modules/items";++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "parts"+ });++ const formData = await request.formData();++ // Net-new "New Part": no existing itemId — mint a brand-new Part/Tool and add+ // it as a New Part affected item. The other change types add an existing item.+ if (formData.get("changeType") === "New Part") {+ const validation = await validator(changeOrderNewPartValidator).validate(+ formData+ );+ if (validation.error) {+ return validationError(validation.error);+ }+ const {+ changeOrderId,+ readableId,+ name,+ replenishmentSystem,+ itemTrackingType+ } = validation.data;+ const add = await addChangeOrderAffectedItem(client, {+ changeOrderId,+ changeType: "New Part",+ // A net-new affected item is always a Part.+ newPart: {+ readableId,+ name,+ itemType: "Part",+ replenishmentSystem,+ itemTrackingType+ },+ companyId,+ userId+ });+ if (add.error || !add.data) {+ return data(+ { success: false },+ await flash(+ request,+ error(add.error, add.error?.message ?? "Failed to add new part")+ )+ );+ }+ return { success: true, id: add.data.id };+ }++ const validation = await validator(changeOrderAffectedItemValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { changeOrderId, itemId, changeType, revision } = validation.data;++ const add = await addChangeOrderAffectedItem(client, {+ changeOrderId,+ itemId,+ changeType,+ // Only a Revision change consumes an explicit revision label.+ revision: changeType === "Revision" ? revision : undefined,+ companyId,+ userId+ });++ if (add.error || !add.data) {+ return data(+ { success: false },+ await flash(+ request,+ error(add.error, add.error?.message ?? "Failed to add affected item")+ )+ );+ }++ return { success: true, id: add.data.id };+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.details.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.details.tsxnew file mode 100644index 0000000000..80228743e9--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.details.tsx@@ -0,0 +1,66 @@+import type { JSONContent } from "@carbon/react";+import { VStack } from "@carbon/react";+import { useParams } from "react-router";+import { useRouteData } from "~/hooks";+import type { ChangeOrder, ChangeOrderActionTask } from "~/modules/items";+import { canEditChangeOrder } from "~/modules/items";+import type { AffectedItemDraft } from "~/modules/items/ui/ChangeOrder";+import {+ ChangeOrderActions,+ ChangeOrderChanges,+ ChangeOrderContent+} from "~/modules/items/ui/ChangeOrder";+import ChangeOrderStatusFlow from "~/modules/items/ui/ChangeOrder/ChangeOrderStatusFlow";+import { path } from "~/utils/path";++// Top-level change-order detail (the CO overview) — mirrors the sales order+// `$orderId.details` and the quality issue `$id.details`: the CO-wide state flow,+// the two rich-text narrative fields (reason for change + description, edited the+// same way as the issue's description), the total changes rollup (every affected+// item's authoring diff), and the action tasks (with the shared "Add Actions"+// picker). Affected items live in their own line routes (`$id.$affectedId.details`),+// linked from the explorer.+export default function ChangeOrderDetailsRoute() {+ const { id } = useParams();+ if (!id) throw new Error("Could not find id");++ const routeData = useRouteData<{+ changeOrder: ChangeOrder;+ actions: ChangeOrderActionTask[];+ affectedItems: AffectedItemDraft[];+ }>(path.to.changeOrder(id));+ const changeOrder = routeData?.changeOrder;++ if (!changeOrder) throw new Error("Could not find change order data");++ const isDisabled = !canEditChangeOrder(changeOrder.status);++ // Same shape the release dialog reviews (label + per-item diff), plus the+ // change type + draft version for the badge in the Changes rollup.+ const changes = (routeData?.affectedItems ?? []).map((a) => ({+ id: a.affectedItem.id,+ label: a.affectedItem.item?.readableIdWithRevision ?? a.affectedItem.itemId,+ name: a.affectedItem.item?.name ?? null,+ changeType: a.affectedItem.changeType,+ version: a.makeMethod?.version,+ diff: a.diff+ }));++ return (+ <VStack spacing={2} className="p-2">+ <ChangeOrderStatusFlow status={changeOrder.status} />+ <ChangeOrderChanges changes={changes} />+ <ChangeOrderContent+ id={id}+ reasonForChange={changeOrder.reasonForChange as JSONContent}+ description={changeOrder.description as JSONContent}+ isDisabled={isDisabled}+ />+ <ChangeOrderActions+ changeOrderId={id}+ actions={routeData?.actions ?? []}+ isDisabled={isDisabled}+ />+ </VStack>+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.status.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.status.tsxnew file mode 100644index 0000000000..56503ecfb9--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.status.tsx@@ -0,0 +1,96 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import type { ActionFunctionArgs } from "react-router";+import { redirect } from "react-router";+import {+ changeOrderBroadcastStages,+ changeOrderStatusValidator,+ updateChangeOrderStatus+} from "~/modules/items";+import {+ applyChangeOrder,+ changeOrderStageEvent,+ notifyChangeOrderTransition+} from "~/modules/items/items.server";+import { getDatabaseClient } from "~/services/database.server";+import { path, requestReferrer } from "~/utils/path";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId, companyId, companyGroupId } =+ await requirePermissions(request, {+ update: "parts"+ });++ const { id } = params;+ if (!id) throw new Error("Could not find id");++ const formData = await request.formData();+ const validation = await validator(changeOrderStatusValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { fromStatus, status: toStatus, assignee } = validation.data;++ // Implementation → Done IS the apply: applyChangeOrder activates each affected+ // item's CO-owned Draft make method and performs the final CAS flip to Done+ // (G1/G2). All other transitions go through the plain guarded status writer.+ if (toStatus === "Done") {+ const applied = await applyChangeOrder(client, getDatabaseClient(), {+ changeOrderId: id,+ userId,+ companyId+ });+ if (applied.error || !applied.data) {+ throw redirect(+ requestReferrer(request) ?? path.to.changeOrderDetails(id),+ await flash(+ request,+ error(applied.error, "Failed to apply change order")+ )+ );+ }+ } else {+ const update = await updateChangeOrderStatus(client, {+ id,+ companyId,+ fromStatus,+ toStatus,+ assignee,+ updatedBy: userId+ });++ if (update.error || !update.data) {+ throw redirect(+ requestReferrer(request) ?? path.to.changeOrderDetails(id),+ await flash(+ request,+ error(update.error, "Failed to update change order status")+ )+ );+ }+ }++ // Broadcast to the company team only on the stages that broadcast on entry+ // (Start / Implementation / Done). Best-effort; never blocks the redirect.+ if (changeOrderBroadcastStages.includes(toStatus)) {+ await notifyChangeOrderTransition({+ event: changeOrderStageEvent[toStatus],+ changeOrderId: id,+ companyId,+ companyGroupId,+ userId+ });+ }++ throw redirect(+ requestReferrer(request) ?? path.to.changeOrderDetails(id),+ await flash(request, success("Updated change order status"))+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.tsxnew file mode 100644index 0000000000..f645f5218d--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.tsx@@ -0,0 +1,318 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { JSONContent } from "@carbon/react";+import { msg } from "@lingui/core/macro";+import type { LoaderFunctionArgs } from "react-router";+import { Outlet, redirect, useLoaderData, useParams } from "react-router";+import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";+import {+ getChangeOrder,+ getChangeOrderActions,+ getChangeOrderAffectedItems,+ getChangeOrderDiff,+ getChangeOrderRequiredActionsList,+ getChangeOrderTypesList,+ getConfigurationParameters,+ getConfigurationRules,+ getItemFiles,+ getItemManufacturing,+ getMakeMethodById,+ getMakeMethods,+ getMethodMaterialsByMakeMethod,+ getMethodOperationsByMakeMethodId,+ getPart,+ getPartUsedIn,+ getPickMethods,+ getSupplierParts+} from "~/modules/items";+import { getRevisionLock } from "~/modules/items/items.server";+import type { AffectedItemDraft } from "~/modules/items/ui/ChangeOrder";+import {+ ChangeOrderExplorer,+ ChangeOrderHeader,+ ChangeOrderProperties+} from "~/modules/items/ui/ChangeOrder";+import { getIssue, getIssues } from "~/modules/quality";+import { getLocationsList } from "~/modules/resources";+import type { MethodItemType, MethodType } from "~/modules/shared";+import { getTagsList } from "~/modules/shared";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const handle: Handle = {+ // Leaf crumb: show the CO's readable number (from loader data), not a second+ // static "Change Orders" (the parent _layout already renders the list crumb).+ breadcrumb: (+ _params: unknown,+ data?: { changeOrder?: { changeOrderId?: string } }+ ) => data?.changeOrder?.changeOrderId ?? msg`Change Order`,+ module: "parts",+ // The CO detail workspace has its own left affected-items sidebar — hide the+ // Items module sidebar here so two left sidebars don't stack.+ hideModuleSidebar: true+};++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "parts"+ });++ const { id } = params;+ if (!id) throw new Error("Could not find id");++ const [changeOrder, types, affected, diff, actions, nonConformances] =+ await Promise.all([+ getChangeOrder(client, id, companyId),+ getChangeOrderTypesList(client, companyId),+ getChangeOrderAffectedItems(client, id, companyId),+ getChangeOrderDiff(client, id, companyId),+ getChangeOrderActions(client, id, companyId),+ // NCR cross-link picker options (4a).+ getIssues(client, companyId)+ ]);++ // Company locations feed the embedded PartProperties pick-method editor.+ const locations = (await getLocationsList(client, companyId)).data ?? [];++ // Active default-action templates for the "Add Actions" picker.+ const requiredActions =+ (await getChangeOrderRequiredActionsList(client, companyId)).data ?? [];++ if (changeOrder.error) {+ throw redirect(+ path.to.changeOrders,+ await flash(+ request,+ error(changeOrder.error, "Failed to load change order")+ )+ );+ }++ // Human label for the currently-linked NCR (so the sidebar link shows the+ // readable id/name, not the raw id).+ const linkedNonConformanceId = changeOrder.data?.nonConformanceId ?? null;+ const linkedNonConformance = linkedNonConformanceId+ ? (await getIssue(client, linkedNonConformanceId)).data+ : null;++ const affectedRows = affected.data ?? [];++ // Impact = where each affected item is used across the system (jobs, POs,+ // sales, receipts, methods, NCRs, …) — the same "Used In" data the part detail+ // page loads, one entry per affected item.+ const impactUsedIn = await Promise.all(+ affectedRows.map(async (a) => ({+ itemId: a.itemId,+ readableIdWithRevision: a.item?.readableIdWithRevision ?? a.itemId,+ itemName: a.item?.name ?? null,+ usedIn: await getPartUsedIn(client, a.itemId, companyId)+ }))+ );++ const diffByAffectedId = new Map(+ (diff.data?.items ?? []).map((entry) => [entry.affectedItemId, entry])+ );++ // Per affected item: load its CO-owned Draft make method's real rows shaped+ // exactly as the embedded BillOfMaterial / BillOfProcess editors expect (same+ // assembly as x+/part+/$itemId.make.$makeMethodId). The draft lives on the+ // same item for a Version, or on the new item (newItemId) for Revision/New Part.+ const affectedItems: AffectedItemDraft[] = await Promise.all(+ affectedRows.map(async (affectedItem) => {+ const draftItemId = affectedItem.newItemId ?? affectedItem.itemId;+ const draftMakeMethodId = affectedItem.draftMakeMethodId;++ if (!draftMakeMethodId) {+ return {+ affectedItem,+ draftItemId,+ makeMethod: null,+ methodMaterials: [],+ methodOperations: [],+ tags: [],+ configurable: false,+ configurationRules: [],+ parameters: [],+ revisionStatus: null,+ releaseControl: null,+ partData: null,+ diff: diffByAffectedId.get(affectedItem.id)+ };+ }++ // Revision / Replacement Part / New Part edit the item's attributes + files+ // on the draft item — load the same bundle the part detail route feeds+ // PartProperties, embedded on the CO card. Parts only (Tool attribute+ // editing is a follow-up); Version has no attribute editing (Q2 matrix).+ const needsAttributes =+ (affectedItem.changeType === "Revision" ||+ affectedItem.changeType === "Replacement Part" ||+ affectedItem.changeType === "New Part") &&+ affectedItem.item?.type === "Part";+ let partData = null;+ if (needsAttributes) {+ const [partSummary, supplierParts, pickMethods, partTags] =+ await Promise.all([+ getPart(client, draftItemId, companyId),+ getSupplierParts(client, draftItemId, companyId),+ getPickMethods(client, draftItemId, companyId),+ getTagsList(client, companyId, "part")+ ]);+ if (partSummary.data) {+ partData = {+ itemId: draftItemId,+ locations,+ partSummary: partSummary.data,+ files: getItemFiles(client, draftItemId, companyId),+ supplierParts: supplierParts.data ?? [],+ pickMethods: pickMethods.data ?? [],+ makeMethods: getMakeMethods(client, draftItemId, companyId),+ tags: partTags.data ?? []+ };+ }+ }++ const [+ makeMethod,+ methodMaterials,+ methodOperations,+ tags,+ manufacturing,+ revisionLock+ ] = await Promise.all([+ getMakeMethodById(client, draftMakeMethodId, companyId),+ getMethodMaterialsByMakeMethod(client, draftMakeMethodId),+ getMethodOperationsByMakeMethodId(client, draftMakeMethodId),+ getTagsList(client, companyId, "operation"),+ getItemManufacturing(client, draftItemId, companyId),+ getRevisionLock(client, { itemId: draftItemId, companyId })+ ]);++ const config = manufacturing.data?.requiresConfiguration+ ? {+ parameters: (+ await getConfigurationParameters(client, draftItemId, companyId)+ ).parameters,+ configurationRules: await getConfigurationRules(+ client,+ draftItemId,+ companyId+ )+ }+ : {+ parameters: [] as Awaited<+ ReturnType<typeof getConfigurationParameters>+ >["parameters"],+ configurationRules: [] as Awaited<+ ReturnType<typeof getConfigurationRules>+ >+ };++ return {+ affectedItem,+ draftItemId,+ makeMethod: makeMethod.data ?? null,+ methodMaterials:+ methodMaterials.data?.map((m) => ({+ ...m,+ description: m.item?.name ?? "",+ methodOperationId: m.methodOperationId ?? undefined,+ methodType: m.methodType as MethodType,+ itemType: m.itemType as MethodItemType+ })) ?? [],+ methodOperations:+ methodOperations.data?.map((operation) => ({+ ...operation,+ description: operation.description ?? "",+ procedureId: operation.procedureId ?? undefined,+ operationSupplierProcessId:+ operation.operationSupplierProcessId ?? undefined,+ operationMinimumCost: operation.operationMinimumCost ?? 0,+ operationLeadTime: operation.operationLeadTime ?? 0,+ operationUnitCost: operation.operationUnitCost ?? 0,+ tags: operation.tags ?? [],+ workCenterId: operation.workCenterId ?? undefined,+ workInstruction: operation.workInstruction as JSONContent | null+ })) ?? [],+ tags: tags.data ?? [],+ configurable: manufacturing.data?.requiresConfiguration ?? false,+ configurationRules: config.configurationRules,+ parameters: config.parameters,+ revisionStatus: revisionLock.revisionStatus,+ releaseControl: revisionLock.releaseControl,+ partData,+ diff: diffByAffectedId.get(affectedItem.id)+ };+ })+ );++ // Minimal, explicit option shape (cheap type — avoids widening the loader's+ // instantiation surface with the full issues-view row).+ const nonConformanceOptions: {+ id: string;+ nonConformanceId: string;+ name: string;+ }[] = (nonConformances.data ?? []).flatMap((nc) =>+ nc.id && nc.nonConformanceId+ ? [+ {+ id: nc.id,+ nonConformanceId: nc.nonConformanceId,+ name: nc.name ?? ""+ }+ ]+ : []+ );++ return {+ changeOrder: changeOrder.data,+ types: types.data ?? [],+ affectedItems,+ diff: diff.data ?? { items: [] },+ actions: actions.data ?? [],+ requiredActions,+ impactUsedIn,+ nonConformanceOptions,+ linkedNonConformance: linkedNonConformance+ ? {+ id: linkedNonConformance.id,+ nonConformanceId: linkedNonConformance.nonConformanceId,+ name: linkedNonConformance.name+ }+ : null+ };+}++export default function ChangeOrderIdRoute() {+ const { id } = useParams();+ if (!id) throw new Error("Could not find id");+ // Surfaced to child routes + header/explorer/properties via useRouteData.+ useLoaderData<typeof loader>();++ return (+ // Standard 3-pane detail workspace (matches sales-order / job): the explorer+ // is the affected-items list, the content is the selected affected item's+ // detail (the $id.details Outlet, with the CO-wide stage flow + actions on+ // top), and the properties panel holds the CO-centric fields, details,+ // actions, impact, and the release dialog.+ <PanelProvider>+ <div className="flex flex-col h-[calc(100dvh-49px)] overflow-hidden w-full">+ <ChangeOrderHeader />+ <div className="flex h-[calc(100dvh-99px)] overflow-hidden w-full">+ <div className="flex flex-grow overflow-hidden">+ <ResizablePanels+ explorer={<ChangeOrderExplorer />}+ content={+ <div className="h-[calc(100dvh-99px)] overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent w-full">+ <Outlet />+ </div>+ }+ properties={<ChangeOrderProperties key={id} />}+ />+ </div>+ </div>+ </div>+ </PanelProvider>+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/_layout.tsx b/apps/erp/app/routes/x+/items+/change-order+/_layout.tsxnew file mode 100644index 0000000000..26deeae586--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/_layout.tsx@@ -0,0 +1,19 @@+import { msg } from "@lingui/core/macro";+import type { MetaFunction } from "react-router";+import { Outlet } from "react-router";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const meta: MetaFunction = () => {+ return [{ title: "Carbon | Change Order" }];+};++export const handle: Handle = {+ breadcrumb: msg`Change Orders`,+ to: path.to.changeOrders,+ module: "items"+};++export default function ChangeOrderRoute() {+ return <Outlet />;+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/delete.$id.tsx b/apps/erp/app/routes/x+/items+/change-order+/delete.$id.tsxnew file mode 100644index 0000000000..4c1333215c--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/delete.$id.tsx@@ -0,0 +1,32 @@+import { error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs } from "react-router";+import { data, redirect } from "react-router";+import { deleteChangeOrder } from "~/modules/items";+import { path } from "~/utils/path";++export async function action({ request, params }: ActionFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ delete: "parts"+ });++ const { id } = params;+ if (!id) throw new Error("id is not found");++ const mutation = await deleteChangeOrder(client, id, companyId);+ if (mutation.error) {+ return data(+ { success: false },+ await flash(+ request,+ error(mutation.error, "Failed to delete change order")+ )+ );+ }++ throw redirect(+ path.to.changeOrders,+ await flash(request, success("Successfully deleted change order"))+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/new-from-item.$itemId.tsx b/apps/erp/app/routes/x+/items+/change-order+/new-from-item.$itemId.tsxnew file mode 100644index 0000000000..4b1ff14660--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/new-from-item.$itemId.tsx@@ -0,0 +1,91 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { getLocalTimeZone, today } from "@internationalized/date";+import type { ActionFunctionArgs } from "react-router";+import { redirect } from "react-router";+import {+ addChangeOrderAffectedItem,+ type ChangeOrderChangeType,+ changeOrderChangeTypes,+ getItem,+ insertChangeOrder+} from "~/modules/items";+import { path, requestReferrer } from "~/utils/path";++// One-click "Create Change Order" for a part/tool: mint a CO and attach the item+// as its first affected item, then open the CO. Change-order creation lives only+// here (and new.tsx) — this route is the single home for the create+attach flow,+// so no CO logic leaks into the revision/part routes that link to it.+//+// The optional `changeType` + `revision` POST fields let callers request a+// specific kind of change (the new-revision modal posts `Revision` plus the+// typed revision label); with no body it defaults to a `Version` change (the+// parts-table "Create Change Order" action).+export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "parts"+ });++ const { itemId } = params;+ if (!itemId) throw new Error("itemId not found");++ const formData = await request.formData();+ const changeTypeRaw = formData.get("changeType");+ const changeType: ChangeOrderChangeType = changeOrderChangeTypes.includes(+ changeTypeRaw as ChangeOrderChangeType+ )+ ? (changeTypeRaw as ChangeOrderChangeType)+ : "Version";+ const revisionRaw = formData.get("revision");+ const revision =+ typeof revisionRaw === "string" && revisionRaw.trim()+ ? revisionRaw.trim()+ : undefined;++ const backTo = requestReferrer(request) ?? path.to.changeOrders;++ const item = await getItem(client, itemId);+ const label =+ item.data?.readableIdWithRevision ?? item.data?.readableId ?? itemId;++ const co = await insertChangeOrder(client, {+ companyId,+ createdBy: userId,+ name: `Change for ${label}`,+ openDate: today(getLocalTimeZone()).toString()+ });+ if (co.error || !co.data) {+ throw redirect(+ backTo,+ await flash(request, error(co.error, "Failed to create change order"))+ );+ }++ const add = await addChangeOrderAffectedItem(client, {+ changeOrderId: co.data.id,+ itemId,+ changeType,+ revision,+ companyId,+ userId+ });+ if (add.error) {+ throw redirect(+ path.to.changeOrder(co.data.id),+ await flash(+ request,+ error(+ add.error,+ "Change order created, but the item could not be added"+ )+ )+ );+ }++ throw redirect(+ path.to.changeOrder(co.data.id),+ await flash(request, success("Change order created"))+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-order+/update.tsx b/apps/erp/app/routes/x+/items+/change-order+/update.tsxnew file mode 100644index 0000000000..5d47369ba0--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order+/update.tsx@@ -0,0 +1,69 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import type { ActionFunctionArgs } from "react-router";+import { isChangeOrderLocked, updateChangeOrder } from "~/modules/items";++// Inline field editor used by ChangeOrderProperties (and future inline editors).+// The fetcher posts { id, field, value }; only a curated set of header fields is+// writable here. Rich-text (reasonForChange/description) is written directly by+// ChangeOrderContent via the supabase client, so it is not handled here.+const EDITABLE_FIELDS = [+ "name",+ "changeOrderTypeId",+ "assignee",+ "priority",+ "openDate",+ "dueDate",+ "nonConformanceId"+] as const;++type EditableField = (typeof EDITABLE_FIELDS)[number];++export async function action({ request }: ActionFunctionArgs) {+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "parts"+ });++ const formData = await request.formData();+ const id = formData.get("id");+ const field = formData.get("field");+ const value = formData.get("value");++ if (typeof id !== "string" || !id) {+ return { error: { message: "Invalid change order id" }, data: null };+ }+ if (+ typeof field !== "string" ||+ !EDITABLE_FIELDS.includes(field as EditableField)+ ) {+ return { error: { message: `Invalid field: ${field}` }, data: null };+ }++ // Locked guard — Done change orders are read-only.+ const existing = await client+ .from("changeOrder")+ .select("status")+ .eq("id", id)+ .eq("companyId", companyId)+ .single();++ if (isChangeOrderLocked(existing.data?.status)) {+ return {+ error: { message: "Cannot modify a completed change order." },+ data: null+ };+ }++ const normalized = typeof value === "string" && value !== "" ? value : null;++ const result = await updateChangeOrder(client, {+ id,+ [field]: normalized,+ updatedBy: userId+ });++ if (result.error) {+ return { error: { message: "Failed to update change order" }, data: null };+ }++ return { error: null, data: result.data };+}diff --git a/apps/erp/app/routes/x+/items+/change-order-actions.$id.tsx b/apps/erp/app/routes/x+/items+/change-order-actions.$id.tsxnew file mode 100644index 0000000000..55b3a8804d--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order-actions.$id.tsx@@ -0,0 +1,100 @@+import { assertIsPost, error, notFound, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data, redirect, useLoaderData, useNavigate } from "react-router";+import {+ changeOrderRequiredActionValidator,+ getChangeOrderRequiredAction,+ upsertChangeOrderRequiredAction+} from "~/modules/items";+import { ChangeOrderRequiredActionForm } from "~/modules/items/ui/ChangeOrderActions";+import { path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ role: "employee"+ });++ const { id } = params;+ if (!id) throw notFound("id not found");++ const requiredAction = await getChangeOrderRequiredAction(client, id);++ if (requiredAction.error) {+ throw redirect(+ path.to.changeOrderRequiredActions,+ await flash(+ request,+ error(requiredAction.error, "Failed to get change order action")+ )+ );+ }++ return {+ requiredAction: requiredAction.data+ };+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "parts"+ });++ const formData = await request.formData();+ const validation = await validator(+ changeOrderRequiredActionValidator+ ).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...d } = validation.data;+ if (!id) throw new Error("id not found");++ const update = await upsertChangeOrderRequiredAction(client, {+ id,+ name: d.name,+ active: d.active,+ companyId,+ userId+ });++ if (update.error) {+ return data(+ {},+ await flash(+ request,+ error(update.error, "Failed to update change order action")+ )+ );+ }++ throw redirect(+ path.to.changeOrderRequiredActions,+ await flash(request, success("Updated change order action"))+ );+}++export default function EditChangeOrderRequiredActionRoute() {+ const { requiredAction } = useLoaderData<typeof loader>();+ const navigate = useNavigate();++ const initialValues = {+ id: requiredAction.id ?? undefined,+ name: requiredAction.name ?? "",+ active: requiredAction.active ?? true+ };++ return (+ <ChangeOrderRequiredActionForm+ key={initialValues.id}+ initialValues={initialValues}+ onClose={() => navigate(-1)}+ />+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-order-actions.delete.$id.tsx b/apps/erp/app/routes/x+/items+/change-order-actions.delete.$id.tsxnew file mode 100644index 0000000000..63004ac8be--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order-actions.delete.$id.tsx@@ -0,0 +1,90 @@+import { error, notFound, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { useLingui } from "@lingui/react/macro";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { redirect, useLoaderData, useNavigate, useParams } from "react-router";+import { ConfirmDelete } from "~/components/Modals";+import {+ deleteChangeOrderRequiredAction,+ getChangeOrderRequiredAction+} from "~/modules/items";+import { getParams, path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ role: "employee"+ });+ const { id } = params;+ if (!id) throw notFound("id not found");++ const requiredAction = await getChangeOrderRequiredAction(client, id);+ if (requiredAction.error) {+ throw redirect(+ `${path.to.changeOrderRequiredActions}?${getParams(request)}`,+ await flash(+ request,+ error(requiredAction.error, "Failed to get change order action")+ )+ );+ }++ return { requiredAction: requiredAction.data };+}++export async function action({ request, params }: ActionFunctionArgs) {+ const { client } = await requirePermissions(request, {+ delete: "parts"+ });++ const { id } = params;+ if (!id) {+ throw redirect(+ `${path.to.changeOrderRequiredActions}?${getParams(request)}`,+ await flash(+ request,+ error(params, "Failed to get a change order action id")+ )+ );+ }++ const { error: deleteError } = await deleteChangeOrderRequiredAction(+ client,+ id+ );+ if (deleteError) {+ throw redirect(+ `${path.to.changeOrderRequiredActions}?${getParams(request)}`,+ await flash(+ request,+ error(deleteError, "Failed to delete change order action")+ )+ );+ }++ throw redirect(+ `${path.to.changeOrderRequiredActions}?${getParams(request)}`,+ await flash(request, success("Successfully deleted change order action"))+ );+}++export default function DeleteChangeOrderRequiredActionRoute() {+ const { id } = useParams();+ const { requiredAction } = useLoaderData<typeof loader>();+ const navigate = useNavigate();+ const { t } = useLingui();++ if (!requiredAction) return null;+ if (!id) throw notFound("id not found");++ const onCancel = () => navigate(path.to.changeOrderRequiredActions);+ return (+ <ConfirmDelete+ action={path.to.deleteChangeOrderRequiredAction(id)}+ name={requiredAction.name}+ text={t`Are you sure you want to delete the change order action: ${requiredAction.name}? This cannot be undone.`}+ onCancel={onCancel}+ />+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-order-actions.new.tsx b/apps/erp/app/routes/x+/items+/change-order-actions.new.tsxnew file mode 100644index 0000000000..23dfbed321--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order-actions.new.tsx@@ -0,0 +1,79 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { redirect, useNavigate } from "react-router";+import {+ changeOrderRequiredActionValidator,+ upsertChangeOrderRequiredAction+} from "~/modules/items";+import { ChangeOrderRequiredActionForm } from "~/modules/items/ui/ChangeOrderActions";+import { getParams, path, requestReferrer } from "~/utils/path";++export async function loader({ request }: LoaderFunctionArgs) {+ await requirePermissions(request, {+ create: "parts"+ });++ return null;+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "parts"+ });++ const formData = await request.formData();+ const modal = formData.get("type") === "modal";++ const validation = await validator(+ changeOrderRequiredActionValidator+ ).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const insert = await upsertChangeOrderRequiredAction(client, {+ name: validation.data.name,+ active: validation.data.active,+ companyId,+ userId+ });+ if (insert.error) {+ return modal+ ? insert+ : redirect(+ requestReferrer(request) ??+ `${path.to.changeOrderRequiredActions}?${getParams(request)}`,+ await flash(+ request,+ error(insert.error, "Failed to insert change order action")+ )+ );+ }++ return modal+ ? insert+ : redirect(+ `${path.to.changeOrderRequiredActions}?${getParams(request)}`,+ await flash(request, success("Change order action created"))+ );+}++export default function NewChangeOrderRequiredActionRoute() {+ const navigate = useNavigate();+ const initialValues = {+ name: "",+ active: true+ };++ return (+ <ChangeOrderRequiredActionForm+ initialValues={initialValues}+ onClose={() => navigate(-1)}+ />+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-order-actions.tsx b/apps/erp/app/routes/x+/items+/change-order-actions.tsxnew file mode 100644index 0000000000..1215cdb10d--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order-actions.tsx@@ -0,0 +1,47 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import { VStack } from "@carbon/react";+import { msg } from "@lingui/core/macro";+import type { LoaderFunctionArgs } from "react-router";+import { Outlet, useLoaderData } from "react-router";+import { getChangeOrderRequiredActions } from "~/modules/items";+import { ChangeOrderRequiredActionsTable } from "~/modules/items/ui/ChangeOrderActions";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";+import { getGenericQueryFilters } from "~/utils/query";++export const handle: Handle = {+ breadcrumb: msg`Change Order Actions`,+ to: path.to.changeOrderRequiredActions+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "parts",+ role: "employee"+ });++ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const search = searchParams.get("search");+ const { limit, offset, sorts, filters } =+ getGenericQueryFilters(searchParams);++ return await getChangeOrderRequiredActions(client, companyId, {+ search,+ limit,+ offset,+ sorts,+ filters+ });+}++export default function ChangeOrderActionsRoute() {+ const { data, count } = useLoaderData<typeof loader>();++ return (+ <VStack spacing={0} className="h-full">+ <ChangeOrderRequiredActionsTable data={data ?? []} count={count ?? 0} />+ <Outlet />+ </VStack>+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-order-types.$id.tsx b/apps/erp/app/routes/x+/items+/change-order-types.$id.tsxnew file mode 100644index 0000000000..ee9a257e28--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order-types.$id.tsx@@ -0,0 +1,97 @@+import { assertIsPost, error, notFound, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data, redirect, useLoaderData, useNavigate } from "react-router";+import {+ changeOrderTypeValidator,+ getChangeOrderType,+ upsertChangeOrderType+} from "~/modules/items";+import { ChangeOrderTypeForm } from "~/modules/items/ui/ChangeOrderTypes";+import { path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ role: "employee"+ });++ const { id } = params;+ if (!id) throw notFound("id not found");++ const changeOrderType = await getChangeOrderType(client, id);++ if (changeOrderType.error) {+ throw redirect(+ path.to.changeOrderTypes,+ await flash(+ request,+ error(changeOrderType.error, "Failed to get change order category")+ )+ );+ }++ return {+ changeOrderType: changeOrderType.data+ };+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "parts"+ });++ const formData = await request.formData();+ const validation = await validator(changeOrderTypeValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...d } = validation.data;+ if (!id) throw new Error("id not found");++ const update = await upsertChangeOrderType(client, {+ id,+ ...d,+ updatedBy: userId+ });++ if (update.error) {+ return data(+ {},+ await flash(+ request,+ error(update.error, "Failed to update change order category")+ )+ );+ }++ throw redirect(+ path.to.changeOrderTypes,+ await flash(request, success("Updated change order category"))+ );+}++export default function EditChangeOrderTypeRoute() {+ const { changeOrderType } = useLoaderData<typeof loader>();+ const navigate = useNavigate();++ const initialValues = {+ id: changeOrderType.id ?? undefined,+ name: changeOrderType.name ?? ""+ };++ return (+ <ChangeOrderTypeForm+ key={initialValues.id}+ initialValues={initialValues}+ onClose={() => navigate(-1)}+ />+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-order-types.delete.$id.tsx b/apps/erp/app/routes/x+/items+/change-order-types.delete.$id.tsxnew file mode 100644index 0000000000..d99a417a1c--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order-types.delete.$id.tsx@@ -0,0 +1,86 @@+import { error, notFound, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { useLingui } from "@lingui/react/macro";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { redirect, useLoaderData, useNavigate, useParams } from "react-router";+import { ConfirmDelete } from "~/components/Modals";+import { deleteChangeOrderType, getChangeOrderType } from "~/modules/items";+import { getParams, path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ role: "employee"+ });+ const { id } = params;+ if (!id) throw notFound("id not found");++ const changeOrderType = await getChangeOrderType(client, id);+ if (changeOrderType.error) {+ throw redirect(+ `${path.to.changeOrderTypes}?${getParams(request)}`,+ await flash(+ request,+ error(changeOrderType.error, "Failed to get change order category")+ )+ );+ }++ return { changeOrderType: changeOrderType.data };+}++export async function action({ request, params }: ActionFunctionArgs) {+ const { client } = await requirePermissions(request, {+ delete: "parts"+ });++ const { id } = params;+ if (!id) {+ throw redirect(+ `${path.to.changeOrderTypes}?${getParams(request)}`,+ await flash(+ request,+ error(params, "Failed to get a change order category id")+ )+ );+ }++ const { error: deleteError } = await deleteChangeOrderType(client, id);+ if (deleteError) {+ const errorMessage =+ deleteError.code === "23503"+ ? "Change order category is used elsewhere, cannot delete"+ : "Failed to delete change order category";++ throw redirect(+ `${path.to.changeOrderTypes}?${getParams(request)}`,+ await flash(request, error(deleteError, errorMessage))+ );+ }++ throw redirect(+ `${path.to.changeOrderTypes}?${getParams(request)}`,+ await flash(request, success("Successfully deleted change order category"))+ );+}++export default function DeleteChangeOrderTypeRoute() {+ const { id } = useParams();+ const { changeOrderType } = useLoaderData<typeof loader>();+ const navigate = useNavigate();+ const { t } = useLingui();++ if (!changeOrderType) return null;+ if (!id) throw notFound("id not found");++ const onCancel = () => navigate(path.to.changeOrderTypes);+ return (+ <ConfirmDelete+ action={path.to.deleteChangeOrderType(id)}+ name={changeOrderType.name}+ text={t`Are you sure you want to delete the change order category: ${changeOrderType.name}? This cannot be undone.`}+ onCancel={onCancel}+ />+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-order-types.new.tsx b/apps/erp/app/routes/x+/items+/change-order-types.new.tsxnew file mode 100644index 0000000000..507acffa4e--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order-types.new.tsx@@ -0,0 +1,77 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { redirect, useNavigate } from "react-router";+import {+ changeOrderTypeValidator,+ upsertChangeOrderType+} from "~/modules/items";+import { ChangeOrderTypeForm } from "~/modules/items/ui/ChangeOrderTypes";+import { getParams, path, requestReferrer } from "~/utils/path";++export async function loader({ request }: LoaderFunctionArgs) {+ await requirePermissions(request, {+ create: "parts"+ });++ return null;+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "parts"+ });++ const formData = await request.formData();+ const modal = formData.get("type") === "modal";++ const validation = await validator(changeOrderTypeValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const insert = await upsertChangeOrderType(client, {+ name: validation.data.name,+ companyId,+ createdBy: userId+ });+ if (insert.error) {+ return modal+ ? insert+ : redirect(+ requestReferrer(request) ??+ `${path.to.changeOrderTypes}?${getParams(request)}`,+ await flash(+ request,+ error(insert.error, "Failed to insert change order category")+ )+ );+ }++ return modal+ ? insert+ : redirect(+ `${path.to.changeOrderTypes}?${getParams(request)}`,+ await flash(request, success("Change order category created"))+ );+}++export default function NewChangeOrderTypeRoute() {+ const navigate = useNavigate();+ const initialValues = {+ name: ""+ };++ return (+ <ChangeOrderTypeForm+ initialValues={initialValues}+ onClose={() => navigate(-1)}+ />+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-order-types.tsx b/apps/erp/app/routes/x+/items+/change-order-types.tsxnew file mode 100644index 0000000000..4bf121fa70--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-order-types.tsx@@ -0,0 +1,47 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import { VStack } from "@carbon/react";+import { msg } from "@lingui/core/macro";+import type { LoaderFunctionArgs } from "react-router";+import { Outlet, useLoaderData } from "react-router";+import { getChangeOrderTypes } from "~/modules/items";+import { ChangeOrderTypesTable } from "~/modules/items/ui/ChangeOrderTypes";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";+import { getGenericQueryFilters } from "~/utils/query";++export const handle: Handle = {+ breadcrumb: msg`Change Order Types`,+ to: path.to.changeOrderTypes+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "parts",+ role: "employee"+ });++ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const search = searchParams.get("search");+ const { limit, offset, sorts, filters } =+ getGenericQueryFilters(searchParams);++ return await getChangeOrderTypes(client, companyId, {+ search,+ limit,+ offset,+ sorts,+ filters+ });+}++export default function ChangeOrderTypesRoute() {+ const { data, count } = useLoaderData<typeof loader>();++ return (+ <VStack spacing={0} className="h-full">+ <ChangeOrderTypesTable data={data ?? []} count={count ?? 0} />+ <Outlet />+ </VStack>+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-orders+/_index.tsx b/apps/erp/app/routes/x+/items+/change-orders+/_index.tsxnew file mode 100644index 0000000000..f5c720c7b1--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-orders+/_index.tsx@@ -0,0 +1,61 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { VStack } from "@carbon/react";+import type { LoaderFunctionArgs } from "react-router";+import { Outlet, redirect, useLoaderData } from "react-router";+import { getChangeOrders, getChangeOrderTypesList } from "~/modules/items";+import { ChangeOrdersTable } from "~/modules/items/ui/ChangeOrder";+import { path } from "~/utils/path";+import { getGenericQueryFilters } from "~/utils/query";++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "parts",+ role: "employee"+ });++ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const search = searchParams.get("search");+ const { limit, offset, sorts, filters } =+ getGenericQueryFilters(searchParams);++ const [changeOrders, types] = await Promise.all([+ getChangeOrders(client, companyId, {+ search,+ limit,+ offset,+ sorts,+ filters+ }),+ getChangeOrderTypesList(client, companyId)+ ]);++ if (changeOrders.error) {+ throw redirect(+ path.to.authenticatedRoot,+ await flash(+ request,+ error(changeOrders.error, "Error loading change orders")+ )+ );+ }++ return {+ changeOrders: changeOrders.data ?? [],+ count: changeOrders.count ?? 0,+ types: types.data ?? []+ };+}++export default function ChangeOrdersIndexRoute() {+ const { changeOrders, count, types } = useLoaderData<typeof loader>();++ return (+ <VStack spacing={0} className="h-full">+ <ChangeOrdersTable data={changeOrders} count={count} types={types} />+ <Outlet />+ </VStack>+ );+}diff --git a/apps/erp/app/routes/x+/items+/change-orders+/_layout.tsx b/apps/erp/app/routes/x+/items+/change-orders+/_layout.tsxnew file mode 100644index 0000000000..4a7ceff7a8--- /dev/null+++ b/apps/erp/app/routes/x+/items+/change-orders+/_layout.tsx@@ -0,0 +1,19 @@+import { msg } from "@lingui/core/macro";+import type { MetaFunction } from "react-router";+import { Outlet } from "react-router";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const meta: MetaFunction = () => {+ return [{ title: "Carbon | Change Orders" }];+};++export const handle: Handle = {+ breadcrumb: msg`Change Orders`,+ to: path.to.changeOrders,+ module: "items"+};++export default function ChangeOrdersRoute() {+ return <Outlet />;+}diff --git a/apps/erp/app/routes/x+/items+/methods+/get.tsx b/apps/erp/app/routes/x+/items+/methods+/get.tsxindex c62e4678a2..369332e1b4 100644--- a/apps/erp/app/routes/x+/items+/methods+/get.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/get.tsx@@ -1,9 +1,12 @@+import { success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { copyItem, copyMakeMethod, getMethodValidator } from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";import { path, requestReferrer } from "~/utils/path";export async function action({ request }: ActionFunctionArgs) {@@ -24,6 +27,17 @@ export async function action({ request }: ActionFunctionArgs) {// MakeMethodTools.tsx now sends makeMethod IDs directlyconst isMakeMethodId = (id: string) => id.startsWith("make_");+ // Release-lock gate: copyMakeMethod/copyItem OVERWRITE the target method's+ // materials + operations, so gate on the destination (target) item.+ const lock = await checkRevisionLock(serviceRole, {+ kind: isMakeMethodId(validation.data.targetId) ? "makeMethod" : "item",+ id: validation.data.targetId,+ companyId+ });+ if (!lock.ok) {+ return { error: lock.message };+ }+const upsert =isMakeMethodId(validation.data.sourceId) ||isMakeMethodId(validation.data.targetId)@@ -44,5 +58,8 @@ export async function action({ request }: ActionFunctionArgs) {};}- throw redirect(requestReferrer(request) ?? path.to.items);+ throw redirect(+ requestReferrer(request) ?? path.to.items,+ lock.warn ? await flash(request, success(lock.message)) : undefined+ );}diff --git a/apps/erp/app/routes/x+/items+/methods+/material.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/material.$id.tsxindex 8351aedf34..1a9c2549f5 100644--- a/apps/erp/app/routes/x+/items+/methods+/material.$id.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/material.$id.tsx@@ -1,10 +1,11 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { methodMaterialValidator, upsertMethodMaterial } from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";import { setCustomFields } from "~/utils/form";export async function action({ request, params }: ActionFunctionArgs) {@@ -27,6 +28,17 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}+ // Release-lock gate: block edits to a released (Production) revision unless a+ // change order is used. enforce -> block; warn -> proceed + flash; off -> no-op.+ const lock = await checkRevisionLock(client, {+ kind: "makeMethod",+ id: validation.data.makeMethodId,+ companyId+ });+ if (!lock.ok) {+ return data({ id: null }, await flash(request, error(null, lock.message)));+ }+const updateMethodMaterial = await upsertMethodMaterial(client, {...validation.data,id: id,@@ -59,9 +71,15 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- return {+ const result = {id: methodMaterialId,success: true,message: "Material updated"};++ if (lock.warn) {+ return data(result, await flash(request, success(lock.message)));+ }++ return result;}diff --git a/apps/erp/app/routes/x+/items+/methods+/material.delete.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/material.delete.$id.tsxindex 33e26c7921..6fcec72f82 100644--- a/apps/erp/app/routes/x+/items+/methods+/material.delete.$id.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/material.delete.$id.tsx@@ -1,13 +1,14 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { deleteMethodMaterial } from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client } = await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {delete: "parts"});@@ -16,6 +17,17 @@ export async function action({ request, params }: ActionFunctionArgs) {throw new Error("id not found");}+ // Release-lock gate: block edits to a released (Production) revision unless a+ // change order is used. enforce -> block; warn -> proceed + flash; off -> no-op.+ const lock = await checkRevisionLock(client, {+ kind: "material",+ id,+ companyId+ });+ if (!lock.ok) {+ return data({ id: null }, await flash(request, error(null, lock.message)));+ }+const deleteMaterial = await deleteMethodMaterial(client, id);if (deleteMaterial.error) {return data(@@ -29,5 +41,9 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ if (lock.warn) {+ return data({}, await flash(request, success(lock.message)));+ }+return {};}diff --git a/apps/erp/app/routes/x+/items+/methods+/material.new.tsx b/apps/erp/app/routes/x+/items+/methods+/material.new.tsxindex 095922b218..01f3629e80 100644--- a/apps/erp/app/routes/x+/items+/methods+/material.new.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/material.new.tsx@@ -1,10 +1,11 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { methodMaterialValidator, upsertMethodMaterial } from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";import { setCustomFields } from "~/utils/form";export async function action({ request, params }: ActionFunctionArgs) {@@ -22,6 +23,17 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}+ // Release-lock gate: block edits to a released (Production) revision unless a+ // change order is used. enforce -> block; warn -> proceed + flash; off -> no-op.+ const lock = await checkRevisionLock(client, {+ kind: "makeMethod",+ id: validation.data.makeMethodId,+ companyId+ });+ if (!lock.ok) {+ return data({ id: null }, await flash(request, error(null, lock.message)));+ }+const insertMethodMaterial = await upsertMethodMaterial(client, {...validation.data,companyId,@@ -54,9 +66,15 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- return {+ const result = {id: methodMaterialId,success: true,message: "Material created"};++ if (lock.warn) {+ return data(result, await flash(request, success(lock.message)));+ }++ return result;}diff --git a/apps/erp/app/routes/x+/items+/methods+/material.order.tsx b/apps/erp/app/routes/x+/items+/methods+/material.order.tsxindex 5f890a4a38..02bf89b659 100644--- a/apps/erp/app/routes/x+/items+/methods+/material.order.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/material.order.tsx@@ -1,13 +1,14 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { updateMaterialOrder } from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "parts"});@@ -27,6 +28,17 @@ export async function action({ request }: ActionFunctionArgs) {}));+ // Release-lock gate: block edits to a released (Production) revision unless a+ // change order is used. All materials in a reorder share one make method.+ const lock = await checkRevisionLock(client, {+ kind: "material",+ id: updates[0]?.id,+ companyId+ });+ if (!lock.ok) {+ return data({}, await flash(request, error(null, lock.message)));+ }+const updateSortOrders = await updateMaterialOrder(client, updates);if (updateSortOrders.some((update) => update.error))return data(@@ -37,5 +49,9 @@ export async function action({ request }: ActionFunctionArgs) {));+ if (lock.warn) {+ return data(null, await flash(request, success(lock.message)));+ }+return null;}diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.$id.tsxindex c037d06933..837cd43808 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.$id.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.$id.tsx@@ -1,4 +1,4 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";@@ -8,6 +8,7 @@ import {methodOperationValidator,upsertMethodOperation} from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";import { setCustomFields } from "~/utils/form";export async function action({ request, params }: ActionFunctionArgs) {@@ -30,6 +31,18 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}+ // Release-lock gate: enforce -> block; warn -> proceed + flash; off -> no-op.+ const lock = await checkRevisionLock(client, {+ kind: "makeMethod",+ id: validation.data.makeMethodId,+ companyId+ });+ if (!lock.ok) {+ return validationError({+ fieldErrors: { description: lock.message }+ });+ }+const updateMethodOperation = await upsertMethodOperation(client, {...validation.data,id: id,@@ -62,9 +75,15 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- return {+ const result = {id: methodOperationId,success: true,message: "Operation updated"};++ if (lock.warn) {+ return data(result, await flash(request, success(lock.message)));+ }++ return result;}diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.$operationId.step.order.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.$operationId.step.order.tsxindex 5831edde04..b727cf1078 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.$operationId.step.order.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.$operationId.step.order.tsx@@ -1,14 +1,15 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { assertMethodOperationIsDraft } from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";import { updateMethodOperationStepOrder } from "~/modules/production";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "parts"});@@ -30,6 +31,16 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ // Release-lock gate: enforce -> block; warn -> proceed + flash; off -> no-op.+ const lock = await checkRevisionLock(client, {+ kind: "operation",+ id: operationId,+ companyId+ });+ if (!lock.ok) {+ return data({}, await flash(request, error(null, lock.message)));+ }+await assertMethodOperationIsDraft(client, operationId);const updates = Object.entries(JSON.parse(updateMap)).map(@@ -53,5 +64,9 @@ export async function action({ request, params }: ActionFunctionArgs) {));+ if (lock.warn) {+ return data({ success: true }, await flash(request, success(lock.message)));+ }+return { success: true };}diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.delete.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.delete.tsxindex e18017e404..c66cd228f6 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.delete.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.delete.tsx@@ -1,9 +1,12 @@+import { success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";+import { checkRevisionLock } from "~/modules/items/items.server";export async function action({ request }: ActionFunctionArgs) {- const { client } = await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {delete: "parts"});@@ -19,6 +22,21 @@ export async function action({ request }: ActionFunctionArgs) {);}+ // Release-lock gate: enforce -> block; warn -> proceed + flash; off -> no-op.+ const lock = await checkRevisionLock(client, {+ kind: "operation",+ id,+ companyId+ });+ if (!lock.ok) {+ return data(+ { success: false, error: lock.message },+ {+ status: 400+ }+ );+ }+const { error } = await client.from("methodOperation").delete().eq("id", id);if (error) {@@ -30,5 +48,9 @@ export async function action({ request }: ActionFunctionArgs) {);}+ if (lock.warn) {+ return data({ success: true }, await flash(request, success(lock.message)));+ }+return { success: true };}diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.new.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.new.tsxindex 0ce1a6e570..c68720d71f 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.new.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.new.tsx@@ -1,4 +1,4 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";@@ -8,6 +8,7 @@ import {methodOperationValidator,upsertMethodOperation} from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";import { setCustomFields } from "~/utils/form";export async function action({ request, params }: ActionFunctionArgs) {@@ -25,6 +26,18 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}+ // Release-lock gate: enforce -> block; warn -> proceed + flash; off -> no-op.+ const lock = await checkRevisionLock(client, {+ kind: "makeMethod",+ id: validation.data.makeMethodId,+ companyId+ });+ if (!lock.ok) {+ return validationError({+ fieldErrors: { description: lock.message }+ });+ }+const insertMethodOperation = await upsertMethodOperation(client, {...validation.data,companyId,@@ -56,9 +69,15 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- return {+ const result = {id: methodOperationId,success: true,message: "Operation created"};++ if (lock.warn) {+ return data(result, await flash(request, success(lock.message)));+ }++ return result;}diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.order.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.order.tsxindex 469a480abf..054421da2f 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.order.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.order.tsx@@ -1,13 +1,14 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { updateOperationOrder } from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "parts"});@@ -27,6 +28,17 @@ export async function action({ request }: ActionFunctionArgs) {}));+ // Release-lock gate: enforce -> block; warn -> proceed + flash; off -> no-op.+ // All operations in a reorder share one make method, so resolve from the first.+ const lock = await checkRevisionLock(client, {+ kind: "operation",+ id: updates[0]?.id,+ companyId+ });+ if (!lock.ok) {+ return data({}, await flash(request, error(null, lock.message)));+ }+const updateSortOrders = await updateOperationOrder(client, updates);if (updateSortOrders.some((update) => update.error))return data(@@ -37,5 +49,9 @@ export async function action({ request }: ActionFunctionArgs) {));+ if (lock.warn) {+ return data(null, await flash(request, success(lock.message)));+ }+return null;}diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.parameter.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.parameter.$id.tsxindex 55b8708689..1613f34beb 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.parameter.$id.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.parameter.$id.tsx@@ -5,6 +5,7 @@ import { validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { upsertMethodOperationParameter } from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";import { operationParameterValidator } from "~/modules/shared";export async function action({ request, params }: ActionFunctionArgs) {@@ -29,6 +30,16 @@ export async function action({ request, params }: ActionFunctionArgs) {const { id: _id, ...d } = validation.data;+ // Release-lock gate: enforce -> block; warn -> proceed + flash; off -> no-op.+ const lock = await checkRevisionLock(client, {+ kind: "parameter",+ id,+ companyId+ });+ if (!lock.ok) {+ return data({ id: null }, await flash(request, error(null, lock.message)));+ }+const update = await upsertMethodOperationParameter(client, {id,...d,@@ -63,6 +74,9 @@ export async function action({ request, params }: ActionFunctionArgs) {return data({ id: methodOperationParameterId },- await flash(request, success("Method operation parameter updated"))+ await flash(+ request,+ success(lock.warn ? lock.message : "Method operation parameter updated")+ ));}diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.parameter.delete.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.parameter.delete.$id.tsxindex 0cf26d967d..b910d3b126 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.parameter.delete.$id.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.parameter.delete.$id.tsx@@ -1,13 +1,14 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { deleteMethodOperationParameter } from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client } = await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {delete: "parts"});@@ -16,6 +17,16 @@ export async function action({ request, params }: ActionFunctionArgs) {throw new Error("id not found");}+ // Release-lock gate: enforce -> block; warn -> proceed + flash; off -> no-op.+ const lock = await checkRevisionLock(client, {+ kind: "parameter",+ id,+ companyId+ });+ if (!lock.ok) {+ return data({ id: null }, await flash(request, error(null, lock.message)));+ }+const deleteOperationParameter = await deleteMethodOperationParameter(client,id@@ -35,5 +46,9 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ if (lock.warn) {+ return data({}, await flash(request, success(lock.message)));+ }+return {};}diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.parameter.new.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.parameter.new.tsxindex 92ec2e1053..eaf48d1f8c 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.parameter.new.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.parameter.new.tsx@@ -1,10 +1,11 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { upsertMethodOperationParameter } from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";import { operationParameterValidator } from "~/modules/shared";export async function action({ request }: ActionFunctionArgs) {@@ -22,6 +23,16 @@ export async function action({ request }: ActionFunctionArgs) {return validationError(validation.error);}+ // Release-lock gate: enforce -> block; warn -> proceed + flash; off -> no-op.+ const lock = await checkRevisionLock(client, {+ kind: "operation",+ id: validation.data.operationId,+ companyId+ });+ if (!lock.ok) {+ return data({ id: null }, await flash(request, error(null, lock.message)));+ }+const insert = await upsertMethodOperationParameter(client, {...validation.data,companyId,@@ -52,5 +63,12 @@ export async function action({ request }: ActionFunctionArgs) {);}+ if (lock.warn) {+ return data(+ { id: methodOperationParameterId },+ await flash(request, success(lock.message))+ );+ }+return { id: methodOperationParameterId };}diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.step.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.step.$id.tsxindex e91611caa6..026aaae8a2 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.step.$id.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.step.$id.tsx@@ -8,11 +8,12 @@ import {assertMethodOperationIsDraft,upsertMethodOperationStep} from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";import { operationStepValidator } from "~/modules/shared";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "parts"});@@ -30,6 +31,16 @@ export async function action({ request, params }: ActionFunctionArgs) {const { id: _id, ...d } = validation.data;+ // Release-lock gate: enforce -> block; warn -> proceed + flash; off -> no-op.+ const lock = await checkRevisionLock(client, {+ kind: "operation",+ id: validation.data.operationId,+ companyId+ });+ if (!lock.ok) {+ return { success: false, message: lock.message };+ }+await assertMethodOperationIsDraft(client, validation.data.operationId);const update = await upsertMethodOperationStep(client, {@@ -67,6 +78,9 @@ export async function action({ request, params }: ActionFunctionArgs) {return data({ id: methodOperationStepId },- await flash(request, success("Method operation step updated"))+ await flash(+ request,+ success(lock.warn ? lock.message : "Method operation step updated")+ ));}diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.step.delete.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.step.delete.$id.tsxindex eede48ea37..57e45d4ab3 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.step.delete.$id.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.step.delete.$id.tsx@@ -1,4 +1,4 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";@@ -7,10 +7,11 @@ import {assertMethodOperationIsDraft,deleteMethodOperationStep} from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client } = await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {delete: "parts"});@@ -29,6 +30,16 @@ export async function action({ request, params }: ActionFunctionArgs) {throw new Error("Step not found");}+ // Release-lock gate: enforce -> block; warn -> proceed + flash; off -> no-op.+ const lock = await checkRevisionLock(client, {+ kind: "operation",+ id: step.data.operationId,+ companyId+ });+ if (!lock.ok) {+ return data({ id: null }, await flash(request, error(null, lock.message)));+ }+await assertMethodOperationIsDraft(client, step.data.operationId);const deleteOperationStep = await deleteMethodOperationStep(client, id);@@ -47,5 +58,9 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ if (lock.warn) {+ return data({}, await flash(request, success(lock.message)));+ }+return {};}diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.step.new.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.step.new.tsxindex 9d096770e0..bd8a943c95 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.step.new.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.step.new.tsx@@ -1,4 +1,4 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";@@ -8,6 +8,7 @@ import {assertMethodOperationIsDraft,upsertMethodOperationStep} from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";import { operationStepValidator } from "~/modules/shared";export async function action({ request }: ActionFunctionArgs) {@@ -23,6 +24,16 @@ export async function action({ request }: ActionFunctionArgs) {return validationError(validation.error);}+ // Release-lock gate: enforce -> block; warn -> proceed + flash; off -> no-op.+ const lock = await checkRevisionLock(client, {+ kind: "operation",+ id: validation.data.operationId,+ companyId+ });+ if (!lock.ok) {+ return data({ id: null }, await flash(request, error(null, lock.message)));+ }+await assertMethodOperationIsDraft(client, validation.data.operationId);const insert = await upsertMethodOperationStep(client, {@@ -55,5 +66,12 @@ export async function action({ request }: ActionFunctionArgs) {);}+ if (lock.warn) {+ return data(+ { id: methodOperationStepId },+ await flash(request, success(lock.message))+ );+ }+return { id: methodOperationStepId };}diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.tool.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.tool.$id.tsxindex 19bdddd8a3..74e12fc5a4 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.tool.$id.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.tool.$id.tsx@@ -5,6 +5,7 @@ import { validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { upsertMethodOperationTool } from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";import { operationToolValidator } from "~/modules/shared";export async function action({ request, params }: ActionFunctionArgs) {@@ -27,6 +28,12 @@ export async function action({ request, params }: ActionFunctionArgs) {const { id: _id, ...d } = validation.data;+ // Release-lock gate: enforce -> block; warn -> proceed + flash; off -> no-op.+ const lock = await checkRevisionLock(client, { kind: "tool", id, companyId });+ if (!lock.ok) {+ return data({ id: null }, await flash(request, error(null, lock.message)));+ }+const update = await upsertMethodOperationTool(client, {id,...d,@@ -61,6 +68,9 @@ export async function action({ request, params }: ActionFunctionArgs) {return data({ id: methodOperationToolId },- await flash(request, success("Method operation tool updated"))+ await flash(+ request,+ success(lock.warn ? lock.message : "Method operation tool updated")+ ));}diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.tool.delete.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.tool.delete.$id.tsxindex 2b5fa40d68..43360c9b8d 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.tool.delete.$id.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.tool.delete.$id.tsx@@ -1,13 +1,14 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { deleteMethodOperationTool } from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client } = await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {delete: "parts"});@@ -16,6 +17,12 @@ export async function action({ request, params }: ActionFunctionArgs) {throw new Error("id not found");}+ // Release-lock gate: enforce -> block; warn -> proceed + flash; off -> no-op.+ const lock = await checkRevisionLock(client, { kind: "tool", id, companyId });+ if (!lock.ok) {+ return data({ id: null }, await flash(request, error(null, lock.message)));+ }+const deleteOperationTool = await deleteMethodOperationTool(client, id);if (deleteOperationTool.error) {return data(@@ -32,5 +39,9 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ if (lock.warn) {+ return data({}, await flash(request, success(lock.message)));+ }+return {};}diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.tool.new.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.tool.new.tsxindex b7242af840..9fa7f514d8 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.tool.new.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.tool.new.tsx@@ -1,10 +1,11 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { upsertMethodOperationTool } from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";import { operationToolValidator } from "~/modules/shared";export async function action({ request, params }: ActionFunctionArgs) {@@ -20,6 +21,16 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}+ // Release-lock gate: enforce -> block; warn -> proceed + flash; off -> no-op.+ const lock = await checkRevisionLock(client, {+ kind: "operation",+ id: validation.data.operationId,+ companyId+ });+ if (!lock.ok) {+ return data({ id: null }, await flash(request, error(null, lock.message)));+ }+const insert = await upsertMethodOperationTool(client, {...validation.data,companyId,@@ -50,5 +61,12 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ if (lock.warn) {+ return data(+ { id: methodOperationToolId },+ await flash(request, success(lock.message))+ );+ }+return { id: methodOperationToolId };}diff --git a/apps/erp/app/routes/x+/items+/methods+/save.tsx b/apps/erp/app/routes/x+/items+/methods+/save.tsxindex 3bb8d8dfe0..a5ea5b2b24 100644--- a/apps/erp/app/routes/x+/items+/methods+/save.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/save.tsx@@ -1,9 +1,12 @@+import { success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { copyItem, copyMakeMethod, getMethodValidator } from "~/modules/items";+import { checkRevisionLock } from "~/modules/items/items.server";import { path, requestReferrer } from "~/utils/path";export async function action({ request }: ActionFunctionArgs) {@@ -24,6 +27,17 @@ export async function action({ request }: ActionFunctionArgs) {// MakeMethodTools.tsx now sends makeMethod IDs directlyconst isMakeMethodId = (id: string) => id.startsWith("make_");+ // Release-lock gate: copyMakeMethod/copyItem OVERWRITE the target method's+ // materials + operations, so gate on the destination (target) item.+ const lock = await checkRevisionLock(serviceRole, {+ kind: isMakeMethodId(validation.data.targetId) ? "makeMethod" : "item",+ id: validation.data.targetId,+ companyId+ });+ if (!lock.ok) {+ return { error: lock.message };+ }+const upsert =isMakeMethodId(validation.data.sourceId) ||isMakeMethodId(validation.data.targetId)@@ -44,5 +58,8 @@ export async function action({ request }: ActionFunctionArgs) {};}- throw redirect(requestReferrer(request) ?? path.to.items);+ throw redirect(+ requestReferrer(request) ?? path.to.items,+ lock.warn ? await flash(request, success(lock.message)) : undefined+ );}diff --git a/apps/erp/app/routes/x+/items+/methods+/version.new.tsx b/apps/erp/app/routes/x+/items+/methods+/version.new.tsxindex 05253907d4..45ee488081 100644--- a/apps/erp/app/routes/x+/items+/methods+/version.new.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/version.new.tsx@@ -27,6 +27,10 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}+ // No change-order gate here: the V1 change-order model applies BOM edits by+ // spinning fresh method versions at Done and never stages/reserves a pending+ // revision, so there is nothing for an open CO to lock against.+const insertMethodOperation = await upsertMakeMethodVersion(client, {...validation.data,companyId,diff --git a/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsxindex bb37c9430d..9b7c94f2dd 100644--- a/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx@@ -1,8 +1,10 @@-import { assertIsPost } from "@carbon/auth";+import { assertIsPost, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";+import { checkRevisionLock } from "~/modules/items/items.server";import { activateMethodVersion } from "~/modules/items/items.service";import { requestReferrer } from "~/utils/path";@@ -20,37 +22,57 @@ export async function action({ request, params }: ActionFunctionArgs) {return { success: false, message: "Invalid operation tool id" };}- const update = await activateMethodVersion(getCarbonServiceRole(), {- id,- companyId,- userId- });-- if (update.error) {+ // Validate redirect inputs BEFORE mutating: activation switches the live+ // BOM/BOP, so a missing query param or referrer must fail without having+ // already flipped the method.+ if (!methodToReplace) {return {success: false,- message: "Failed to activate method version"+ message: "Method to replace is required"};}- if (!methodToReplace) {+ const redirectPath = requestReferrer(request)?.replace(methodToReplace, id);++ if (!redirectPath) {return {success: false,- message: "Method to replace is required"+ message: "Failed to redirect to the correct page"};}- const redirectPath = requestReferrer(request)?.replace(- methodToReplace ?? "",- id ?? ""- );+ const serviceRole = getCarbonServiceRole();- if (!redirectPath) {+ // Release-lock gate: activating a make-method version switches the live+ // BOM/BOP for the item, so resolve the version's parent item and gate on it.+ const lock = await checkRevisionLock(serviceRole, {+ kind: "makeMethod",+ id,+ companyId+ });+ if (!lock.ok) {+ return { success: false, message: lock.message };+ }++ // No change-order gate here: the V1 change-order model applies BOM edits by+ // spinning fresh method versions at Done and never stages/reserves a pending+ // revision, so there is nothing for an open CO to lock against.++ const update = await activateMethodVersion(serviceRole, {+ id,+ companyId,+ userId+ });++ if (update.error) {return {success: false,- message: "Failed to redirect to the correct page"+ message: "Failed to activate method version"};}- return redirect(redirectPath);+ return redirect(+ redirectPath,+ lock.warn ? await flash(request, success(lock.message)) : undefined+ );}diff --git a/apps/erp/app/routes/x+/items+/revisions.new.tsx b/apps/erp/app/routes/x+/items+/revisions.new.tsxindex ce002201a7..2fbd2ac33e 100644--- a/apps/erp/app/routes/x+/items+/revisions.new.tsx+++ b/apps/erp/app/routes/x+/items+/revisions.new.tsx@@ -43,27 +43,24 @@ export async function action({ request }: ActionFunctionArgs) {return { success: false, error: "Failed to create revision" };}- switch (currentItem.data.type) {- case "Part":- return { success: true, link: path.to.partDetails(result.data.id) };- case "Material":- return {- success: true,- link: path.to.materialDetails(result.data.id)- };- case "Tool":- return { success: true, link: path.to.toolDetails(result.data.id) };- case "Consumable":- return {- success: true,- link: path.to.consumableDetails(result.data.id)- };- case "Service":- return {- success: true,- link: path.to.serviceDetails(result.data.id)- };- default:- return { success: true, link: path.to.items };- }+ const link = (() => {+ switch (currentItem.data.type) {+ case "Part":+ return path.to.partDetails(result.data.id);+ case "Material":+ return path.to.materialDetails(result.data.id);+ case "Tool":+ return path.to.toolDetails(result.data.id);+ case "Consumable":+ return path.to.consumableDetails(result.data.id);+ case "Service":+ return path.to.serviceDetails(result.data.id);+ default:+ return path.to.items;+ }+ })();++ // newItemId lets the caller (e.g. the new-revision modal's "open change order"+ // option) act on the created revision without parsing it out of `link`.+ return { success: true, link, newItemId: result.data.id };}diff --git a/apps/erp/app/routes/x+/items+/update.tsx b/apps/erp/app/routes/x+/items+/update.tsxindex 55a79745ca..799081af1f 100644--- a/apps/erp/app/routes/x+/items+/update.tsx+++ b/apps/erp/app/routes/x+/items+/update.tsx@@ -4,96 +4,16 @@ import { getLogger } from "@carbon/logger";import { getMaterialDescription, getMaterialId } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import type { InventoryItemType } from "~/modules/items";+import { deriveItemMethodUpdate } from "~/modules/items";import {cascadeItemTrackingType,updateItemMethodAndSourcing} from "~/modules/items/items.service";import { getCompanySettings } from "~/modules/settings";-import type { MethodType, SourcingType } from "~/modules/shared";import { getDatabaseClient } from "~/services/database.server";const logger = getLogger("erp", "update");-type ItemReplenishmentSystem =- Database["public"]["Enums"]["itemReplenishmentSystem"];--/**- * Maps an inline edit of one of the three interlocked item-level fields- * (replenishmentSystem, defaultMethodType, sourcingType) to the columns that- * should be written on the item and the values that should be mirrored down to- * its method materials. Pure — no DB access — so the relationships between the- * fields live in one readable place instead of being scattered across branches.- */-function deriveItemMethodUpdate(- field: "replenishmentSystem" | "defaultMethodType" | "sourcingType",- value: string-): {- itemUpdate: {- replenishmentSystem?: ItemReplenishmentSystem;- defaultMethodType?: MethodType;- sourcingType?: SourcingType;- };- cascade: { sourcingType?: SourcingType; methodType?: MethodType };-} {- switch (field) {- case "replenishmentSystem": {- const replenishmentSystem = value as ItemReplenishmentSystem;- // Picking a concrete replenishment system pins the default method type.- if (value !== "Buy and Make") {- const defaultMethodType: MethodType =- value === "Make"- ? "Make to Order"- : value === "Buy"- ? "Purchase to Order"- : "Pull from Inventory";- return {- itemUpdate: { replenishmentSystem, defaultMethodType },- cascade: { methodType: defaultMethodType }- };- }- return { itemUpdate: { replenishmentSystem }, cascade: {} };- }- case "defaultMethodType": {- const defaultMethodType = value as MethodType;- // A concrete method type pins the replenishment system to match.- if (value !== "Pull from Inventory") {- const replenishmentSystem: ItemReplenishmentSystem =- value === "Make to Order"- ? "Make"- : value === "Purchase to Order"- ? "Buy"- : "Buy and Make";- return {- itemUpdate: { defaultMethodType, replenishmentSystem },- cascade: { methodType: defaultMethodType }- };- }- return {- itemUpdate: { defaultMethodType },- cascade: { methodType: defaultMethodType }- };- }- case "sourcingType": {- const sourcingType = value as SourcingType;- // Sourcing drives method type: Drop Ship → Purchase to Order, Ship from- // Inventory → Pull from Inventory, Specified → leave method type as-is.- const methodType: MethodType | undefined =- value === "Drop Ship"- ? "Purchase to Order"- : value === "Ship from Inventory"- ? "Pull from Inventory"- : undefined;- return {- itemUpdate: {- sourcingType,- ...(methodType ? { defaultMethodType: methodType } : {})- },- cascade: { sourcingType, methodType }- };- }- }-}-export async function action({ request }: ActionFunctionArgs) {const { client, companyId, userId } = await requirePermissions(request, {update: "parts"@@ -132,7 +52,11 @@ export async function action({ request }: ActionFunctionArgs) {userId});} catch (err) {- logger.error("Error", { error: err });+ logger.error("Failed to cascade item tracking type", {+ field,+ itemIds: items,+ error: err+ });return {error: { message: "Failed to cascade tracking flags" },data: null@@ -170,7 +94,12 @@ export async function action({ request }: ActionFunctionArgs) {cascade});} catch (err) {- logger.error("Error", { error: err });+ logger.error("Failed to update item method/sourcing", {+ field,+ value,+ itemIds: items,+ error: err+ });return { error: { message: "Failed to update item" }, data: null };}return { data: null, error: null };diff --git a/apps/erp/app/routes/x+/part+/$itemId.details.tsx b/apps/erp/app/routes/x+/part+/$itemId.details.tsxindex 50fef5ad1e..5d1a822d8b 100644--- a/apps/erp/app/routes/x+/part+/$itemId.details.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.details.tsx@@ -20,6 +20,7 @@ import type { ItemFile, MakeMethod, PartSummary } from "~/modules/items";import {getConfigurationParameters,getConfigurationRules,+ getItemChangeOrderData,getItemManufacturing,getMakeMethodById,getMakeMethods,@@ -30,6 +31,11 @@ import {upsertItemManufacturing,upsertPart} from "~/modules/items";+import { getRevisionLock } from "~/modules/items/items.server";+import {+ ItemChangeOrders,+ ItemOpenChangeOrderAlert+} from "~/modules/items/ui/ChangeOrder";import {BillOfMaterial,BillOfProcess,@@ -60,22 +66,45 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const url = new URL(request.url);const requestedMethodId = url.searchParams.get("methodId");- const makeMethods = await getMakeMethods(client, itemId, companyId);+ const [makeMethods, revisionLock, changeOrderData] = await Promise.all([+ getMakeMethods(client, itemId, companyId),+ getRevisionLock(client, { itemId, companyId }),+ // Part → CO traceability (4b): CO history for this part + type labels.+ getItemChangeOrderData(client, itemId, companyId)+ ]);+ const revisionStatus = revisionLock.revisionStatus;+ const releaseControl = revisionLock.releaseControl;+ // Include CO-owned draft methods so a revision/new-part item created by an open+ // Change Order still shows its BOM/BOP on the item master. The draft is the same+ // makeMethod the CO edits, so the two surfaces stay in sync. Active is still+ // preferred below, so a Version CO's item keeps its live method as the default.+ const selectable = makeMethods.data ?? [];const makeMethod = requestedMethodId- ? (makeMethods.data?.find((m) => m.id === requestedMethodId) ??- makeMethods.data?.find((m) => m.status === "Active") ??- makeMethods.data?.[0])- : (makeMethods.data?.find((m) => m.status === "Active") ??- makeMethods.data?.[0]);+ ? (selectable.find((m) => m.id === requestedMethodId) ??+ selectable.find((m) => m.status === "Active") ??+ selectable[0])+ : (selectable.find((m) => m.status === "Active") ?? selectable[0]);if (!makeMethod) {- return { methodData: null, tags: [] };+ return {+ methodData: null,+ tags: [],+ revisionStatus,+ releaseControl,+ ...changeOrderData+ };}const fullMethod = await getMakeMethodById(client, makeMethod.id, companyId);if (fullMethod.error || !fullMethod.data) {- return { methodData: null, tags: [] };+ return {+ methodData: null,+ tags: [],+ revisionStatus,+ releaseControl,+ ...changeOrderData+ };}const [methodMaterials, methodOperations, tags, partManufacturing] =@@ -125,7 +154,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {partManufacturing: partManufacturing.data,...configData},- tags: tags.data ?? []+ tags: tags.data ?? [],+ revisionStatus,+ releaseControl,+ ...changeOrderData};}@@ -216,7 +248,14 @@ export default function PartDetailsRoute() {if (!itemId) throw new Error("Could not find itemId");const permissions = usePermissions();- const { methodData, tags } = useLoaderData<typeof loader>();+ const {+ methodData,+ tags,+ revisionStatus,+ releaseControl,+ changeOrders,+ changeOrderTypes+ } = useLoaderData<typeof loader>();const partData = useRouteData<{partSummary: PartSummary;@@ -236,6 +275,9 @@ export default function PartDetailsRoute() {return (<VStack spacing={2} className="p-2">+ {permissions.is("employee") && (+ <ItemOpenChangeOrderAlert changeOrders={changeOrders ?? []} />+ )}{permissions.is("employee") && methodData && (<>{["Make", "Buy and Make"].includes(@@ -297,6 +339,8 @@ export default function PartDetailsRoute() {methodData.configurationParametersAndGroups.parameters}replenishmentSystem={partData.partSummary?.replenishmentSystem}+ revisionStatus={revisionStatus}+ releaseControl={releaseControl}/><BillOfProcesskey={`bop:${itemId}`}@@ -313,6 +357,8 @@ export default function PartDetailsRoute() {methodData.configurationParametersAndGroups.parameters}tags={tags}+ revisionStatus={revisionStatus}+ releaseControl={releaseControl}/></>)}@@ -345,6 +391,10 @@ export default function PartDetailsRoute() {title={t`CAD Model`}/><ItemRiskRegister itemId={itemId} />+ <ItemChangeOrders+ changeOrders={changeOrders ?? []}+ types={changeOrderTypes ?? []}+ /></>)}</VStack>diff --git a/apps/erp/app/routes/x+/part+/$itemId.make.$makeMethodId.tsx b/apps/erp/app/routes/x+/part+/$itemId.make.$makeMethodId.tsxindex 3a910214a1..1fde3e4262 100644--- a/apps/erp/app/routes/x+/part+/$itemId.make.$makeMethodId.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.make.$makeMethodId.tsx@@ -20,6 +20,7 @@ import {getMethodMaterialsByMakeMethod,getMethodOperationsByMakeMethodId} from "~/modules/items";+import { getRevisionLock } from "~/modules/items/items.server";import {BillOfMaterial,BillOfProcess,@@ -43,13 +44,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {methodMaterials,methodOperations,tags,- partManufacturing+ partManufacturing,+ revisionLock] = await Promise.all([getMakeMethodById(client, makeMethodId, companyId),getMethodMaterialsByMakeMethod(client, makeMethodId),getMethodOperationsByMakeMethodId(client, makeMethodId),getTagsList(client, companyId, "operation"),- getItemManufacturing(client, itemId, companyId)+ getItemManufacturing(client, itemId, companyId),+ getRevisionLock(client, { itemId, companyId })]);if (makeMethod.error) {@@ -127,7 +130,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {...configData,model: getModelByItemId(client, makeMethod.data.itemId),makeMethods: getMakeMethods(client, makeMethod.data.itemId, companyId),- tags: tags.data ?? []+ tags: tags.data ?? [],+ revisionStatus: revisionLock.revisionStatus,+ releaseControl: revisionLock.releaseControl};}@@ -143,7 +148,9 @@ export default function PartMakeMethodPage() {partManufacturing,configurationParametersAndGroups,configurationRules,- tags+ tags,+ revisionStatus,+ releaseControl} = loaderData;const { itemId, makeMethodId } = useParams();@@ -179,6 +186,8 @@ export default function PartMakeMethodPage() {configurationRules={configurationRules}parameters={configurationParametersAndGroups.parameters}replenishmentSystem={partData?.partSummary?.replenishmentSystem}+ revisionStatus={revisionStatus}+ releaseControl={releaseControl}/><BillOfProcesskey={`bop:${makeMethodId}`}@@ -190,6 +199,8 @@ export default function PartMakeMethodPage() {configurationRules={configurationRules}parameters={configurationParametersAndGroups.parameters}tags={tags}+ revisionStatus={revisionStatus}+ releaseControl={releaseControl}/><Suspense fallback={null}><Await resolve={loaderData.model}>diff --git a/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsxindex 54d57bd760..b1e475da05 100644--- a/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx@@ -1,10 +1,9 @@-import { assertIsPost, success } from "@carbon/auth";+import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { validator } from "@carbon/form";import { useRouteData } from "@carbon/react";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";-import { redirect, useLoaderData, useNavigate, useParams } from "react-router";+import { useLoaderData, useNavigate, useParams } from "react-router";import type { PartSummary } from "~/modules/items";import { supplierPartValidator, upsertSupplierPart } from "~/modules/items";import { SupplierPartForm } from "~/modules/items/ui/Item";@@ -122,10 +121,10 @@ export async function action({ request, params }: ActionFunctionArgs) {});}- throw redirect(- path.to.partPurchasing(itemId),- await flash(request, success("Supplier part updated"))- );+ // Fetcher-friendly success (mirrors the create route): the form's fetcher+ // effect toasts + fires onClose, so callers embedded outside the part page+ // (e.g. the change-order line detail) aren't yanked to partPurchasing.+ return { success: true, message: "Supplier part updated" };}export default function EditPartSupplierRoute() {diff --git a/apps/erp/app/routes/x+/part+/$itemId.tsx b/apps/erp/app/routes/x+/part+/$itemId.tsxindex eb55c4e004..c4463a71f5 100644--- a/apps/erp/app/routes/x+/part+/$itemId.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.tsx@@ -105,12 +105,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const methodTree = getMakeMethods(client, itemId, companyId).then(async (makeMethods) => {+ // Include CO-owned drafts so a revision/new-part item created by an open+ // Change Order shows its method tree on the item master, in sync with the+ // CO (same makeMethod). Active is still preferred as the default below.+ const selectable = makeMethods.data ?? [];const makeMethod = requestedMethodId- ? (makeMethods.data?.find((m) => m.id === requestedMethodId) ??- makeMethods.data?.find((m) => m.status === "Active") ??- makeMethods.data?.[0])- : (makeMethods.data?.find((m) => m.status === "Active") ??- makeMethods.data?.[0]);+ ? (selectable.find((m) => m.id === requestedMethodId) ??+ selectable.find((m) => m.status === "Active") ??+ selectable[0])+ : (selectable.find((m) => m.status === "Active") ?? selectable[0]);if (!makeMethod) return null;const fullMethod = await getMakeMethodById(diff --git a/apps/erp/app/routes/x+/settings+/items.tsx b/apps/erp/app/routes/x+/settings+/items.tsxindex 9d444ad1ba..66e33334bd 100644--- a/apps/erp/app/routes/x+/settings+/items.tsx+++ b/apps/erp/app/routes/x+/settings+/items.tsx@@ -1,10 +1,12 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { Hidden, Select, Submit, ValidatedForm, validator } from "@carbon/form";import {Card,CardContent,CardDescription,+ CardFooter,CardHeader,CardTitle,Heading,@@ -15,14 +17,17 @@ import {VStack} from "@carbon/react";import { msg } from "@lingui/core/macro";-import { Trans } from "@lingui/react/macro";+import { Trans, useLingui } from "@lingui/react/macro";import { useCallback, useEffect } from "react";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useFetcher, useLoaderData } from "react-router";+import { plmReleaseControl } from "~/modules/items";import {getCompanySettings,+ plmReleaseControlValidator,updateMaterialGeneratedIdsSetting,- updateMetricSettings+ updateMetricSettings,+ updatePlmReleaseControlSetting} from "~/modules/settings";import type { Handle } from "~/utils/handle";@@ -78,15 +83,43 @@ export async function action({ request }: ActionFunctionArgs) {return { success: false, message: result.error.message };return { success: true, message: "Material units setting updated" };}++ case "plmReleaseControl": {+ const validation = await validator(plmReleaseControlValidator).validate(+ formData+ );+ if (validation.error) {+ return { success: false, message: "Invalid form data" };+ }++ const result = await updatePlmReleaseControlSetting(+ client,+ companyId,+ validation.data.plmReleaseControl+ );+ if (result.error)+ return { success: false, message: result.error.message };+ return { success: true, message: "Release control setting updated" };+ }}return { success: false, message: "Invalid form data" };}export default function ItemsSettingsRoute() {+ const { t } = useLingui();const { companySettings } = useLoaderData<typeof loader>();const fetcher = useFetcher<typeof action>();+ const releaseControlLabels: Record<+ (typeof plmReleaseControl)[number],+ string+ > = {+ off: t`Off — released revisions stay editable`,+ warn: t`Warn — edits succeed with a warning`,+ enforce: t`Enforce — edits are blocked`+ };+const isToggling = fetcher.state !== "idle";useEffect(() => {@@ -207,6 +240,47 @@ export default function ItemsSettingsRoute() {</HStack></CardContent></Card>+ <Card>+ <ValidatedForm+ method="post"+ validator={plmReleaseControlValidator}+ defaultValues={{+ plmReleaseControl: companySettings.plmReleaseControl ?? "enforce"+ }}+ fetcher={fetcher}+ >+ <CardHeader>+ <CardTitle>+ <Trans>Release Control</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>+ Controls whether the bill of material and bill of process of a+ released (Production) revision can be edited outside a change+ order.+ </Trans>+ </CardDescription>+ </CardHeader>+ <CardContent>+ <Hidden name="intent" value="plmReleaseControl" />+ <div className="flex flex-col gap-2 max-w-[400px]">+ <Select+ name="plmReleaseControl"+ label={t`Release control`}+ options={plmReleaseControl.map((option) => ({+ value: option,+ label: releaseControlLabels[option]+ }))}+ />+ </div>+ </CardContent>+ <CardFooter>+ <Submit>+ <Trans>Save</Trans>+ </Submit>+ </CardFooter>+ </ValidatedForm>+ </Card></VStack></ScrollArea>);diff --git a/apps/erp/app/routes/x+/tool+/$itemId.details.tsx b/apps/erp/app/routes/x+/tool+/$itemId.details.tsxindex a0ee495750..d25a68514b 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.details.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.details.tsx@@ -14,6 +14,7 @@ import { CadModel, DeferredFiles } from "~/components";import { usePermissions, useRouteData } from "~/hooks";import type { ItemFile, MakeMethod, ToolSummary } from "~/modules/items";import {+ getItemChangeOrderData,getItemManufacturing,getMakeMethodById,getMakeMethods,@@ -24,6 +25,11 @@ import {upsertItemManufacturing,upsertTool} from "~/modules/items";+import { getRevisionLock } from "~/modules/items/items.server";+import {+ ItemChangeOrders,+ ItemOpenChangeOrderAlert+} from "~/modules/items/ui/ChangeOrder";import {BillOfMaterial,BillOfProcess,@@ -52,21 +58,44 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const url = new URL(request.url);const requestedMethodId = url.searchParams.get("methodId");- const makeMethods = await getMakeMethods(client, itemId, companyId);+ const [makeMethods, revisionLock, changeOrderData] = await Promise.all([+ getMakeMethods(client, itemId, companyId),+ getRevisionLock(client, { itemId, companyId }),+ // Tool → CO traceability (4b): CO history for this tool + type labels.+ getItemChangeOrderData(client, itemId, companyId)+ ]);+ const revisionStatus = revisionLock.revisionStatus;+ const releaseControl = revisionLock.releaseControl;+ // Include CO-owned draft methods so a revision/new-part item created by an open+ // Change Order still shows its BOM/BOP on the item master. The draft is the same+ // makeMethod the CO edits, so the two surfaces stay in sync. Active is still+ // preferred below, so a Version CO's item keeps its live method as the default.+ const selectable = makeMethods.data ?? [];const makeMethod = requestedMethodId- ? (makeMethods.data?.find((m) => m.id === requestedMethodId) ??- makeMethods.data?.find((m) => m.status === "Active") ??- makeMethods.data?.[0])- : (makeMethods.data?.find((m) => m.status === "Active") ??- makeMethods.data?.[0]);+ ? (selectable.find((m) => m.id === requestedMethodId) ??+ selectable.find((m) => m.status === "Active") ??+ selectable[0])+ : (selectable.find((m) => m.status === "Active") ?? selectable[0]);if (!makeMethod) {- return { methodData: null, tags: [] };+ return {+ methodData: null,+ tags: [],+ revisionStatus,+ releaseControl,+ ...changeOrderData+ };}const fullMethod = await getMakeMethodById(client, makeMethod.id, companyId);if (fullMethod.error || !fullMethod.data) {- return { methodData: null, tags: [] };+ return {+ methodData: null,+ tags: [],+ revisionStatus,+ releaseControl,+ ...changeOrderData+ };}const [methodMaterials, methodOperations, tags, toolManufacturing] =@@ -97,7 +126,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {})) ?? [],toolManufacturing: toolManufacturing.data},- tags: tags.data ?? []+ tags: tags.data ?? [],+ revisionStatus,+ releaseControl,+ ...changeOrderData};}@@ -179,7 +211,14 @@ export default function ToolDetailsRoute() {if (!itemId) throw new Error("Could not find itemId");const permissions = usePermissions();- const { methodData, tags } = useLoaderData<typeof loader>();+ const {+ methodData,+ tags,+ revisionStatus,+ releaseControl,+ changeOrders,+ changeOrderTypes+ } = useLoaderData<typeof loader>();const toolData = useRouteData<{toolSummary: ToolSummary;@@ -199,28 +238,36 @@ export default function ToolDetailsRoute() {return (<VStack spacing={2} className="p-2">+ {permissions.is("employee") && (+ <ItemOpenChangeOrderAlert changeOrders={changeOrders ?? []} />+ )}{permissions.is("employee") && methodData && (<>- <Suspense fallback={<Menubar />}>- <Await resolve={toolData?.makeMethods}>- {(makeMethods) => (- <MakeMethodTools- itemId={methodData.makeMethod.itemId}- makeMethods={makeMethods?.data ?? []}- type="Tool"- currentMethodId={methodData.makeMethod.id}+ {["Make", "Buy and Make"].includes(+ toolData.toolSummary?.replenishmentSystem ?? ""+ ) && (+ <>+ <Suspense fallback={<Menubar />}>+ <Await resolve={toolData?.makeMethods}>+ {(makeMethods) => (+ <MakeMethodTools+ itemId={methodData.makeMethod.itemId}+ makeMethods={makeMethods?.data ?? []}+ type="Tool"+ currentMethodId={methodData.makeMethod.id}+ />+ )}+ </Await>+ </Suspense>+ {manufacturingInitialValues && (+ <ItemManufacturingForm+ key={itemId}+ // @ts-ignore+ initialValues={manufacturingInitialValues}+ withConfiguration={false}/>)}- </Await>- </Suspense>-- {manufacturingInitialValues && (- <ItemManufacturingForm- key={itemId}- // @ts-ignore- initialValues={manufacturingInitialValues}- withConfiguration={false}- />+ </>)}<ItemNotesid={toolData.toolSummary?.id ?? null}@@ -240,6 +287,8 @@ export default function ToolDetailsRoute() {// @ts-ignoreoperations={methodData.methodOperations}replenishmentSystem={toolData.toolSummary?.replenishmentSystem}+ revisionStatus={revisionStatus}+ releaseControl={releaseControl}/><BillOfProcesskey={`bop:${itemId}`}@@ -247,6 +296,8 @@ export default function ToolDetailsRoute() {// @ts-ignoreoperations={methodData.methodOperations ?? []}tags={tags}+ revisionStatus={revisionStatus}+ releaseControl={releaseControl}/></>)}@@ -273,6 +324,10 @@ export default function ToolDetailsRoute() {/><ItemRiskRegister itemId={itemId} />+ <ItemChangeOrders+ changeOrders={changeOrders ?? []}+ types={changeOrderTypes ?? []}+ /></>)}</VStack>diff --git a/apps/erp/app/routes/x+/tool+/$itemId.make.$makeMethodId.tsx b/apps/erp/app/routes/x+/tool+/$itemId.make.$makeMethodId.tsxindex 5b16873849..3d95c7a11b 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.make.$makeMethodId.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.make.$makeMethodId.tsx@@ -17,6 +17,7 @@ import {getMethodMaterialsByMakeMethod,getMethodOperationsByMakeMethodId} from "~/modules/items";+import { getRevisionLock } from "~/modules/items/items.server";import {BillOfMaterial,BillOfProcess,@@ -35,12 +36,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {if (!itemId) throw new Error("Could not find itemId");if (!makeMethodId) throw new Error("Could not find makeMethodId");- const [makeMethod, methodMaterials, methodOperations, tags] =+ const [makeMethod, methodMaterials, methodOperations, tags, revisionLock] =await Promise.all([getMakeMethodById(client, makeMethodId, companyId),getMethodMaterialsByMakeMethod(client, makeMethodId),getMethodOperationsByMakeMethodId(client, makeMethodId),- getTagsList(client, companyId, "operation")+ getTagsList(client, companyId, "operation"),+ getRevisionLock(client, { itemId, companyId })]);if (makeMethod.error) {@@ -98,7 +100,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {})) ?? [],model: getModelByItemId(client, makeMethod.data.itemId),makeMethods: getMakeMethods(client, makeMethod.data.itemId, companyId),- tags: tags.data ?? []+ tags: tags.data ?? [],+ revisionStatus: revisionLock.revisionStatus,+ releaseControl: revisionLock.releaseControl};}@@ -106,8 +110,15 @@ export default function ToolMakeMethodPage() {const { t } = useLingui();const loaderData = useLoaderData<typeof loader>();const permissions = usePermissions();- const { makeMethod, makeMethods, methodMaterials, methodOperations, tags } =- loaderData;+ const {+ makeMethod,+ makeMethods,+ methodMaterials,+ methodOperations,+ tags,+ revisionStatus,+ releaseControl+ } = loaderData;const { itemId, makeMethodId } = useParams();if (!itemId) throw new Error("Could not find itemId");@@ -139,6 +150,8 @@ export default function ToolMakeMethodPage() {materials={methodMaterials}operations={methodOperations}replenishmentSystem={toolData?.toolSummary?.replenishmentSystem}+ revisionStatus={revisionStatus}+ releaseControl={releaseControl}/><BillOfProcesskey={`bop:${makeMethodId}`}@@ -147,6 +160,8 @@ export default function ToolMakeMethodPage() {// @ts-expect-erroroperations={methodOperations}tags={tags}+ revisionStatus={revisionStatus}+ releaseControl={releaseControl}/><Suspense fallback={null}><Await resolve={loaderData.model}>diff --git a/apps/erp/app/stores/items.ts b/apps/erp/app/stores/items.tsindex b0df538f7a..af27de06f9 100644--- a/apps/erp/app/stores/items.ts+++ b/apps/erp/app/stores/items.ts@@ -6,6 +6,8 @@ import type { ListItem } from "~/types";export type Item = ListItem & {readableIdWithRevision: string;+ readableId?: string | null;+ revision?: string | null;replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"];itemTrackingType: Database["public"]["Enums"]["itemTrackingType"];unitOfMeasureCode: string;@@ -17,6 +19,33 @@ export type Item = ListItem & {successorItemId?: string | null;};+// '0'/''/null are all the initial revision; named revisions (A, B, …) rank above+// it and sort lexically (mirrors the item fetch's `revision DESC` ordering).+function revisionRank(revision?: string | null): string {+ return revision == null || revision === "" ? "0" : revision;+}++// Collapse a list of item revisions to one row per readableId, keeping the+// latest revision — deterministically, without depending on array order. Used+// by pickers that should offer a single current revision per part (e.g. change+// orders). Falls back to `id` as the key when `readableId` is absent.+export function latestRevisionByReadableId<+ T extends { id: string; readableId?: string; revision?: string | null }+>(items: T[]): T[] {+ const byKey = new Map<string, T>();+ for (const item of items) {+ const key = item.readableId ?? item.id;+ const existing = byKey.get(key);+ if (+ !existing ||+ revisionRank(item.revision) > revisionRank(existing.revision)+ ) {+ byKey.set(key, item);+ }+ }+ return Array.from(byKey.values());+}+const $itemsStore = atom<Item[]>([]);const $partsStore = computed($itemsStore, (item) =>diff --git a/apps/erp/app/utils/handle.ts b/apps/erp/app/utils/handle.tsindex 54493f15f3..6ad9dbd0c1 100644--- a/apps/erp/app/utils/handle.ts+++ b/apps/erp/app/utils/handle.ts@@ -5,6 +5,10 @@ export type Handle = {breadcrumb?: any;to?: string;module?: string;+ // When true, a module _layout hides its GroupedContentSidebar for this route —+ // used by full-screen detail views that provide their own left panel (e.g. the+ // change-order workspace) so the app doesn't stack two left sidebars.+ hideModuleSidebar?: boolean;};// A breadcrumb label may be plain text/markup or a Lingui MessageDescriptordiff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 3205202e10..7415e4c006 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -12,6 +12,35 @@ export const ERP_URL = getAppUrl();export const path = {to: {+ abilities: `${x}/resources/abilities`,+ ability: (id: string) => generatePath(`${x}/resources/ability/${id}`),+ account: `${x}/account`,+ accounting: `${x}/accounting`,+ accountingDefaults: `${x}/accounting/defaults`,+ accountingGroupsBankAccounts: `${x}/accounting/groups/bank-accounts`,+ accountingGroupsFixedAssets: `${x}/accounting/groups/fixed-assets`,+ accountingGroupsInventory: `${x}/accounting/groups/inventory`,+ accountingGroupsPurchasing: `${x}/accounting/groups/purchasing`,+ accountingGroupsSales: `${x}/accounting/groups/sales`,+ accountingJournals: `${x}/accounting/journals`,+ accountingPeriodClose: (id: string) =>+ generatePath(`${x}/accounting/periods/${id}/close`),+ accountingPeriodDelete: (id: string) =>+ generatePath(`${x}/accounting/periods/${id}/delete`),+ accountingPeriods: `${x}/accounting/periods`,+ accountingPeriodsGenerate: `${x}/accounting/periods/generate`,+ accountingRoot: `${x}/accounting`,+ accountingSettings: `${x}/settings/accounting`,+ accountPassword: `${x}/account/password`,+ accountPersonal: `${x}/account/personal`,+ accountSecurity: `${x}/account/security`,+ acknowledge: `${x}/acknowledge`,+ activateGauge: (id: string) =>+ generatePath(`${x}/quality/gauges/activate/${id}`),+ activeMethodVersion: (id: string) =>+ generatePath(`${x}/items/methods/versions/activate/${id}`),+ addAndIssueMaintenanceDispatchItem: (dispatchId: string) =>+ generatePath(`${x}/maintenance/${dispatchId}/add-and-issue`),api: {abilities: `${api}/resources/abilities`,accounts: `${api}/accounting/accounts`,@@ -29,7 +58,9 @@ export const path = {`${api}/items/methods/${methodId}/bom.csv?withOperations=${withOperations}`),chat: `${api}/ai/chat`,+ costCenters: `${api}/accounting/cost-centers`,countries: `${api}/countries`,+ createCsvLookup: `${api}/csv/create-lookup`,currencies: `${api}/accounting/currencies`,customerContacts: (id: string) =>generatePath(`${api}/sales/customer-contacts/${id}`),@@ -39,10 +70,7 @@ export const path = {customerTypes: `${api}/sales/customer-types`,customFieldOptions: (table: string, fieldId: string) =>generatePath(`${api}/settings/custom-fields/${table}/${fieldId}`),- costCenters: `${api}/accounting/cost-centers`,departments: `${api}/people/departments`,- timecard: `${api}/people/timecard`,- outstandingTrainings: `${api}/resources/trainings`,digitalQuote: (id: string) =>generatePath(`${api}/sales/digital-quote/${id}`),digitalSupplierQuote: (id: string) =>@@ -52,38 +80,28 @@ export const path = {emptyPermissions: `${api}/users/empty-permissions`,failureModes: `${api}/resources/failure-modes`,gauges: `${api}/quality/gauges`,- createCsvLookup: `${api}/csv/create-lookup`,generateCsvColumns: (table: string) =>generatePath(`${api}/ai/csv/${table}/columns`),inspectionDocumentBalloonAnalyze: (inspectionDocumentId: string) =>generatePath(`${api}/quality/inspection-document/${inspectionDocumentId}/balloon-analyze`),- userSelectGroups: (- type: string | undefined,- offset: number,- limit = 25- ) =>- generatePath(- `${api}/users/select/groups?type=${type ?? ""}&offset=${offset}&limit=${limit}`- ),- userSelectGroupMembers: (groupId: string) =>- generatePath(`${api}/users/select/groups/${groupId}/members`),- userSelectSearch: (q: string, type?: string) =>- generatePath(- `${api}/users/select/search?q=${encodeURIComponent(q)}&type=${type ?? ""}`- ),- userSelectResolve: (ids: string[]) =>- generatePath(`${api}/users/select/resolve?ids=${ids.join(",")}`),- userSelectGroupEmails: (groupId: string) =>- generatePath(`${api}/users/select/groups/${groupId}/emails`),item: (type: string) => generatePath(`${api}/item/${type}`),+ itemConfigurable: `${api}/items/configurable`,itemCostRecalculate: (itemId: string) =>generatePath(`${api}/items/${itemId}/recalculate-cost`),- itemConfigurable: `${api}/items/configurable`,+ itemDrawing: `${api}/item/drawing`,itemForecast: (itemId: string, locationId: string) =>generatePath(`${api}/items/${itemId}/${locationId}/forecast`),+ itemMakeMethodStatus: (itemId: string) =>+ generatePath(`${api}/items/${itemId}/make-method-status`),+ itemMpns: `${api}/items/mpns`,itemPostingGroups: `${api}/items/groups`,+ itemRecipeProcesses: (itemId: string) =>+ generatePath(`${api}/items/${itemId}/recipe-processes`),+ jiraCreateIssue: `${api}/integrations/jira/issue/create`,+ jiraLinkExistingIssue: `${api}/integrations/jira/issue/link`,+ jiraSyncNotes: `${api}/integrations/jira/issue/sync-notes`,jobBillOfMaterials: (id: string, withOperations: boolean = false) =>generatePath(`${api}/production/methods/${id}/bom?withOperations=${withOperations}`@@ -100,6 +118,9 @@ export const path = {generatePath(`${api}/kanban/complete/${id}`),kanbanJobLink: (id: string) => generatePath(`${api}/kanban/link/${id}`),kanbanStart: (id: string) => generatePath(`${api}/kanban/start/${id}`),+ linearCreateIssue: `${api}/integrations/linear/issue/create`,+ linearLinkExistingIssue: `${api}/integrations/linear/issue/link`,+ linearSyncNotes: `${api}/integrations/linear/issue/sync-notes`,locations: `${api}/resources/locations`,maintenanceDispatches: `${api}/resources/maintenance`,maintenanceSchedules: `${api}/resources/scheduled-maintenance`,@@ -108,55 +129,50 @@ export const path = {materialFinishes: (substanceId: string) =>generatePath(`${api}/items/finishes/${substanceId}`),materialForms: `${api}/items/forms`,+ materialGrades: (substanceId: string) =>+ generatePath(`${api}/items/grades/${substanceId}`),+ materialSubstances: `${api}/items/substances`,materials: (materialFormId?: string) =>generatePath(`${api}/items/materials${materialFormId ? `?materialFormId=${materialFormId}` : ""}`),- materialGrades: (substanceId: string) =>- generatePath(`${api}/items/grades/${substanceId}`),materialTypes: (substanceId: string, formId: string) =>generatePath(`${api}/items/types/${substanceId}/${formId}`),- materialSubstances: `${api}/items/substances`,- itemMpns: `${api}/items/mpns`,messagingNotify: `${api}/messaging/notify`,+ modelConvertStatus: (modelUploadId: string) =>+ generatePath(`${api}/model/convert-status/${modelUploadId}`),+ modelUpload: `${api}/model/upload`,mrp: (locationId?: string) =>generatePath(`${api}/mrp${locationId ? `?location=${locationId}` : ""}`),- modelConvertStatus: (modelUploadId: string) =>- generatePath(`${api}/model/convert-status/${modelUploadId}`),- modelUpload: `${api}/model/upload`,onShapeBom: (documentId: string, versionId: string, elementId: string) =>generatePath(`${api}/integrations/onshape/d/${documentId}/v/${versionId}/e/${elementId}/bom`),onShapeDocuments: `${api}/integrations/onshape/documents`,- onShapeVersions: (documentId: string) =>- generatePath(`${api}/integrations/onshape/d/${documentId}/versions`),onShapeElements: (documentId: string, versionId: string) =>generatePath(`${api}/integrations/onshape/d/${documentId}/v/${versionId}/elements`),onShapeSync: `${api}/integrations/onshape/sync`,- linearCreateIssue: `${api}/integrations/linear/issue/create`,- linearLinkExistingIssue: `${api}/integrations/linear/issue/link`,- linearSyncNotes: `${api}/integrations/linear/issue/sync-notes`,- jiraCreateIssue: `${api}/integrations/jira/issue/create`,- jiraLinkExistingIssue: `${api}/integrations/jira/issue/link`,- jiraSyncNotes: `${api}/integrations/jira/issue/sync-notes`,+ onShapeVersions: (documentId: string) =>+ generatePath(`${api}/integrations/onshape/d/${documentId}/versions`),outsideOperations: (jobId: string) =>generatePath(`${api}/production/outside-operations/${jobId}`),- purchasingKpi: (key: string) =>- generatePath(`${api}/purchasing/kpi/${key}`),- qualityKpi: (key: string) => generatePath(`${api}/quality/kpi/${key}`),+ outstandingTrainings: `${api}/resources/trainings`,+ paymentTerms: `${api}/accounting/payment-terms`,procedures: `${api}/production/procedures`,processes: `${api}/resources/processes`,- itemRecipeProcesses: (itemId: string) =>- generatePath(`${api}/items/${itemId}/recipe-processes`),productionKpi: (key: string) =>generatePath(`${api}/production/kpi/${key}`),+ purchaseInvoice: (id: string) =>+ generatePath(`${api}/purchase-invoice/${id}`),+ purchasingKpi: (key: string) =>+ generatePath(`${api}/purchasing/kpi/${key}`),+ qualityKpi: (key: string) => generatePath(`${api}/quality/kpi/${key}`),quoteBillOfMaterials: (methodId: string,withOperations: boolean = false@@ -171,22 +187,20 @@ export const path = {generatePath(`${api}/sales/quote/line/${methodId}/bom.csv?withOperations=${withOperations}`),- quotes: `${api}/sales/quotes`,quoteLines: (quoteId: string) =>generatePath(`${api}/sales/quotes/${quoteId}/lines`),+ quotes: `${api}/sales/quotes`,+ resourcesKpi: (key: string) =>+ generatePath(`${api}/resources/kpi/${key}`),rollback: (table: string, id: string) =>generatePath(`${api}/settings/sequence/rollback?table=${table}¤tSequence=${id}`),- resourcesKpi: (key: string) =>- generatePath(`${api}/resources/kpi/${key}`),- purchaseInvoice: (id: string) =>- generatePath(`${api}/purchase-invoice/${id}`),- salesRfq: (id: string) => generatePath(`${api}/sales-rfq/${id}`),salesCustomerOverride: `${api}/sales/customer-override`,salesKpi: (key: string) => generatePath(`${api}/sales/kpi/${key}`),- salesResolvePrice: `${api}/sales/resolve-price`,salesOrders: `${api}/sales/orders`,+ salesResolvePrice: `${api}/sales/resolve-price`,+ salesRfq: (id: string) => generatePath(`${api}/sales-rfq/${id}`),scrapReasons: `${api}/production/scrap-reasons`,search: `${api}/search`,seedQualityDocuments: `${api}/quality/documents/seed`,@@ -198,6 +212,14 @@ export const path = {services: `${api}/items/services`,shifts: (id: string) =>generatePath(`${api}/people/shifts?location=${id}`),+ shippingMethods: `${api}/inventory/shipping-methods`,+ storageTypes: `${api}/inventory/storage-types`,+ storageUnitChildren: (parentId: string) =>+ generatePath(+ `${api}/inventory/storage-unit-children?parentId=${parentId}`+ ),+ storageUnitDescendants: (id: string) =>+ generatePath(`${api}/inventory/storage-unit-descendants?id=${id}`),storageUnits: (id: string) =>generatePath(`${api}/inventory/storage-units?locationId=${id}`),storageUnitsTree: (id: string) =>@@ -208,13 +230,6 @@ export const path = {itemId ? `&itemId=${itemId}` : ""}`),- storageTypes: `${api}/inventory/storage-types`,- storageUnitDescendants: (id: string) =>- generatePath(`${api}/inventory/storage-unit-descendants?id=${id}`),- storageUnitChildren: (parentId: string) =>- generatePath(- `${api}/inventory/storage-unit-children?parentId=${parentId}`- ),supplierContacts: (id: string) =>generatePath(`${api}/purchasing/supplier-contacts/${id}`),supplierLocations: (id: string) =>@@ -224,422 +239,109 @@ export const path = {supplierTypes: `${api}/purchasing/supplier-types`,tags: (table?: string) =>generatePath(`${api}/shared/tags?table=${table}`),+ timecard: `${api}/people/timecard`,unitOfMeasures: `${api}/items/uoms`,- webhookTables: `${api}/webhook/tables`,+ userSelectGroupEmails: (groupId: string) =>+ generatePath(`${api}/users/select/groups/${groupId}/emails`),+ userSelectGroupMembers: (groupId: string) =>+ generatePath(`${api}/users/select/groups/${groupId}/members`),+ userSelectGroups: (+ type: string | undefined,+ offset: number,+ limit = 25+ ) =>+ generatePath(+ `${api}/users/select/groups?type=${type ?? ""}&offset=${offset}&limit=${limit}`+ ),+ userSelectResolve: (ids: string[]) =>+ generatePath(`${api}/users/select/resolve?ids=${ids.join(",")}`),+ userSelectSearch: (q: string, type?: string) =>+ generatePath(+ `${api}/users/select/search?q=${encodeURIComponent(q)}&type=${type ?? ""}`+ ),webhookStripe: `${api}/webhook/stripe`,- workCentersByLocation: (id: string) =>- generatePath(`${api}/resources/work-centers?location=${id}`),+ webhookTables: `${api}/webhook/tables`,workCenters: `${api}/resources/work-centers`,- paymentTerms: `${api}/accounting/payment-terms`,- shippingMethods: `${api}/inventory/shipping-methods`- },- external: {- mes: MES_URL,- mesJobOperationsForJob: (jobId: string) =>- `${MES_URL}/x/operations?search=${encodeURIComponent(jobId)}`,- mesJobOperation: (id: string) => `${MES_URL}/x/operation/${id}`,- mesJobOperationStart: (id: string, type: "Setup" | "Labor" | "Machine") =>- `${MES_URL}/x/start/${id}?type=${type}`,- mesJobOperationComplete: (id: string) => `${MES_URL}/x/end/${id}`+ workCentersByLocation: (id: string) =>+ generatePath(`${api}/resources/work-centers?location=${id}`)},- file: {- cadModel: (id: string) => generatePath(`${file}/model/${id}`),- kanbanLabelsPdf: (- ids: string | string[],- action: "order" | "start" | "complete"- ) => {- const idString = Array.isArray(ids) ? ids.join(",") : ids;- return generatePath(- `${file}/kanban/labels/${action}.pdf?ids=${idString}`- );- },- kanbanQrCode: (id: string, action: "order" | "start" | "complete") =>- generatePath(`${file}/kanban/${id}/${action}.png`),- jobTraveler: (id: string) => generatePath(`${file}/traveler/${id}.pdf`),- jobTravelerByJobId: (jobId: string) =>- generatePath(`${file}/job/${jobId}/traveler.pdf`),- nonConformance: (id: string) => generatePath(`${file}/issue/${id}.pdf`),- operationLabelsPdf: (- id: string,- {- labelSize,- trackedEntityId- }: { labelSize?: string; trackedEntityId?: string } = {}- ) => {- let url = `${file}/operation/${id}/labels.pdf`;- const params = new URLSearchParams();-- if (labelSize) params.append("labelSize", labelSize);- if (trackedEntityId) params.append("trackedEntityId", trackedEntityId);-- const queryString = params.toString();- if (queryString) url += `?${queryString}`;-- return generatePath(url);- },- operationLabelsZpl: (- id: string,- {- labelSize,- trackedEntityId- }: { labelSize?: string; trackedEntityId?: string } = {}- ) => {- let url = `${file}/operation/${id}/labels.zpl`;- const params = new URLSearchParams();-- if (labelSize) params.append("labelSize", labelSize);- if (trackedEntityId) params.append("trackedEntityId", trackedEntityId);-- const queryString = params.toString();- if (queryString) url += `?${queryString}`;-- return generatePath(url);- },- preview: (bucket: string, path: string) =>- generatePath(`${file}/preview/${bucket}/${path}`),- previewImage: (bucket: string, path: string) =>- generatePath(`${file}/preview/image?file=${bucket}/${path}`),- previewFile: (path: string) => generatePath(`${file}/preview/${path}`),- purchaseOrder: (id: string) =>- generatePath(`${file}/purchase-order/${id}.pdf`),- receiptLabelsPdf: (- id: string,- { labelSize, lineId }: { labelSize?: string; lineId?: string } = {}- ) => {- let url = `${file}/receipt/${id}/labels.pdf`;- const params = new URLSearchParams();-- if (labelSize) params.append("labelSize", labelSize);- if (lineId) params.append("lineId", lineId);-- const queryString = params.toString();- if (queryString) url += `?${queryString}`;-- return generatePath(url);- },- receiptLabelsZpl: (- id: string,- { labelSize, lineId }: { labelSize?: string; lineId?: string } = {}- ) => {- let url = `${file}/receipt/${id}/labels.zpl`;- const params = new URLSearchParams();-- if (labelSize) params.append("labelSize", labelSize);- if (lineId) params.append("lineId", lineId);-- const queryString = params.toString();- if (queryString) url += `?${queryString}`;-- return generatePath(url);- },-- salesOrder: (id: string) => generatePath(`${file}/sales-order/${id}.pdf`),- salesInvoice: (id: string) =>- generatePath(`${file}/sales-invoice/${id}.pdf`),- shipment: (id: string) => generatePath(`${file}/shipment/${id}.pdf`),- shipmentLabelsPdf: (- id: string,- { labelSize, lineId }: { labelSize?: string; lineId?: string } = {}- ) => {- let url = `${file}/shipment/${id}/labels.pdf`;- const params = new URLSearchParams();-- if (labelSize) params.append("labelSize", labelSize);- if (lineId) params.append("lineId", lineId);-- const queryString = params.toString();- if (queryString) url += `?${queryString}`;-- return generatePath(url);- },- shipmentLabelsZpl: (- id: string,- { labelSize, lineId }: { labelSize?: string; lineId?: string } = {}- ) => {- let url = `${file}/shipment/${id}/labels.zpl`;- const params = new URLSearchParams();-- if (labelSize) params.append("labelSize", labelSize);- if (lineId) params.append("lineId", lineId);-- const queryString = params.toString();- if (queryString) url += `?${queryString}`;-- return generatePath(url);- },- trackedEntityLabelPdf: (- id: string,- { labelSize }: { labelSize?: string } = {}- ) => {- let url = `${file}/entity/${id}/labels.pdf`;- const params = new URLSearchParams();-- if (labelSize) params.append("labelSize", labelSize);-- const queryString = params.toString();- if (queryString) url += `?${queryString}`;-- return generatePath(url);- },- trackedEntityLabelZpl: (- id: string,- { labelSize }: { labelSize?: string } = {}- ) => {- let url = `${file}/entity/${id}/labels.zpl`;- const params = new URLSearchParams();-- if (labelSize) params.append("labelSize", labelSize);-- const queryString = params.toString();- if (queryString) url += `?${queryString}`;-- return generatePath(url);- },- storageUnitLabelsZpl: (- ids: string | string[],- opts?: { labelSize?: string }- ) => {- const idString = Array.isArray(ids) ? ids.join(",") : ids;- let url = `${file}/storage-unit/labels.zpl?ids=${idString}`;- if (opts?.labelSize) url += `&labelSize=${opts.labelSize}`;- return url;- },- storageUnitLabelsPdf: (- ids: string | string[],- opts?: { labelSize?: string }- ) => {- const idString = Array.isArray(ids) ? ids.join(",") : ids;- let url = `${file}/storage-unit/labels.pdf?ids=${idString}`;- if (opts?.labelSize) url += `&labelSize=${opts.labelSize}`;- return url;- },- stockTransfer: (id: string) =>- generatePath(`${file}/stock-transfer/${id}.pdf`),- stockTransferLabelsPdf: (- id: string,- { labelSize, lineId }: { labelSize?: string; lineId?: string } = {}- ) => {- let url = `${file}/stock-transfer/${id}/labels.pdf`;- const params = new URLSearchParams();-- if (labelSize) params.append("labelSize", labelSize);- if (lineId) params.append("lineId", lineId);-- const queryString = params.toString();- if (queryString) url += `?${queryString}`;-- return generatePath(url);- },- stockTransferLabelsZpl: (- id: string,- { labelSize, lineId }: { labelSize?: string; lineId?: string } = {}- ) => {- let url = `${file}/stock-transfer/${id}/labels.zpl`;- const params = new URLSearchParams();-- if (labelSize) params.append("labelSize", labelSize);- if (lineId) params.append("lineId", lineId);-- const queryString = params.toString();- if (queryString) url += `?${queryString}`;-- return generatePath(url);- },- quote: (id: string) => generatePath(`${file}/quote/${id}.pdf`)- },- legal: {- termsAndConditions: "https://carbon.ms/terms",- privacyPolicy: "https://carbon.ms/privacy"- },- onboarding: {- company: `${onboarding}/company`,- industry: `${onboarding}/industry`,- location: `${onboarding}/location`,- plan: `${onboarding}/plan`,- root: `${onboarding}`,- theme: `${onboarding}/theme`,- user: `${onboarding}/user`- },- authenticatedRoot: x,- selectCompany,- acknowledge: `${x}/acknowledge`,- approvalRules: `${x}/settings/approval-rules`,+ apiDocs: "https://docs.carbon.ms/api-reference",+ apiKey: (id: string) => generatePath(`${x}/settings/api-keys/${id}`),+ apiKeys: `${x}/settings/api-keys`,approvalRule: (id: string) =>generatePath(`${x}/settings/approval-rules/${id}`),- newApprovalRule: (documentType?: string) =>- documentType- ? `${x}/settings/approval-rules/new?type=${documentType}`- : `${x}/settings/approval-rules/new`,- deleteApprovalRule: (id: string) =>- generatePath(`${x}/settings/approval-rules/${id}/delete`),- abilities: `${x}/resources/abilities`,- ability: (id: string) => generatePath(`${x}/resources/ability/${id}`),- account: `${x}/account`,- accountPersonal: `${x}/account/personal`,- accountPassword: `${x}/account/password`,- accounting: `${x}/accounting`,- accountingDefaults: `${x}/accounting/defaults`,- accountingJournals: `${x}/accounting/journals`,- accountingPeriods: `${x}/accounting/periods`,- accountingPeriodsGenerate: `${x}/accounting/periods/generate`,- accountingPeriodClose: (id: string) =>- generatePath(`${x}/accounting/periods/${id}/close`),- accountingPeriodDelete: (id: string) =>- generatePath(`${x}/accounting/periods/${id}/delete`),- accountingSettings: `${x}/settings/accounting`,- journalEntry: (id: string) => generatePath(`${x}/journal-entry/${id}`),- journalEntryDetails: (id: string) =>- generatePath(`${x}/journal-entry/${id}/details`),- newJournalEntry: `${x}/accounting/journals/new`,- postJournalEntry: (id: string) =>- generatePath(`${x}/journal-entry/${id}/post`),- reverseJournalEntry: (id: string) =>- generatePath(`${x}/journal-entry/${id}/reverse`),- journalLineDimensions: (lineId: string) =>- `/api/accounting/journal-line-dimensions/${lineId}`,- accountingGroupsBankAccounts: `${x}/accounting/groups/bank-accounts`,- accountingGroupsFixedAssets: `${x}/accounting/groups/fixed-assets`,- accountingGroupsInventory: `${x}/accounting/groups/inventory`,- accountingGroupsPurchasing: `${x}/accounting/groups/purchasing`,- accountingGroupsSales: `${x}/accounting/groups/sales`,- accountingRoot: `${x}/accounting`,- fixedAssets: `${x}/accounting/fixed-assets`,- fixedAsset: (id: string) => generatePath(`${x}/fixed-asset/${id}`),- fixedAssetDetails: (id: string) =>- generatePath(`${x}/fixed-asset/${id}/details`),- fixedAssetDispose: (id: string) =>- generatePath(`${x}/fixed-asset/${id}/dispose`),- fixedAssetRegister: (id: string) =>- generatePath(`${x}/fixed-asset/${id}/register`),- fixedAssetPurchase: (id: string) =>- generatePath(`${x}/fixed-asset/${id}/purchase`),- fixedAssetSell: (id: string) => generatePath(`${x}/fixed-asset/${id}/sell`),- newFixedAsset: `${x}/accounting/fixed-assets/new`,- deleteFixedAsset: (id: string) =>- generatePath(`${x}/fixed-asset/${id}/delete`),- assetClasses: `${x}/accounting/asset-classes`,- assetClass: (id: string) =>- generatePath(`${x}/accounting/asset-class/${id}`),- newAssetClass: `${x}/accounting/asset-classes/new`,- deleteAssetClass: (id: string) =>- generatePath(`${x}/accounting/asset-class/${id}/delete`),- depreciationRuns: `${x}/accounting/depreciation-runs`,- depreciationRun: (id: string) =>- generatePath(`${x}/depreciation-run/${id}`),- newDepreciationRun: `${x}/accounting/depreciation-runs/new`,- deleteDepreciationRun: (id: string) =>- generatePath(`${x}/depreciation-run/${id}/delete`),- repeatDepreciationRun: (id: string) =>- generatePath(`${x}/depreciation-run/${id}/repeat`),- fixedAssetImport: `${x}/accounting/fixed-asset-import`,- intercompany: `${x}/accounting/intercompany`,- newIntercompanyTransaction: `${x}/accounting/intercompany/new`,- activeMethodVersion: (id: string) =>- generatePath(`${x}/items/methods/versions/activate/${id}`),- activateGauge: (id: string) =>- generatePath(`${x}/quality/gauges/activate/${id}`),+ approvalRules: `${x}/settings/approval-rules`,assemblyInstruction: (id: string) => generatePath(`${x}/assembly/${id}`),- assemblyInstructions: `${x}/production/assemblies`,assemblyInstructionStatus: (id: string) =>generatePath(`${x}/assembly/${id}/status`),- assemblyJobsCancel: (id: string) =>- generatePath(`${x}/assembly/${id}/jobs/cancel`),- assemblyModelConvert: (id: string) =>- generatePath(`${x}/assembly/${id}/model/convert`),- assemblyModelInvalidate: (id: string) =>- generatePath(`${x}/assembly/${id}/model/invalidate`),- assemblyPlanRerun: (id: string) =>- generatePath(`${x}/assembly/${id}/plan/rerun`),- deleteAssemblyInstruction: (id: string) =>- generatePath(`${x}/assembly/delete/${id}`),- newAssemblyInstruction: `${x}/production/assemblies/new`,- newAssemblyInstructionStep: (id: string) =>- generatePath(`${x}/assembly/${id}/steps/new`),assemblyInstructionStep: (id: string, stepId: string) =>generatePath(`${x}/assembly/${id}/steps/${stepId}`),- assemblyInstructionStepMotion: (id: string, stepId: string) =>- generatePath(`${x}/assembly/${id}/steps/motion/${stepId}`),assemblyInstructionStepComponents: (id: string, stepId: string) =>generatePath(`${x}/assembly/${id}/steps/components/${stepId}`),assemblyInstructionStepComponentsReassign: (id: string) =>generatePath(`${x}/assembly/${id}/steps/components/reassign`),- deleteAssemblyInstructionStep: (id: string, stepId: string) =>- generatePath(`${x}/assembly/${id}/steps/delete/${stepId}`),+ assemblyInstructionStepMotion: (id: string, stepId: string) =>+ generatePath(`${x}/assembly/${id}/steps/motion/${stepId}`),assemblyInstructionStepOrder: (id: string) =>generatePath(`${x}/assembly/${id}/steps/order`),assemblyInstructionStepStatus: (id: string, stepId: string) =>generatePath(`${x}/assembly/${id}/steps/status/${stepId}`),- generateAssemblyInstructionSteps: (id: string) =>- generatePath(`${x}/assembly/${id}/steps/generate`),- newAssemblyStepRequirement: (id: string) =>- generatePath(`${x}/assembly/${id}/requirements/new`),- assemblyStepRequirement: (id: string, requirementId: string) =>- generatePath(`${x}/assembly/${id}/requirements/${requirementId}`),- deleteAssemblyStepRequirement: (id: string, requirementId: string) =>- generatePath(`${x}/assembly/${id}/requirements/delete/${requirementId}`),- assemblyStepRequirementOrder: (id: string) =>- generatePath(`${x}/assembly/${id}/requirements/order`),- newAssemblyStepMaterial: (id: string) =>- generatePath(`${x}/assembly/${id}/materials/new`),+ assemblyInstructions: `${x}/production/assemblies`,+ assemblyJobsCancel: (id: string) =>+ generatePath(`${x}/assembly/${id}/jobs/cancel`),+ assemblyModelConvert: (id: string) =>+ generatePath(`${x}/assembly/${id}/model/convert`),+ assemblyModelInvalidate: (id: string) =>+ generatePath(`${x}/assembly/${id}/model/invalidate`),+ assemblyPlanRerun: (id: string) =>+ generatePath(`${x}/assembly/${id}/plan/rerun`),+ assemblyStandardNote: (noteId: string) =>+ generatePath(`${x}/assembly/standard-notes/${noteId}`),assemblyStepMaterial: (id: string, materialId: string) =>generatePath(`${x}/assembly/${id}/materials/${materialId}`),- deleteAssemblyStepMaterial: (id: string, materialId: string) =>- generatePath(`${x}/assembly/${id}/materials/delete/${materialId}`),assemblyStepMaterialOrder: (id: string) =>generatePath(`${x}/assembly/${id}/materials/order`),- newAssemblyUnit: (id: string) =>- generatePath(`${x}/assembly/${id}/units/new`),- updateAssemblyUnit: (id: string, unitId: string) =>- generatePath(`${x}/assembly/${id}/units/${unitId}`),- newAssemblyComponentMapping: (id: string) =>- generatePath(`${x}/assembly/${id}/component-mappings/new`),- deleteAssemblyComponentMapping: (id: string, mappingId: string) =>- generatePath(- `${x}/assembly/${id}/component-mappings/delete/${mappingId}`- ),- autoMatchAssemblyComponents: (id: string) =>- generatePath(`${x}/assembly/${id}/component-mappings/auto`),- deleteAssemblyUnit: (id: string, unitId: string) =>- generatePath(`${x}/assembly/${id}/units/delete/${unitId}`),- newAssemblyStandardNote: `${x}/assembly/standard-notes/new`,- assemblyStandardNote: (noteId: string) =>- generatePath(`${x}/assembly/standard-notes/${noteId}`),- deleteAssemblyStandardNote: (noteId: string) =>- generatePath(`${x}/assembly/standard-notes/delete/${noteId}`),+ assemblyStepRequirement: (id: string, requirementId: string) =>+ generatePath(`${x}/assembly/${id}/requirements/${requirementId}`),+ assemblyStepRequirementOrder: (id: string) =>+ generatePath(`${x}/assembly/${id}/requirements/order`),+ assetClass: (id: string) =>+ generatePath(`${x}/accounting/asset-class/${id}`),+ assetClasses: `${x}/accounting/asset-classes`,+ assignIssueItemEntities: `${x}/issue/item/assign-entities`,attribute: (id: string) => generatePath(`${x}/people/attribute/${id}`),- attributes: `${x}/people/attributes`,- apiDocs: "https://docs.carbon.ms/api-reference",- mcpDocs: "https://docs.carbon.ms/mcp",- apiKey: (id: string) => generatePath(`${x}/settings/api-keys/${id}`),- apiKeys: `${x}/settings/api-keys`,attributeCategory: (id: string) =>generatePath(`${x}/people/attributes/${id}`),attributeCategoryList: (id: string) =>generatePath(`${x}/people/attributes/list/${id}`),+ attributes: `${x}/people/attributes`,auditLog: `${x}/settings/audit-logs`,auditLogDetails: `${x}/settings/audit-logs/details`,+ authenticatedRoot: x,+ autoMatchAssemblyComponents: (id: string) =>+ generatePath(`${x}/assembly/${id}/component-mappings/auto`),+ backups: `${x}/settings/backups`,+ balanceSheet: `${x}/accounting/balance-sheet`,+ balanceSheetLedger: (id: string) =>+ generatePath(`${x}/accounting/balance-sheet/${id}`),batchProperty: (itemId: string) =>generatePath(`${x}/inventory/batch-property/${itemId}/property`),batchPropertyOrder: (itemId: string) =>generatePath(`${x}/inventory/batch-property/${itemId}/property/order`),billing: `${x}/settings/billing`,bulkEditPermissions: `${x}/users/bulk-edit-permissions`,- bulkUpdateItems: `${x}/items/update`,- bulkUpdateProductionPlanning: `${x}/production/planning/update`,- bulkUpdatePurchasingPlanning: `${x}/purchasing/planning/update`,- bulkUpdateProcedure: `${x}/procedure/update`,- bulkUpdateJob: `${x}/job/update`,bulkUpdateIssue: `${x}/issue/update`,- updateIssueItem: `${x}/issue/item/update`,- splitIssueItem: `${x}/issue/item/split`,- assignIssueItemEntities: `${x}/issue/item/assign-entities`,- issueActionTasksOrder: `${x}/issue/action-tasks/order`,bulkUpdateIssueWorkflow: `${x}/issue-workflow/update`,+ bulkUpdateItems: `${x}/items/update`,+ bulkUpdateJob: `${x}/job/update`,+ bulkUpdateProcedure: `${x}/procedure/update`,+ bulkUpdateProductionPlanning: `${x}/production/planning/update`,+ bulkUpdatePurchaseInvoice: `${x}/purchase-invoice/update`,bulkUpdatePurchaseOrder: `${x}/purchase-order/update`,+ bulkUpdatePurchasingPlanning: `${x}/purchasing/planning/update`,bulkUpdatePurchasingRfq: `${x}/purchasing-rfq/update`,- bulkUpdatePurchaseInvoice: `${x}/purchase-invoice/update`,- bulkUpdateQuote: `${x}/quote/update`,bulkUpdateQualityDocument: `${x}/quality-document/update`,+ bulkUpdateQuote: `${x}/quote/update`,bulkUpdateReceiptLine: `${x}/receipt/lines/update`,bulkUpdateSalesInvoice: `${x}/sales-invoice/update`,bulkUpdateSalesOrder: `${x}/sales-order/update`,@@ -649,34 +351,70 @@ export const path = {bulkUpdateSupplierQuote: `${x}/supplier-quote/update`,bulkUpdateTraining: `${x}/training/update`,calibrations: `${x}/quality/calibrations`,+ cancelPurchasingRfq: (id: string) =>+ generatePath(`${x}/purchasing-rfq/${id}/cancel`),+ changeOrder: (id: string) => generatePath(`${x}/items/change-order/${id}`),+ changeOrderAction: (id: string) =>+ generatePath(`${x}/items/change-order/${id}/action`),+ changeOrderActionOrder: (id: string) =>+ generatePath(`${x}/items/change-order/${id}/action/order`),+ changeOrderActionStatus: (id: string, actionId: string) =>+ generatePath(`${x}/items/change-order/${id}/action/${actionId}/status`),+ // Change Order content (Phase 2): BOM change rows + per-assembly targets, and+ // freeform actions. Top-to-bottom: affected items selected first, then+ // per-item staged BOM/BOP/attributes edited in place.+ changeOrderAffected: (id: string) =>+ generatePath(`${x}/items/change-order/${id}/affected`),+ changeOrderAffectedChangeType: (id: string, affectedId: string) =>+ generatePath(+ `${x}/items/change-order/${id}/affected/${affectedId}/change-type`+ ),+ changeOrderAffectedCutover: (id: string, affectedId: string) =>+ generatePath(+ `${x}/items/change-order/${id}/affected/${affectedId}/cutover`+ ),+ // Each affected item is its own line-item detail route (mirrors the sales+ // order line detail `${x}/sales-order/${orderId}/${lineId}/details`). The URL+ // drives selection — refresh + back/forward reselect it.+ changeOrderAffectedItem: (id: string, affectedId: string) =>+ generatePath(`${x}/items/change-order/${id}/${affectedId}/details`),+ // Delete action for a supplier part managed on a CO line (Buy Revision/New+ // Part). Create/edit are reached relatively from the SupplierParts grid.+ changeOrderDeleteSupplierPart: (+ id: string,+ affectedId: string,+ supplierPartId: string+ ) =>+ generatePath(+ `${x}/items/change-order/${id}/${affectedId}/details/${supplierPartId}/delete`+ ),+ changeOrderDetails: (id: string) =>+ generatePath(`${x}/items/change-order/${id}/details`),+ changeOrderRequiredAction: (id: string) =>+ generatePath(`${x}/items/change-order-actions/${id}`),+ // Change Order Actions config (the changeOrderRequiredAction default-action+ // templates) — a sibling of the CO list, like change-order-types above.+ changeOrderRequiredActions: `${x}/items/change-order-actions`,+ changeOrderStatus: (id: string) =>+ generatePath(`${x}/items/change-order/${id}/status`),+ // Change Orders — a sub-area of the Items module. List + config live under+ // /x/items/change-orders; the detail record lives under /x/items/change-order/:id.+ changeOrders: `${x}/items/change-orders`,+ changeOrderType: (id: string) =>+ generatePath(`${x}/items/change-order-types/${id}`),+ // Change Order Types — a sibling of the CO list (not nested under it), so the+ // Items sidebar doesn't highlight both entries via prefix matching.+ changeOrderTypes: `${x}/items/change-order-types`,chartOfAccount: (id: string) =>generatePath(`${x}/accounting/charts/${id}`),chartOfAccounts: `${x}/accounting/charts`,chartOfAccountsLedger: (id: string) =>generatePath(`${x}/accounting/charts/ledger/${id}`),- moveChartOfAccount: (id: string) =>- generatePath(`${x}/accounting/charts/move/${id}`),- costCenter: (id: string) =>- generatePath(`${x}/accounting/cost-centers/${id}`),- costCenters: `${x}/accounting/cost-centers`,- trialBalance: `${x}/accounting/trial-balance`,- trialBalanceLedger: (id: string) =>- generatePath(`${x}/accounting/trial-balance/${id}`),- balanceSheet: `${x}/accounting/balance-sheet`,- balanceSheetLedger: (id: string) =>- generatePath(`${x}/accounting/balance-sheet/${id}`),- incomeStatement: `${x}/accounting/income-statement`,- incomeStatementLedger: (id: string) =>- generatePath(`${x}/accounting/income-statement/${id}`),+ closeIssue: (id: string) => generatePath(`${x}/issue/${id}/close`),+ companies: `${x}/settings/companies`,company: `${x}/settings/company`,companySwitch: (companyId: string) =>generatePath(`${x}/settings/company/switch/${companyId}`),- backups: `${x}/settings/backups`,- companies: `${x}/settings/companies`,- getStarted: `${x}/get-started`,- getStartedPage: (slug: string) => generatePath(`${x}/get-started/${slug}`),- getStartedState: `${x}/get-started/state`,- getStartedEnroll: `${x}/get-started/enroll`,completeTrainingAssignment: (id: string) =>generatePath(`${share}/training/${id}`),configurationParameter: (itemId: string) =>@@ -689,11 +427,7 @@ export const path = {generatePath(`${x}/part/${itemId}/parameter/order`),configurationRule: (itemId: string) =>generatePath(`${x}/part/${itemId}/rule`),- contractor: (id: string) =>- generatePath(`${x}/resources/contractors/${id}`),- contractors: `${x}/resources/contractors`,consumable: (id: string) => generatePath(`${x}/consumable/${id}`),- consumables: `${x}/items/consumables`,consumableCosting: (id: string) =>generatePath(`${x}/consumable/${id}/costing`),consumableDetails: (id: string) =>@@ -711,33 +445,34 @@ export const path = {consumableQuality: (id: string) =>generatePath(`${x}/consumable/${id}/quality`),consumableRoot: `${x}/consumable`,+ consumableRules: (id: string) =>+ generatePath(`${x}/consumable/${id}/rules`),consumableSupplier: (itemId: string, id: string) =>generatePath(`${x}/consumable/${itemId}/purchasing/${id}`),- deleteConsumableSupplier: (itemId: string, id: string) =>- generatePath(`${x}/consumable/${itemId}/purchasing/${id}/delete`),consumableSuppliers: (id: string) =>generatePath(`${x}/consumable/${id}/suppliers`),+ consumables: `${x}/items/consumables`,+ contact: `${x}/people/contact`,+ contractor: (id: string) =>+ generatePath(`${x}/resources/contractors/${id}`),+ contractors: `${x}/resources/contractors`,convertQuoteToOrder: (id: string) =>generatePath(`${x}/quote/${id}/convert`),convertSupplierQuoteToOrder: (id: string) =>generatePath(`${x}/supplier-quote/${id}/convert`),- exchangeRate: (id: string) =>- generatePath(`${x}/accounting/exchange-rates/${id}`),- exchangeRates: `${x}/accounting/exchange-rates`,- dimension: (id: string) => generatePath(`${x}/accounting/dimensions/${id}`),- dimensions: `${x}/accounting/dimensions`,+ costCenter: (id: string) =>+ generatePath(`${x}/accounting/cost-centers/${id}`),+ costCenters: `${x}/accounting/cost-centers`,customer: (id: string) => generatePath(`${x}/customer/${id}`),- customerDetails: (id: string) =>- generatePath(`${x}/customer/${id}/details`),- customerRoot: `${x}/customer`,- customers: `${x}/sales/customers`,- customerAccounts: `${x}/users/customers`,customerAccounting: (id: string) =>generatePath(`${x}/customer/${id}/accounting`),+ customerAccounts: `${x}/users/customers`,customerContact: (customerId: string, id: string) =>generatePath(`${x}/customer/${customerId}/contacts/${id}`),customerContacts: (id: string) =>generatePath(`${x}/customer/${id}/contacts`),+ customerDetails: (id: string) =>+ generatePath(`${x}/customer/${id}/details`),customerLocation: (customerId: string, id: string) =>generatePath(`${x}/customer/${customerId}/locations/${id}`),customerLocations: (id: string) =>@@ -748,26 +483,28 @@ export const path = {),customerPayment: (id: string) =>generatePath(`${x}/customer/${id}/payments`),- customerPortals: `${x}/sales/customer-portals`,customerPortal: (id: string) =>generatePath(`${x}/sales/customer-portals/${id}`),+ customerPortals: `${x}/sales/customer-portals`,+ customerRisks: (id: string) => generatePath(`${x}/customer/${id}/risks`),+ customerRoot: `${x}/customer`,customerShipping: (id: string) =>generatePath(`${x}/customer/${id}/shipping`),- customerTax: (id: string) => generatePath(`${x}/customer/${id}/tax`),- customerRisks: (id: string) => generatePath(`${x}/customer/${id}/risks`),customerStatus: (id: string) =>generatePath(`${x}/sales/customer-statuses/${id}`),customerStatuses: `${x}/sales/customer-statuses`,+ customers: `${x}/sales/customers`,+ customerTax: (id: string) => generatePath(`${x}/customer/${id}/tax`),customerType: (id: string) =>generatePath(`${x}/sales/customer-types/${id}`),customerTypes: `${x}/sales/customer-types`,customField: (tableId: string, id: string) =>generatePath(`${x}/settings/custom-fields/${tableId}/${id}`),+ customFieldList: (id: string) =>+ generatePath(`${x}/settings/custom-fields/${id}`),customFields: `${x}/settings/custom-fields`,customFieldsTable: (table: string) =>generatePath(`${x}/settings/custom-fields/${table}`),- customFieldList: (id: string) =>- generatePath(`${x}/settings/custom-fields/${id}`),deactivateUsers: `${x}/users/deactivate`,defaultRevision: (id: string) =>@@ -776,10 +513,28 @@ export const path = {generatePath(`${x}/resources/abilities/delete/${id}`),deleteAccountingCharts: (id: string) =>generatePath(`${x}/accounting/charts/delete/${id}`),- deleteCostCenter: (id: string) =>- generatePath(`${x}/accounting/cost-centers/delete/${id}`),deleteApiKey: (id: string) =>generatePath(`${x}/settings/api-keys/delete/${id}`),+ deleteApprovalRule: (id: string) =>+ generatePath(`${x}/settings/approval-rules/${id}/delete`),+ deleteAssemblyComponentMapping: (id: string, mappingId: string) =>+ generatePath(+ `${x}/assembly/${id}/component-mappings/delete/${mappingId}`+ ),+ deleteAssemblyInstruction: (id: string) =>+ generatePath(`${x}/assembly/delete/${id}`),+ deleteAssemblyInstructionStep: (id: string, stepId: string) =>+ generatePath(`${x}/assembly/${id}/steps/delete/${stepId}`),+ deleteAssemblyStandardNote: (noteId: string) =>+ generatePath(`${x}/assembly/standard-notes/delete/${noteId}`),+ deleteAssemblyStepMaterial: (id: string, materialId: string) =>+ generatePath(`${x}/assembly/${id}/materials/delete/${materialId}`),+ deleteAssemblyStepRequirement: (id: string, requirementId: string) =>+ generatePath(`${x}/assembly/${id}/requirements/delete/${requirementId}`),+ deleteAssemblyUnit: (id: string, unitId: string) =>+ generatePath(`${x}/assembly/${id}/units/delete/${unitId}`),+ deleteAssetClass: (id: string) =>+ generatePath(`${x}/accounting/asset-class/${id}/delete`),deleteAttribute: (id: string) =>generatePath(`${x}/people/attribute/delete/${id}`),deleteAttributeCategory: (id: string) =>@@ -788,6 +543,18 @@ export const path = {generatePath(`${x}/inventory/batch-property/${itemId}/property/delete/${id}`),+ deleteChangeOrder: (id: string) =>+ generatePath(`${x}/items/change-order/delete/${id}`),+ deleteChangeOrderAction: (id: string, actionId: string) =>+ generatePath(`${x}/items/change-order/${id}/action/delete/${actionId}`),+ deleteChangeOrderAffected: (id: string, affectedId: string) =>+ generatePath(+ `${x}/items/change-order/${id}/affected/delete/${affectedId}`+ ),+ deleteChangeOrderRequiredAction: (id: string) =>+ generatePath(`${x}/items/change-order-actions/delete/${id}`),+ deleteChangeOrderType: (id: string) =>+ generatePath(`${x}/items/change-order-types/delete/${id}`),deleteCompany: (id: string) =>generatePath(`${x}/settings/companies/delete/${id}`),deleteConfigurationParameter: (itemId: string, id: string) =>@@ -796,12 +563,12 @@ export const path = {generatePath(`${x}/part/${itemId}/parameter/group/delete/${id}`),deleteConfigurationRule: (itemId: string, field: string) =>generatePath(`${x}/part/${itemId}/rule/delete/${field}`),+ deleteConsumableSupplier: (itemId: string, id: string) =>+ generatePath(`${x}/consumable/${itemId}/purchasing/${id}/delete`),deleteContractor: (id: string) =>generatePath(`${x}/resources/contractors/delete/${id}`),- deleteExchangeRate: (id: string) =>- generatePath(`${x}/accounting/exchange-rates/delete/${id}`),- deleteDimension: (id: string) =>- generatePath(`${x}/accounting/dimensions/delete/${id}`),+ deleteCostCenter: (id: string) =>+ generatePath(`${x}/accounting/cost-centers/delete/${id}`),deleteCustomer: (id: string) => generatePath(`${x}/customer/${id}/delete`),deleteCustomerContact: (customerId: string, id: string) =>generatePath(`${x}/customer/${customerId}/contacts/delete/${id}`),@@ -811,14 +578,24 @@ export const path = {generatePath(`${x}/part/${id}/sales/customer-parts/delete/${customerPartToItemId}`),+ deleteCustomerPortal: (id: string) =>+ generatePath(`${x}/sales/customer-portals/delete/${id}`),deleteCustomerStatus: (id: string) =>generatePath(`${x}/sales/customer-statuses/delete/${id}`),deleteCustomerType: (id: string) =>generatePath(`${x}/sales/customer-types/delete/${id}`),deleteCustomField: (tableId: string, id: string) =>generatePath(`${x}/settings/custom-fields/${tableId}/delete/${id}`),+ deleteDemandProjections: (itemId: string, locationId: string) =>+ generatePath(+ `${x}/production/projections/delete/${itemId}/${locationId}`+ ),deleteDepartment: (id: string) =>generatePath(`${x}/people/departments/delete/${id}`),+ deleteDepreciationRun: (id: string) =>+ generatePath(`${x}/depreciation-run/${id}/delete`),+ deleteDimension: (id: string) =>+ generatePath(`${x}/accounting/dimensions/delete/${id}`),deleteDocument: (id: string) => generatePath(`${x}/documents/${id}/trash`),deleteDocumentPermanently: (id: string) =>generatePath(`${x}/documents/${id}/delete`),@@ -826,8 +603,12 @@ export const path = {generatePath(`${x}/resources/ability/${abilityId}/employee/delete/${id}`),deleteEmployeeType: (id: string) =>generatePath(`${x}/users/employee-types/delete/${id}`),+ deleteExchangeRate: (id: string) =>+ generatePath(`${x}/accounting/exchange-rates/delete/${id}`),deleteFailureMode: (id: string) =>generatePath(`${x}/resources/failure-modes/delete/${id}`),+ deleteFixedAsset: (id: string) =>+ generatePath(`${x}/fixed-asset/${id}/delete`),deleteGauge: (id: string) =>generatePath(`${x}/quality/gauges/delete/${id}`),deleteGaugeCalibrationRecord: (id: string) =>@@ -837,24 +618,45 @@ export const path = {deleteGroup: (id: string) => generatePath(`${x}/users/groups/delete/${id}`),deleteHoliday: (id: string) =>generatePath(`${x}/people/holidays/delete/${id}`),- deleteTimecard: (id: string) =>- generatePath(`${x}/people/timecard/delete/${id}`),- deleteLocation: (id: string) =>- generatePath(`${x}/resources/locations/delete/${id}`),+ deleteInspectionDocument: (id: string) =>+ generatePath(`${x}/inspection/${id}/delete`),+ deleteInvestigationType: (id: string) =>+ generatePath(`${x}/quality/investigation-types/delete/${id}`),+ deleteIssue: (id: string) => generatePath(`${x}/issue/delete/${id}`),+ deleteIssueAssociation: (id: string, type: string, associationId: string) =>+ generatePath(+ `${x}/issue/${id}/association/delete/${type}/${associationId}`+ ),+ deleteIssueType: (id: string) =>+ generatePath(`${x}/quality/issue-types/delete/${id}`),+ deleteIssueWorkflow: (id: string) =>+ generatePath(`${x}/issue-workflow/delete/${id}`),deleteItem: (id: string) => generatePath(`${x}/items/delete/${id}`),deleteItemPostingGroup: (id: string) =>generatePath(`${x}/items/groups/delete/${id}`),- deleteJournalEntry: (id: string) =>- generatePath(`${x}/journal-entry/${id}/delete`),deleteJob: (id: string) => generatePath(`${x}/job/${id}/delete`),deleteJobMaterial: (jobId: string, id: string) =>generatePath(`${x}/job/methods/${jobId}/material/delete/${id}`),- deleteJobOperationStep: (id: string) =>- generatePath(`${x}/job/methods/operation/step/delete/${id}`),deleteJobOperationParameter: (id: string) =>generatePath(`${x}/job/methods/operation/parameter/delete/${id}`),+ deleteJobOperationStep: (id: string) =>+ generatePath(`${x}/job/methods/operation/step/delete/${id}`),deleteJobOperationTool: (id: string) =>generatePath(`${x}/job/methods/operation/tool/delete/${id}`),+ deleteJournalEntry: (id: string) =>+ generatePath(`${x}/journal-entry/${id}/delete`),+ deleteKanban: (id: string) =>+ generatePath(`${x}/inventory/kanbans/delete/${id}`),+ deleteLocation: (id: string) =>+ generatePath(`${x}/resources/locations/delete/${id}`),+ deleteMaintenanceDispatch: (id: string) =>+ generatePath(`${x}/resources/maintenance/delete/${id}`),+ deleteMaintenanceDispatchEvent: (dispatchId: string, eventId: string) =>+ generatePath(`${x}/maintenance/${dispatchId}/event/${eventId}/delete`),+ deleteMaintenanceDispatchItem: (dispatchId: string, itemId: string) =>+ generatePath(`${x}/maintenance/${dispatchId}/item/${itemId}/delete`),+ deleteMaintenanceSchedule: (id: string) =>+ generatePath(`${x}/resources/scheduled-maintenance/delete/${id}`),deleteMaterialDimension: (id: string) =>generatePath(`${x}/items/dimensions/delete/${id}`),deleteMaterialFinish: (id: string) =>@@ -863,67 +665,47 @@ export const path = {generatePath(`${x}/items/forms/delete/${id}`),deleteMaterialGrade: (id: string) =>generatePath(`${x}/items/grades/delete/${id}`),- deleteMaterialType: (id: string) =>- generatePath(`${x}/items/types/delete/${id}`),- deleteMaterialSubstance: (id: string) =>- generatePath(`${x}/items/substances/delete/${id}`),- deleteMethodMaterial: (id: string) =>- generatePath(`${x}/items/methods/material/delete/${id}`),- deleteMethodOperationStep: (id: string) =>- generatePath(`${x}/items/methods/operation/step/delete/${id}`),- deleteMethodOperationParameter: (id: string) =>- generatePath(`${x}/items/methods/operation/parameter/delete/${id}`),- deleteMethodOperationTool: (id: string) =>- generatePath(`${x}/items/methods/operation/tool/delete/${id}`),- deleteIssue: (id: string) => generatePath(`${x}/issue/delete/${id}`),- deleteIssueAssociation: (id: string, type: string, associationId: string) =>- generatePath(- `${x}/issue/${id}/association/delete/${type}/${associationId}`- ),- deleteIssueWorkflow: (id: string) =>- generatePath(`${x}/issue-workflow/delete/${id}`),- deleteInvestigationType: (id: string) =>- generatePath(`${x}/quality/investigation-types/delete/${id}`),- deleteRequiredAction: (id: string) =>- generatePath(`${x}/quality/required-actions/delete/${id}`),- deleteRisk: (id: string) => generatePath(`${x}/quality/risks/delete/${id}`),- deleteIssueType: (id: string) =>- generatePath(`${x}/quality/issue-types/delete/${id}`),- deleteKanban: (id: string) =>- generatePath(`${x}/inventory/kanbans/delete/${id}`),- deleteMaintenanceDispatch: (id: string) =>- generatePath(`${x}/resources/maintenance/delete/${id}`),- deleteMaintenanceSchedule: (id: string) =>- generatePath(`${x}/resources/scheduled-maintenance/delete/${id}`),+ deleteMaterialSubstance: (id: string) =>+ generatePath(`${x}/items/substances/delete/${id}`),+ deleteMaterialSupplier: (itemId: string, id: string) =>+ generatePath(`${x}/material/${itemId}/purchasing/${id}/delete`),+ deleteMaterialType: (id: string) =>+ generatePath(`${x}/items/types/delete/${id}`),+ deleteMethodMaterial: (id: string) =>+ generatePath(`${x}/items/methods/material/delete/${id}`),+ deleteMethodOperationParameter: (id: string) =>+ generatePath(`${x}/items/methods/operation/parameter/delete/${id}`),+ deleteMethodOperationStep: (id: string) =>+ generatePath(`${x}/items/methods/operation/step/delete/${id}`),+ deleteMethodOperationTool: (id: string) =>+ generatePath(`${x}/items/methods/operation/tool/delete/${id}`),deleteNoQuoteReason: (id: string) =>generatePath(`${x}/sales/no-quote-reasons/delete/${id}`),- deleteCustomerPortal: (id: string) =>- generatePath(`${x}/sales/customer-portals/delete/${id}`),deleteNote: (id: string) => generatePath(`${x}/shared/notes/${id}/delete`),deletePartner: (id: string) =>generatePath(`${x}/resources/partners/delete/${id}`),+ deletePartSupplier: (itemId: string, id: string) =>+ generatePath(`${x}/part/${itemId}/purchasing/${id}/delete`),deletePaymentTerm: (id: string) =>generatePath(`${x}/accounting/payment-terms/delete/${id}`),- deleteStockTransfer: (id: string) =>- generatePath(`${x}/stock-transfer/delete/${id}`),- deleteStockTransferLine: (id: string, lineId: string) =>- generatePath(`${x}/stock-transfer/${id}/line/${lineId}/delete`),+ deletePriceOverride: (id: string) =>+ generatePath(`${x}/sales/price-list/delete/${id}`),+ deletePricingRule: (id: string) =>+ generatePath(`${x}/sales/pricing-rules/delete/${id}`),+ deletePrinterRoute: (id: string) =>+ generatePath(`${x}/settings/printing/${id}/delete`),deleteProcedure: (id: string) =>generatePath(`${x}/procedure/delete/${id}`),- deleteProcedureStep: (id: string, stepId: string) =>- generatePath(`${x}/procedure/${id}/steps/delete/${stepId}`),deleteProcedureParameter: (id: string, parameterId: string) =>generatePath(`${x}/procedure/${id}/parameters/delete/${parameterId}`),+ deleteProcedureStep: (id: string, stepId: string) =>+ generatePath(`${x}/procedure/${id}/steps/delete/${stepId}`),deleteProcess: (id: string) =>generatePath(`${x}/resources/processes/delete/${id}`),deleteProductionEvent: (id: string) =>generatePath(`${x}/job/methods/event/delete/${id}`),deleteProductionQuantity: (id: string) =>generatePath(`${x}/job/methods/quantity/delete/${id}`),- deleteDemandProjections: (itemId: string, locationId: string) =>- generatePath(- `${x}/production/projections/delete/${itemId}/${locationId}`- ),deletePurchaseInvoice: (id: string) =>generatePath(`${x}/purchase-invoice/${id}/delete`),deletePurchaseInvoiceLine: (invoiceId: string, lineId: string) =>@@ -932,6 +714,10 @@ export const path = {generatePath(`${x}/purchase-order/${id}/delete`),deletePurchaseOrderLine: (orderId: string, lineId: string) =>generatePath(`${x}/purchase-order/${orderId}/${lineId}/delete`),+ deletePurchasingRfq: (id: string) =>+ generatePath(`${x}/purchasing-rfq/${id}/delete`),+ deletePurchasingRfqLine: (id: string, lineId: string) =>+ generatePath(`${x}/purchasing-rfq/${id}/${lineId}/delete`),deleteQualityDocument: (id: string) =>generatePath(`${x}/quality-document/delete/${id}`),deleteQualityDocumentStep: (id: string, stepId: string) =>@@ -945,13 +731,16 @@ export const path = {generatePath(`${x}/quote/methods/${quoteId}/${lineId}/material/delete/${id}`),- deleteQuoteOperationStep: (id: string) =>- generatePath(`${x}/quote/methods/operation/step/delete/${id}`),deleteQuoteOperationParameter: (id: string) =>generatePath(`${x}/quote/methods/operation/parameter/delete/${id}`),+ deleteQuoteOperationStep: (id: string) =>+ generatePath(`${x}/quote/methods/operation/step/delete/${id}`),deleteQuoteOperationTool: (id: string) =>generatePath(`${x}/quote/methods/operation/tool/delete/${id}`),deleteReceipt: (id: string) => generatePath(`${x}/receipt/${id}/delete`),+ deleteRequiredAction: (id: string) =>+ generatePath(`${x}/quality/required-actions/delete/${id}`),+ deleteRisk: (id: string) => generatePath(`${x}/quality/risks/delete/${id}`),deleteSalesInvoice: (id: string) =>generatePath(`${x}/sales-invoice/${id}/delete`),deleteSalesInvoiceLine: (invoiceId: string, lineId: string) =>@@ -970,12 +759,20 @@ export const path = {deleteShift: (id: string) =>generatePath(`${x}/people/shifts/delete/${id}`),deleteShipment: (id: string) => generatePath(`${x}/shipment/${id}/delete`),- deleteStorageUnit: (id: string) =>- generatePath(`${x}/inventory/storage-units/delete/${id}`),- deleteStorageType: (id: string) =>- generatePath(`${x}/inventory/storage-types/delete/${id}`),deleteShippingMethod: (id: string) =>generatePath(`${x}/inventory/shipping-methods/delete/${id}`),+ deleteStockTransfer: (id: string) =>+ generatePath(`${x}/stock-transfer/delete/${id}`),+ deleteStockTransferLine: (id: string, lineId: string) =>+ generatePath(`${x}/stock-transfer/${id}/line/${lineId}/delete`),+ deleteStorageRule: (id: string) =>+ generatePath(`${x}/inventory/storage-rules/${id}/delete`),+ deleteStorageType: (id: string) =>+ generatePath(`${x}/inventory/storage-types/delete/${id}`),+ deleteStorageUnit: (id: string) =>+ generatePath(`${x}/inventory/storage-units/delete/${id}`),+ deleteSuggestion: (id: string) =>+ generatePath(`${x}/resources/suggestions/delete/${id}`),deleteSupplier: (id: string) => generatePath(`${x}/supplier/${id}/delete`),deleteSupplierContact: (supplierId: string, id: string) =>generatePath(`${x}/supplier/${supplierId}/contacts/delete/${id}`),@@ -989,8 +786,10 @@ export const path = {generatePath(`${x}/supplier-quote/${id}/${lineId}/delete`),deleteSupplierType: (id: string) =>generatePath(`${x}/purchasing/supplier-types/delete/${id}`),- deleteSuggestion: (id: string) =>- generatePath(`${x}/resources/suggestions/delete/${id}`),+ deleteTimecard: (id: string) =>+ generatePath(`${x}/people/timecard/delete/${id}`),+ deleteToolSupplier: (itemId: string, id: string) =>+ generatePath(`${x}/tool/${itemId}/purchasing/${id}/delete`),deleteTraining: (id: string) => generatePath(`${x}/training/delete/${id}`),deleteTrainingAssignment: (assignmentId: string) =>generatePath(@@ -1001,10 +800,10 @@ export const path = {deleteUom: (id: string) => generatePath(`${x}/items/uom/delete/${id}`),deleteUserAttribute: (id: string) =>generatePath(`${x}/account/${id}/delete/attribute`),- deleteWebhook: (id: string) =>- generatePath(`${x}/settings/webhooks/delete/${id}`),deleteWarehouseTransfer: (id: string) =>generatePath(`${x}/warehouse-transfer/${id}/delete`),+ deleteWebhook: (id: string) =>+ generatePath(`${x}/settings/webhooks/delete/${id}`),deleteWorkCenter: (id: string) =>generatePath(`${x}/resources/work-centers/delete/${id}`),demandProjection: (itemId: string, locationId: string) =>@@ -1012,14 +811,27 @@ export const path = {demandProjections: `${x}/production/projections`,department: (id: string) => generatePath(`${x}/people/departments/${id}`),departments: `${x}/people/departments`,+ depreciationRun: (id: string) =>+ generatePath(`${x}/depreciation-run/${id}`),+ depreciationRuns: `${x}/accounting/depreciation-runs`,+ dimension: (id: string) => generatePath(`${x}/accounting/dimensions/${id}`),+ dimensions: `${x}/accounting/dimensions`,document: (id: string) => generatePath(`${x}/documents/search/${id}`),- documentView: (id: string) =>- generatePath(`${x}/documents/search/view/${id}`),- documents: `${x}/documents/search`,documentFavorite: `${x}/documents/favorite`,documentRestore: (id: string) =>generatePath(`${x}/documents/${id}/restore`),+ documentSections: `${x}/templates/shared`,+ documents: `${x}/documents/search`,documentsTrash: `${x}/documents/search?q=trash`,+ documentTemplate: (type: string) => generatePath(`${x}/templates/${type}`),+ documentTemplates: `${x}/templates`,+ documentView: (id: string) =>+ generatePath(`${x}/documents/search/view/${id}`),+ download: (token: string) => `/download/${token}`,+ downloadError: (reason: string) => `/download/error?reason=${reason}`,+ duplicatePriceList: `${x}/sales/price-list/duplicate`,+ editMaintenanceDispatchEvent: (dispatchId: string, eventId: string) =>+ generatePath(`${x}/maintenance/${dispatchId}/event/${eventId}`),employeeAbility: (abilityId: string, id: string) =>generatePath(`${x}/resources/ability/${abilityId}/employee/${id}`),employeeAccount: (id: string) => generatePath(`${x}/users/employees/${id}`),@@ -1027,53 +839,297 @@ export const path = {employeeType: (id: string) =>generatePath(`${x}/users/employee-types/${id}`),employeeTypes: `${x}/users/employee-types`,- operators: `${x}/users/operators`,- operator: (id: string) => generatePath(`${x}/users/operators/${id}`),- operatorResetPin: (id: string) =>- generatePath(`${x}/users/operators/reset-pin/${id}`),+ exchangeRate: (id: string) =>+ generatePath(`${x}/accounting/exchange-rates/${id}`),+ exchangeRates: `${x}/accounting/exchange-rates`,+ external: {+ mes: MES_URL,+ mesJobOperation: (id: string) => `${MES_URL}/x/operation/${id}`,+ mesJobOperationComplete: (id: string) => `${MES_URL}/x/end/${id}`,+ mesJobOperationStart: (id: string, type: "Setup" | "Labor" | "Machine") =>+ `${MES_URL}/x/start/${id}?type=${type}`,+ mesJobOperationsForJob: (jobId: string) =>+ `${MES_URL}/x/operations?search=${encodeURIComponent(jobId)}`+ },externalCustomer: (id: string) => generatePath(`/share/customer/${id}`),externalCustomerFile: (id: string, path: string) =>generatePath(`/share/customer/${id}/${path}`),externalQuote: (id: string) => generatePath(`/share/quote/${id}`),+ externalScar: (id: string) => generatePath(`/share/scar/${id}`),externalSupplierQuote: (id: string) =>generatePath(`/share/supplier-quote/${id}`),- externalScar: (id: string) => generatePath(`/share/scar/${id}`),externalTraining: (assignmentId: string) =>generatePath(`/share/training/${assignmentId}`),- feedback: `${x}/feedback`,failureMode: (id: string) =>generatePath(`${x}/resources/failure-modes/${id}`),failureModes: `${x}/resources/failure-modes`,+ feedback: `${x}/feedback`,+ file: {+ cadModel: (id: string) => generatePath(`${file}/model/${id}`),+ jobTraveler: (id: string) => generatePath(`${file}/traveler/${id}.pdf`),+ jobTravelerByJobId: (jobId: string) =>+ generatePath(`${file}/job/${jobId}/traveler.pdf`),+ kanbanLabelsPdf: (+ ids: string | string[],+ action: "order" | "start" | "complete"+ ) => {+ const idString = Array.isArray(ids) ? ids.join(",") : ids;+ return generatePath(+ `${file}/kanban/labels/${action}.pdf?ids=${idString}`+ );+ },+ kanbanQrCode: (id: string, action: "order" | "start" | "complete") =>+ generatePath(`${file}/kanban/${id}/${action}.png`),+ nonConformance: (id: string) => generatePath(`${file}/issue/${id}.pdf`),+ operationLabelsPdf: (+ id: string,+ {+ labelSize,+ trackedEntityId+ }: { labelSize?: string; trackedEntityId?: string } = {}+ ) => {+ let url = `${file}/operation/${id}/labels.pdf`;+ const params = new URLSearchParams();++ if (labelSize) params.append("labelSize", labelSize);+ if (trackedEntityId) params.append("trackedEntityId", trackedEntityId);++ const queryString = params.toString();+ if (queryString) url += `?${queryString}`;++ return generatePath(url);+ },+ operationLabelsZpl: (+ id: string,+ {+ labelSize,+ trackedEntityId+ }: { labelSize?: string; trackedEntityId?: string } = {}+ ) => {+ let url = `${file}/operation/${id}/labels.zpl`;+ const params = new URLSearchParams();++ if (labelSize) params.append("labelSize", labelSize);+ if (trackedEntityId) params.append("trackedEntityId", trackedEntityId);++ const queryString = params.toString();+ if (queryString) url += `?${queryString}`;++ return generatePath(url);+ },+ preview: (bucket: string, path: string) =>+ generatePath(`${file}/preview/${bucket}/${path}`),+ previewFile: (path: string) => generatePath(`${file}/preview/${path}`),+ previewImage: (bucket: string, path: string) =>+ generatePath(`${file}/preview/image?file=${bucket}/${path}`),+ purchaseOrder: (id: string) =>+ generatePath(`${file}/purchase-order/${id}.pdf`),+ quote: (id: string) => generatePath(`${file}/quote/${id}.pdf`),+ receiptLabelsPdf: (+ id: string,+ { labelSize, lineId }: { labelSize?: string; lineId?: string } = {}+ ) => {+ let url = `${file}/receipt/${id}/labels.pdf`;+ const params = new URLSearchParams();++ if (labelSize) params.append("labelSize", labelSize);+ if (lineId) params.append("lineId", lineId);++ const queryString = params.toString();+ if (queryString) url += `?${queryString}`;++ return generatePath(url);+ },+ receiptLabelsZpl: (+ id: string,+ { labelSize, lineId }: { labelSize?: string; lineId?: string } = {}+ ) => {+ let url = `${file}/receipt/${id}/labels.zpl`;+ const params = new URLSearchParams();++ if (labelSize) params.append("labelSize", labelSize);+ if (lineId) params.append("lineId", lineId);++ const queryString = params.toString();+ if (queryString) url += `?${queryString}`;++ return generatePath(url);+ },+ salesInvoice: (id: string) =>+ generatePath(`${file}/sales-invoice/${id}.pdf`),++ salesOrder: (id: string) => generatePath(`${file}/sales-order/${id}.pdf`),+ shipment: (id: string) => generatePath(`${file}/shipment/${id}.pdf`),+ shipmentLabelsPdf: (+ id: string,+ { labelSize, lineId }: { labelSize?: string; lineId?: string } = {}+ ) => {+ let url = `${file}/shipment/${id}/labels.pdf`;+ const params = new URLSearchParams();++ if (labelSize) params.append("labelSize", labelSize);+ if (lineId) params.append("lineId", lineId);++ const queryString = params.toString();+ if (queryString) url += `?${queryString}`;++ return generatePath(url);+ },+ shipmentLabelsZpl: (+ id: string,+ { labelSize, lineId }: { labelSize?: string; lineId?: string } = {}+ ) => {+ let url = `${file}/shipment/${id}/labels.zpl`;+ const params = new URLSearchParams();++ if (labelSize) params.append("labelSize", labelSize);+ if (lineId) params.append("lineId", lineId);++ const queryString = params.toString();+ if (queryString) url += `?${queryString}`;++ return generatePath(url);+ },+ stockTransfer: (id: string) =>+ generatePath(`${file}/stock-transfer/${id}.pdf`),+ stockTransferLabelsPdf: (+ id: string,+ { labelSize, lineId }: { labelSize?: string; lineId?: string } = {}+ ) => {+ let url = `${file}/stock-transfer/${id}/labels.pdf`;+ const params = new URLSearchParams();++ if (labelSize) params.append("labelSize", labelSize);+ if (lineId) params.append("lineId", lineId);++ const queryString = params.toString();+ if (queryString) url += `?${queryString}`;++ return generatePath(url);+ },+ stockTransferLabelsZpl: (+ id: string,+ { labelSize, lineId }: { labelSize?: string; lineId?: string } = {}+ ) => {+ let url = `${file}/stock-transfer/${id}/labels.zpl`;+ const params = new URLSearchParams();++ if (labelSize) params.append("labelSize", labelSize);+ if (lineId) params.append("lineId", lineId);++ const queryString = params.toString();+ if (queryString) url += `?${queryString}`;++ return generatePath(url);+ },+ storageUnitLabelsPdf: (+ ids: string | string[],+ opts?: { labelSize?: string }+ ) => {+ const idString = Array.isArray(ids) ? ids.join(",") : ids;+ let url = `${file}/storage-unit/labels.pdf?ids=${idString}`;+ if (opts?.labelSize) url += `&labelSize=${opts.labelSize}`;+ return url;+ },+ storageUnitLabelsZpl: (+ ids: string | string[],+ opts?: { labelSize?: string }+ ) => {+ const idString = Array.isArray(ids) ? ids.join(",") : ids;+ let url = `${file}/storage-unit/labels.zpl?ids=${idString}`;+ if (opts?.labelSize) url += `&labelSize=${opts.labelSize}`;+ return url;+ },+ trackedEntityLabelPdf: (+ id: string,+ { labelSize }: { labelSize?: string } = {}+ ) => {+ let url = `${file}/entity/${id}/labels.pdf`;+ const params = new URLSearchParams();++ if (labelSize) params.append("labelSize", labelSize);++ const queryString = params.toString();+ if (queryString) url += `?${queryString}`;++ return generatePath(url);+ },+ trackedEntityLabelZpl: (+ id: string,+ { labelSize }: { labelSize?: string } = {}+ ) => {+ let url = `${file}/entity/${id}/labels.zpl`;+ const params = new URLSearchParams();++ if (labelSize) params.append("labelSize", labelSize);++ const queryString = params.toString();+ if (queryString) url += `?${queryString}`;++ return generatePath(url);+ }+ },fiscalYears: `${x}/accounting/years`,- inspectionDocument: (id: string) => generatePath(`${x}/inspection/${id}`),- inspectionDocuments: `${x}/quality/inspection`,- deleteInspectionDocument: (id: string) =>- generatePath(`${x}/inspection/${id}/delete`),- newInspectionDocument: `${x}/quality/inspection/new`,- saveInspectionDocument: (id: string) =>- generatePath(`${x}/inspection/${id}/save`),- updateInspectionDocumentName: (id: string) =>- generatePath(`${x}/inspection/${id}/update-name`),+ fixedAsset: (id: string) => generatePath(`${x}/fixed-asset/${id}`),+ fixedAssetDetails: (id: string) =>+ generatePath(`${x}/fixed-asset/${id}/details`),+ fixedAssetDispose: (id: string) =>+ generatePath(`${x}/fixed-asset/${id}/dispose`),+ fixedAssetImport: `${x}/accounting/fixed-asset-import`,+ fixedAssetPurchase: (id: string) =>+ generatePath(`${x}/fixed-asset/${id}/purchase`),+ fixedAssetRegister: (id: string) =>+ generatePath(`${x}/fixed-asset/${id}/register`),+ fixedAssetSell: (id: string) => generatePath(`${x}/fixed-asset/${id}/sell`),+ fixedAssets: `${x}/accounting/fixed-assets`,gauge: (id: string) => generatePath(`${x}/quality/gauges/${id}`),- gauges: `${x}/quality/gauges`,gaugeCalibrationRecord: (id: string) =>generatePath(`${x}/quality/calibrations/${id}`),gaugeCalibrationRecords: `${x}/quality/calibrations`,gaugeDeactivate: (id: string) =>generatePath(`${x}/quality/gauges/deactivate/${id}`),- gaugeTypes: `${x}/quality/gauge-types`,+ gauges: `${x}/quality/gauges`,gaugeType: (id: string) => generatePath(`${x}/quality/gauge-types/${id}`),+ gaugeTypes: `${x}/quality/gauge-types`,+ generateAssemblyInstructionSteps: (id: string) =>+ generatePath(`${x}/assembly/${id}/steps/generate`),+ getStarted: `${x}/get-started`,+ getStartedEnroll: `${x}/get-started/enroll`,+ getStartedPage: (slug: string) => generatePath(`${x}/get-started/${slug}`),+ getStartedState: `${x}/get-started/state`,group: (id: string) => generatePath(`${x}/users/groups/${id}`),groups: `${x}/users/groups`,holiday: (id: string) => generatePath(`${x}/people/holidays/${id}`),holidays: `${x}/people/holidays`,import: (tableId: string) => generatePath(`${x}/shared/import/${tableId}`),+ inboundInspection: (id: string) =>+ generatePath(`${x}/quality/inbound-inspections/${id}`),+ inboundInspections: `${x}/quality/inbound-inspections`,+ incomeStatement: `${x}/accounting/income-statement`,+ incomeStatementLedger: (id: string) =>+ generatePath(`${x}/accounting/income-statement/${id}`),+ inspectionDocument: (id: string) => generatePath(`${x}/inspection/${id}`),+ inspectionDocuments: `${x}/quality/inspection`,integration: (id: string) =>generatePath(`${x}/settings/integrations/${id}`),integrationDeactivate: (id: string) =>generatePath(`${x}/settings/integrations/deactivate/${id}`),integrations: `${x}/settings/integrations`,+ intercompany: `${x}/accounting/intercompany`,inventory: `${x}/inventory/quantities`,+ inventoryCount: (id: string) => generatePath(`${x}/inventory-count/${id}`),+ inventoryCountConfirm: (id: string) =>+ generatePath(`${x}/inventory-count/${id}/confirm`),+ inventoryCountDelete: (id: string) =>+ generatePath(`${x}/inventory-count/${id}/delete`),+ inventoryCountLineUpdate: `${x}/inventory-count/lines/update`,+ inventoryCountPost: (id: string) =>+ generatePath(`${x}/inventory-count/${id}/post`),+ inventoryCountRectify: (id: string) =>+ generatePath(`${x}/inventory-count/${id}/rectify`),+ inventoryCountReopen: (id: string) =>+ generatePath(`${x}/inventory-count/${id}/reopen`),+ inventoryCounts: `${x}/inventory/inventory-count`,inventoryItem: (id: string) =>generatePath(`${x}/inventory/quantities/${id}/details`),inventoryItemActivity: (id: string) =>@@ -1081,40 +1137,40 @@ export const path = {inventoryItemAdjustment: (id: string) =>generatePath(`${x}/inventory/quantities/${id}/adjustment`),inventoryRoot: `${x}/inventory`,+ inventorySettings: `${x}/settings/inventory`,inventoryValuation: `${x}/inventory/valuation`,inventoryValuationReconcile: `${x}/inventory/valuation/reconcile`,- stockMovements: `${x}/inventory/stock-movements`,- inventorySettings: `${x}/settings/inventory`,+ investigationType: (id: string) =>+ generatePath(`${x}/quality/investigation-types/${id}`),+ investigationTypes: `${x}/quality/investigation-types`,invoicing: `${x}/invoicing`,invoicingPurchasing: `${x}/invoicing/purchasing`,invoicingSales: `${x}/invoicing/sales`,- issues: `${x}/quality/issues`,issue: (id: string) => generatePath(`${x}/issue/${id}`),- issueDetails: (id: string) => generatePath(`${x}/issue/${id}/details`),- issueStatus: (id: string) => generatePath(`${x}/issue/${id}/status`),- closeIssue: (id: string) => generatePath(`${x}/issue/${id}/close`),+ issueActionDueDate: (id: string) =>+ generatePath(`${x}/issue/action/${id}/due-date`),+ issueActionProcesses: (id: string) =>+ generatePath(`${x}/issue/action/${id}/processes`),issueActions: (id: string) => generatePath(`${x}/issue/${id}`),+ issueActionTasksOrder: `${x}/issue/action-tasks/order`,+ issueDetails: (id: string) => generatePath(`${x}/issue/${id}/details`),issueDispositions: (id: string) =>generatePath(`${x}/issue/${id}/dispositions`),+ issueReview: (id: string) => generatePath(`${x}/issue/${id}/review`),+ issueStatus: (id: string) => generatePath(`${x}/issue/${id}/status`),+ issues: `${x}/quality/issues`,issueTaskStatus: (id: string) =>generatePath(`${x}/issue/task/${id}/status`),issueTaskSupplier: `${x}/issue/task/supplier`,- issueActionDueDate: (id: string) =>- generatePath(`${x}/issue/action/${id}/due-date`),- issueActionProcesses: (id: string) =>- generatePath(`${x}/issue/action/${id}/processes`),- issueReview: (id: string) => generatePath(`${x}/issue/${id}/review`),- issueWorkflow: (id: string) => generatePath(`${x}/issue-workflow/${id}`),- issueWorkflows: `${x}/quality/issue-workflows`,- investigationType: (id: string) =>- generatePath(`${x}/quality/investigation-types/${id}`),- investigationTypes: `${x}/quality/investigation-types`,issueType: (id: string) => generatePath(`${x}/quality/issue-types/${id}`),issueTypes: `${x}/quality/issue-types`,- items: `${x}/items`,+ issueWorkflow: (id: string) => generatePath(`${x}/issue-workflow/${id}`),+ issueWorkflows: `${x}/quality/issue-workflows`,itemCostUpdate: (id: string) => generatePath(`${x}/items/cost/${id}`),itemPostingGroup: (id: string) => generatePath(`${x}/items/groups/${id}`),itemPostingGroups: `${x}/items/groups`,+ itemProperties: (id: string) => generatePath(`${x}/items/${id}/properties`),+ items: `${x}/items`,itemsSettings: `${x}/settings/items`,job: (id: string) => generatePath(`${x}/job/${id}`),jobBatchNumber: (id: string) => generatePath(`${x}/job/${id}/batch`),@@ -1124,63 +1180,67 @@ export const path = {jobDetails: (id: string) => generatePath(`${x}/job/${id}/details`),jobInspectionSteps: (id: string) =>generatePath(`${x}/job/${id}/steps?filter=type:eq:Inspection`),+ jobMakeMethod: (jobId: string, makeMethodId: string) =>+ generatePath(`${x}/job/${jobId}/make/${makeMethodId}`),jobMaterial: (jobId: string, id: string) =>generatePath(`${x}/job/methods/${jobId}/material/${id}`),jobMaterials: (id: string) => generatePath(`${x}/job/${id}/materials`),+ jobMaterialsOrder: `${x}/job/methods/material/order`,jobMethod: (jobId: string, methodId: string) =>generatePath(`${x}/job/${jobId}/method/${methodId}`),- jobMakeMethod: (jobId: string, makeMethodId: string) =>- generatePath(`${x}/job/${jobId}/make/${makeMethodId}`),- jobMaterialsOrder: `${x}/job/methods/material/order`,jobMethodGet: `${x}/job/methods/get`,jobMethodSave: `${x}/job/methods/save`,jobOperation: (jobId: string, id: string) =>generatePath(`${x}/job/methods/${jobId}/operation/${id}`),- jobOperations: (id: string) => generatePath(`${x}/job/${id}/operations`),- jobOperationsOrder: (jobId: string) =>- generatePath(`${x}/job/methods/${jobId}/operation/order`),- jobOperationsDelete: (jobId: string) =>- generatePath(`${x}/job/methods/${jobId}/operation/delete`),- jobOperationStep: (id: string) =>- generatePath(`${x}/job/methods/operation/step/${id}`),- jobOperationStepOrder: (operationId: string) =>- generatePath(`${x}/job/methods/operation/${operationId}/step/order`),+ jobOperationDueDate: `${x}/job/methods/operation/due-date`,jobOperationParameter: (id: string) =>generatePath(`${x}/job/methods/operation/parameter/${id}`),jobOperationProcedureSync: `${x}/job/methods/operation/procedure/sync`,- jobOperationTool: (id: string) =>- generatePath(`${x}/job/methods/operation/tool/${id}`),- jobOperationDueDate: `${x}/job/methods/operation/due-date`,jobOperationStatus: `${x}/job/methods/operation/status`,+ jobOperationStep: (id: string) =>+ generatePath(`${x}/job/methods/operation/step/${id}`),+ jobOperationStepOrder: (operationId: string) =>+ generatePath(`${x}/job/methods/operation/${operationId}/step/order`),jobOperationStepRecords: (id: string) =>generatePath(`${x}/job/${id}/steps`),+ jobOperations: (id: string) => generatePath(`${x}/job/${id}/operations`),+ jobOperationsDelete: (jobId: string) =>+ generatePath(`${x}/job/methods/${jobId}/operation/delete`),+ jobOperationsOrder: (jobId: string) =>+ generatePath(`${x}/job/methods/${jobId}/operation/order`),+ jobOperationTool: (id: string) =>+ generatePath(`${x}/job/methods/operation/tool/${id}`),jobProductionEvent: (jobId: string, eventId: string) =>generatePath(`${x}/job/${jobId}/events/${eventId}`),jobProductionEvents: (id: string) => generatePath(`${x}/job/${id}/events`),jobProductionQuantities: (id: string) =>generatePath(`${x}/job/${id}/quantities`),- jobs: `${x}/production/jobs`,jobRecalculate: (id: string) => generatePath(`${x}/job/${id}/recalculate`),jobRelease: (id: string) => generatePath(`${x}/job/${id}/release`),jobStatus: (id: string) => generatePath(`${x}/job/${id}/status`),+ jobs: `${x}/production/jobs`,+ journalEntry: (id: string) => generatePath(`${x}/journal-entry/${id}`),+ journalEntryDetails: (id: string) =>+ generatePath(`${x}/journal-entry/${id}/details`),+ journalLineDimensions: (lineId: string) =>+ `/api/accounting/journal-line-dimensions/${lineId}`,kanban: (id: string) => generatePath(`${x}/inventory/kanbans/${id}`),kanbans: `${x}/inventory/kanbans`,- documentTemplates: `${x}/templates`,- documentSections: `${x}/templates/shared`,- documentTemplate: (type: string) => generatePath(`${x}/templates/${type}`),- manualPrint: `${x}/print`,+ legal: {+ privacyPolicy: "https://carbon.ms/privacy",+ termsAndConditions: "https://carbon.ms/terms"+ },location: (id: string) => generatePath(`${x}/resources/locations/${id}`),locations: `${x}/resources/locations`,login: "/login",- logout: "/logout",- download: (token: string) => `/download/${token}`,- downloadError: (reason: string) => `/download/error?reason=${reason}`,logos: `${x}/settings/logos`,+ logout: "/logout",maintenanceDispatch: (id: string) => generatePath(`${x}/maintenance/${id}`),maintenanceDispatchComments: (id: string) =>generatePath(`${x}/maintenance/${id}/comments`),maintenanceDispatchEvents: (id: string) =>generatePath(`${x}/maintenance/${id}/events`),+ maintenanceDispatches: `${x}/resources/maintenance`,maintenanceDispatchItems: (id: string) =>generatePath(`${x}/maintenance/${id}/items`),maintenanceDispatchStatus: (id: string) =>@@ -1188,24 +1248,12 @@ export const path = {maintenanceDispatchUpdate: `${x}/maintenance/update`,maintenanceDispatchWorkCenters: (id: string) =>generatePath(`${x}/maintenance/${id}/work-centers`),- newMaintenanceDispatchItem: (dispatchId: string) =>- generatePath(`${x}/maintenance/${dispatchId}/item/new`),- deleteMaintenanceDispatchItem: (dispatchId: string, itemId: string) =>- generatePath(`${x}/maintenance/${dispatchId}/item/${itemId}/delete`),- newMaintenanceDispatchEvent: (dispatchId: string) =>- generatePath(`${x}/maintenance/${dispatchId}/event/new`),- editMaintenanceDispatchEvent: (dispatchId: string, eventId: string) =>- generatePath(`${x}/maintenance/${dispatchId}/event/${eventId}`),- deleteMaintenanceDispatchEvent: (dispatchId: string, eventId: string) =>- generatePath(`${x}/maintenance/${dispatchId}/event/${eventId}/delete`),- addAndIssueMaintenanceDispatchItem: (dispatchId: string) =>- generatePath(`${x}/maintenance/${dispatchId}/add-and-issue`),- maintenanceDispatches: `${x}/resources/maintenance`,maintenanceSchedule: (id: string) =>generatePath(`${x}/resources/scheduled-maintenance/${id}`),maintenanceSchedules: `${x}/resources/scheduled-maintenance`,makeMethodGet: `${x}/items/methods/get`,makeMethodSave: `${x}/items/methods/save`,+ manualPrint: `${x}/print`,markTrainingComplete: `${x}/resources/assignments/complete`,material: (id: string) => generatePath(`${x}/material/${id}`),materialCosting: (id: string) =>@@ -1221,8 +1269,6 @@ export const path = {materialForms: `${x}/items/forms`,materialGrade: (id: string) => generatePath(`${x}/items/grades/${id}`),materialGrades: `${x}/items/grades`,- materialType: (id: string) => generatePath(`${x}/items/types/${id}`),- materialTypes: `${x}/items/types`,materialInventory: (id: string) =>generatePath(`${x}/material/${id}/inventory`),materialInventoryLocation: (id: string, locationId: string) =>@@ -1238,73 +1284,114 @@ export const path = {materialQuality: (id: string) =>generatePath(`${x}/material/${id}/quality`),materialRoot: `${x}/material`,+ materialRules: (id: string) => generatePath(`${x}/material/${id}/rules`),+ materialSubstance: (id: string) =>+ generatePath(`${x}/items/substances/${id}`),+ materialSubstances: `${x}/items/substances`,materialSupplier: (itemId: string, id: string) =>generatePath(`${x}/material/${itemId}/purchasing/${id}`),- deleteMaterialSupplier: (itemId: string, id: string) =>- generatePath(`${x}/material/${itemId}/purchasing/${id}/delete`),materialSuppliers: (id: string) =>generatePath(`${x}/material/${id}/suppliers`),materials: `${x}/items/materials`,- materialSubstance: (id: string) =>- generatePath(`${x}/items/substances/${id}`),- materialSubstances: `${x}/items/substances`,+ materialType: (id: string) => generatePath(`${x}/items/types/${id}`),+ materialTypes: `${x}/items/types`,+ mcpDocs: "https://docs.carbon.ms/mcp",+ // Credit / Debit memos — payment-shaped documents (the `memo` table). The+ // list lives in the invoicing nav beside Payments; details mirror payments.+ memo: (id: string) => generatePath(`${x}/credits/${id}`),+ memoDelete: (id: string) => generatePath(`${x}/credits/${id}/delete`),+ memoNew: `${x}/credits/new`,+ memoPost: (id: string) => generatePath(`${x}/credits/${id}/post`),+ memos: `${x}/invoicing/credits`,+ memoVoid: (id: string) => generatePath(`${x}/credits/${id}/void`),methodMaterial: (id: string) =>generatePath(`${x}/items/methods/material/${id}`),methodMaterials: `${x}/items/methods/materials`,methodMaterialsOrder: `${x}/items/methods/material/order`,methodOperation: (id: string) =>generatePath(`${x}/items/methods/operation/${id}`),- methodOperations: `${x}/items/methods/operations`,- methodOperationsOrder: `${x}/items/methods/operation/order`,- methodOperationsDelete: `${x}/items/methods/operation/delete`,+ methodOperationParameter: (id: string) =>+ generatePath(`${x}/items/methods/operation/parameter/${id}`),methodOperationStep: (id: string) =>generatePath(`${x}/items/methods/operation/step/${id}`),methodOperationStepOrder: (operationId: string) =>generatePath(`${x}/items/methods/operation/${operationId}/step/order`),- methodOperationParameter: (id: string) =>- generatePath(`${x}/items/methods/operation/parameter/${id}`),+ methodOperations: `${x}/items/methods/operations`,+ methodOperationsDelete: `${x}/items/methods/operation/delete`,+ methodOperationsOrder: `${x}/items/methods/operation/order`,methodOperationTool: (id: string) =>generatePath(`${x}/items/methods/operation/tool/${id}`),+ moveChartOfAccount: (id: string) =>+ generatePath(`${x}/accounting/charts/move/${id}`),newAbility: `${x}/resources/abilities/new`,newApiKey: `${x}/settings/api-keys/new`,+ newApprovalRule: (documentType?: string) =>+ documentType+ ? `${x}/settings/approval-rules/new?type=${documentType}`+ : `${x}/settings/approval-rules/new`,+ newAssemblyComponentMapping: (id: string) =>+ generatePath(`${x}/assembly/${id}/component-mappings/new`),+ newAssemblyInstruction: `${x}/production/assemblies/new`,+ newAssemblyInstructionStep: (id: string) =>+ generatePath(`${x}/assembly/${id}/steps/new`),+ newAssemblyStandardNote: `${x}/assembly/standard-notes/new`,+ newAssemblyStepMaterial: (id: string) =>+ generatePath(`${x}/assembly/${id}/materials/new`),+ newAssemblyStepRequirement: (id: string) =>+ generatePath(`${x}/assembly/${id}/requirements/new`),+ newAssemblyUnit: (id: string) =>+ generatePath(`${x}/assembly/${id}/units/new`),+ newAssetClass: `${x}/accounting/asset-classes/new`,newAttribute: `${x}/people/attribute/new`,newAttributeCategory: `${x}/people/attributes/new`,newAttributeForCategory: (id: string) =>generatePath(`${x}/people/attributes/list/${id}/new`),newBatch: `${x}/inventory/batches/new`,newBulkJob: `${x}/job/bulk/new`,+ // Create form lives at its own top-level route (like /x/part/new and+ // /x/sales-order/new) so it renders with the app sidebar rather than nested+ // under the Items module layout.+ newChangeOrder: `${x}/change-order/new`,+ // One-click create-a-CO-for-this-item (POST) — used by the part version+ // dropdown and the new-revision modal.+ newChangeOrderFromItem: (itemId: string) =>+ generatePath(`${x}/items/change-order/new-from-item/${itemId}`),+ newChangeOrderRequiredAction: `${x}/items/change-order-actions/new`,+ newChangeOrderType: `${x}/items/change-order-types/new`,newChartOfAccount: `${x}/accounting/charts/new`,newChartOfAccountGroup: `${x}/accounting/charts/new-group`,- newCostCenter: `${x}/accounting/cost-centers/new`,newCompany: `${x}/settings/company/new`,newCompanyInGroup: `${x}/settings/companies/new`,newConsumable: `${x}/consumable/new`,newConsumableSupplier: (id: string) =>generatePath(`${x}/consumable/${id}/purchasing/new`),newContractor: `${x}/resources/contractors/new`,- newExchangeRate: `${x}/accounting/exchange-rates/new`,- newDimension: `${x}/accounting/dimensions/new`,+ newCostCenter: `${x}/accounting/cost-centers/new`,newCustomer: `${x}/customer/new`,newCustomerAccount: `${x}/users/customers/new`,newCustomerContact: (id: string) =>generatePath(`${x}/customer/${id}/contacts/new`),newCustomerLocation: (id: string) =>generatePath(`${x}/customer/${id}/locations/new`),+ newCustomerPart: (id: string) =>+ generatePath(`${x}/part/${id}/sales/customer-parts/new`),+ newCustomerPortal: `${x}/sales/customer-portals/new`,newCustomerStatus: `${x}/sales/customer-statuses/new`,newCustomerType: `${x}/sales/customer-types/new`,newCustomField: (tableId: string) =>generatePath(`${x}/settings/custom-fields/${tableId}/new`),- newCustomerPart: (id: string) =>- generatePath(`${x}/part/${id}/sales/customer-parts/new`),newDemandProjection: `${x}/production/projections/new`,newDepartment: `${x}/people/departments/new`,+ newDepreciationRun: `${x}/accounting/depreciation-runs/new`,+ newDimension: `${x}/accounting/dimensions/new`,newDocument: `${x}/documents/new`,newEmployee: `${x}/users/employees/new`,- newOperator: `${x}/users/operators/new`,newEmployeeAbility: (id: string) =>generatePath(`${x}/resources/ability/${id}/employee/new`),newEmployeeType: `${x}/users/employee-types/new`,+ newExchangeRate: `${x}/accounting/exchange-rates/new`,newFailureMode: `${x}/resources/failure-modes/new`,+ newFixedAsset: `${x}/accounting/fixed-assets/new`,newFixture: `${x}/fixture/new`,newFixtureSupplier: (id: string) =>generatePath(`${x}/fixture/${id}/purchasing/new`),@@ -1313,7 +1400,9 @@ export const path = {newGaugeType: `${x}/quality/gauge-types/new`,newGroup: `${x}/users/groups/new`,newHoliday: `${x}/people/holidays/new`,- newTimecard: `${x}/people/timecard/new`,+ newInspectionDocument: `${x}/quality/inspection/new`,+ newIntercompanyTransaction: `${x}/accounting/intercompany/new`,+ newInventoryCount: `${x}/inventory/inventory-count/new`,newInvestigationType: `${x}/quality/investigation-types/new`,newIssue: `${x}/issue/new`,newIssueAssociation: (id: string) =>@@ -1326,20 +1415,20 @@ export const path = {generatePath(`${x}/job/methods/${jobId}/material/new`),newJobOperation: (jobId: string) =>generatePath(`${x}/job/methods/${jobId}/operation/new`),- newJobOperationStep: `${x}/job/methods/operation/step/new`,newJobOperationParameter: `${x}/job/methods/operation/parameter/new`,+ newJobOperationStep: `${x}/job/methods/operation/step/new`,newJobOperationTool: `${x}/job/methods/operation/tool/new`,+ newJournalEntry: `${x}/accounting/journals/new`,newKanban: `${x}/inventory/kanbans/new`,newLocation: `${x}/resources/locations/new`,newMaintenanceDispatch: `${x}/maintenance/new`,+ newMaintenanceDispatchEvent: (dispatchId: string) =>+ generatePath(`${x}/maintenance/${dispatchId}/event/new`),+ newMaintenanceDispatchItem: (dispatchId: string) =>+ generatePath(`${x}/maintenance/${dispatchId}/item/new`),newMaintenanceSchedule: `${x}/resources/scheduled-maintenance/new`,newMakeMethodVersion: `${x}/items/methods/version/new`,newMaterial: `${x}/material/new`,- newMethodMaterial: `${x}/items/methods/material/new`,- newMethodOperation: `${x}/items/methods/operation/new`,- newMethodOperationStep: `${x}/items/methods/operation/step/new`,- newMethodOperationTool: `${x}/items/methods/operation/tool/new`,- newMethodOperationParameter: `${x}/items/methods/operation/parameter/new`,newMaterialDimension: `${x}/items/dimensions/new`,newMaterialFinish: `${x}/items/finishes/new`,newMaterialForm: `${x}/items/forms/new`,@@ -1347,24 +1436,28 @@ export const path = {newMaterialSubstance: `${x}/items/substances/new`,newMaterialSupplier: (id: string) =>generatePath(`${x}/material/${id}/purchasing/new`),+ newMaterialType: `${x}/items/types/new`,+ newMethodMaterial: `${x}/items/methods/material/new`,+ newMethodOperation: `${x}/items/methods/operation/new`,+ newMethodOperationParameter: `${x}/items/methods/operation/parameter/new`,+ newMethodOperationStep: `${x}/items/methods/operation/step/new`,+ newMethodOperationTool: `${x}/items/methods/operation/tool/new`,+ newNoQuoteReason: `${x}/sales/no-quote-reasons/new`,newNote: `${x}/shared/notes/new`,+ newOperator: `${x}/users/operators/new`,newPart: `${x}/part/new`,+ newPartner: `${x}/resources/partners/new`,newPartSupplier: (id: string) =>generatePath(`${x}/part/${id}/purchasing/new`),- newStockTransfer: `${x}/stock-transfer/new`,- newStockTransferLine: (id: string) =>- generatePath(`${x}/stock-transfer/${id}/line/new`),- newSuggestion: `${x}/resources/suggestions/new`,+ newPaymentTerm: `${x}/accounting/payment-terms/new`,+ newPickingList: `${x}/picking-list/new`,+ newPriceOverride: `${x}/sales/price-list/new`,+ newPricingRule: `${x}/sales/pricing-rules/new`,newProcedure: `${x}/production/procedures/new`,- newProcedureStep: (id: string) =>- generatePath(`${x}/procedure/${id}/steps/new`),newProcedureParameter: (id: string) =>generatePath(`${x}/procedure/${id}/parameters/new`),- newMaterialType: `${x}/items/types/new`,- newNoQuoteReason: `${x}/sales/no-quote-reasons/new`,- newCustomerPortal: `${x}/sales/customer-portals/new`,- newPartner: `${x}/resources/partners/new`,- newPaymentTerm: `${x}/accounting/payment-terms/new`,+ newProcedureStep: (id: string) =>+ generatePath(`${x}/procedure/${id}/steps/new`),newProcess: `${x}/resources/processes/new`,newPurchaseInvoice: `${x}/purchase-invoice/new`,newPurchaseInvoiceLine: (id: string) =>@@ -1372,6 +1465,9 @@ export const path = {newPurchaseOrder: `${x}/purchase-order/new`,newPurchaseOrderLine: (id: string) =>generatePath(`${x}/purchase-order/${id}/new`),+ newPurchasingRFQ: `${x}/purchasing-rfq/new`,+ newPurchasingRFQLine: (id: string) =>+ generatePath(`${x}/purchasing-rfq/${id}/new`),newQualityDocument: `${x}/quality/documents/new`,newQualityDocumentStep: (id: string) =>generatePath(`${x}/quality-document/${id}/steps/new`),@@ -1379,13 +1475,13 @@ export const path = {newQuoteLine: (id: string) => generatePath(`${x}/quote/${id}/new`),newQuoteLineCost: (id: string, lineId: string) =>generatePath(`${x}/quote/${id}/${lineId}/cost/new`),+ newQuoteMaterial: (quoteId: string, lineId: string) =>+ generatePath(`${x}/quote/methods/${quoteId}/${lineId}/material/new`),newQuoteOperation: (quoteId: string, lineId: string) =>generatePath(`${x}/quote/methods/${quoteId}/${lineId}/operation/new`),- newQuoteOperationStep: `${x}/quote/methods/operation/step/new`,newQuoteOperationParameter: `${x}/quote/methods/operation/parameter/new`,+ newQuoteOperationStep: `${x}/quote/methods/operation/step/new`,newQuoteOperationTool: `${x}/quote/methods/operation/tool/new`,- newQuoteMaterial: (quoteId: string, lineId: string) =>- generatePath(`${x}/quote/methods/${quoteId}/${lineId}/material/new`),newReceipt: `${x}/receipt/new`,newRequiredAction: `${x}/quality/required-actions/new`,newRevision: `${x}/items/revisions/new`,@@ -1401,14 +1497,19 @@ export const path = {newSalesRFQ: `${x}/sales-rfq/new`,newSalesRFQLine: (id: string) => generatePath(`${x}/sales-rfq/${id}/new`),newScrapReason: `${x}/production/scrap-reasons/new`,- newStorageUnit: `${x}/inventory/storage-units/new`,- newStorageType: `${x}/inventory/storage-types/new`,- newShipment: `${x}/shipment/new`,- newShift: `${x}/people/shifts/new`,- newShippingMethod: `${x}/inventory/shipping-methods/new`,newService: `${x}/service/new`,newServiceSupplier: (id: string) =>generatePath(`${x}/service/${id}/purchasing/new`),+ newShift: `${x}/people/shifts/new`,+ newShipment: `${x}/shipment/new`,+ newShippingMethod: `${x}/inventory/shipping-methods/new`,+ newStockTransfer: `${x}/stock-transfer/new`,+ newStockTransferLine: (id: string) =>+ generatePath(`${x}/stock-transfer/${id}/line/new`),+ newStorageRule: `${x}/inventory/storage-rules/new`,+ newStorageType: `${x}/inventory/storage-types/new`,+ newStorageUnit: `${x}/inventory/storage-units/new`,+ newSuggestion: `${x}/resources/suggestions/new`,newSupplier: `${x}/supplier/new`,newSupplierAccount: `${x}/users/suppliers/new`,newSupplierContact: (id: string) =>@@ -1422,6 +1523,7 @@ export const path = {generatePath(`${x}/supplier-quote/${id}/new`),newSupplierType: `${x}/purchasing/supplier-types/new`,newTag: `${x}/settings/tags/new`,+ newTimecard: `${x}/people/timecard/new`,newTool: `${x}/tool/new`,newToolSupplier: (id: string) =>generatePath(`${x}/tool/${id}/purchasing/new`),@@ -1433,58 +1535,50 @@ export const path = {newWarehouseTransfer: `${x}/warehouse-transfer/new`,newWarehouseTransferLine: (transferId: string) =>generatePath(`${x}/warehouse-transfer/${transferId}/details/new`),- newWorkCenter: `${x}/resources/work-centers/new`,newWebhook: `${x}/settings/webhooks/new`,- noQuoteReasons: `${x}/sales/no-quote-reasons`,+ newWorkCenter: `${x}/resources/work-centers/new`,noQuoteReason: (id: string) =>generatePath(`${x}/sales/no-quote-reasons/${id}`),+ noQuoteReasons: `${x}/sales/no-quote-reasons`,notificationSettings: `${x}/account/notifications`,+ onboarding: {+ company: `${onboarding}/company`,+ industry: `${onboarding}/industry`,+ location: `${onboarding}/location`,+ plan: `${onboarding}/plan`,+ root: `${onboarding}`,+ theme: `${onboarding}/theme`,+ user: `${onboarding}/user`+ },+ operator: (id: string) => generatePath(`${x}/users/operators/${id}`),+ operatorResetPin: (id: string) =>+ generatePath(`${x}/users/operators/reset-pin/${id}`),+ operators: `${x}/users/operators`,part: (id: string) => generatePath(`${x}/part/${id}`),- itemProperties: (id: string) => generatePath(`${x}/items/${id}/properties`),partCosting: (id: string) => generatePath(`${x}/part/${id}/costing`),partDetails: (id: string) => generatePath(`${x}/part/${id}/details`),- partMake: (id: string, makeMethodId: string) =>- generatePath(`${x}/part/${id}/make/${makeMethodId}`),partInventory: (id: string) => generatePath(`${x}/part/${id}/inventory`),partInventoryLocation: (id: string, locationId: string) =>generatePath(`${x}/part/${id}/inventory?location=${locationId}`),+ partMake: (id: string, makeMethodId: string) =>+ generatePath(`${x}/part/${id}/make/${makeMethodId}`),+ partner: (id: string, abilityId: string) =>+ generatePath(`${x}/resources/partners/${id}/${abilityId}`),+ partners: `${x}/resources/partners`,partPlanning: (id: string) => generatePath(`${x}/part/${id}/planning`),partPlanningLocation: (id: string, locationId: string) =>generatePath(`${x}/part/${id}/planning?location=${locationId}`),partPricing: (id: string) => generatePath(`${x}/part/${id}/pricing`),partPurchasing: (id: string) => generatePath(`${x}/part/${id}/purchasing`),- partRoot: `${x}/part`,partQuality: (id: string) => generatePath(`${x}/part/${id}/quality`),+ partRoot: `${x}/part`,partRules: (id: string) => generatePath(`${x}/part/${id}/rules`),- materialRules: (id: string) => generatePath(`${x}/material/${id}/rules`),- consumableRules: (id: string) =>- generatePath(`${x}/consumable/${id}/rules`),- toolRules: (id: string) => generatePath(`${x}/tool/${id}/rules`),- storageRules: `${x}/inventory/storage-rules`,- storageRule: (id: string) =>- generatePath(`${x}/inventory/storage-rules/${id}`),- newStorageRule: `${x}/inventory/storage-rules/new`,- deleteStorageRule: (id: string) =>- generatePath(`${x}/inventory/storage-rules/${id}/delete`),- storageRuleAssignItem: (itemId: string) =>- generatePath(`${x}/items/rules/assign/${itemId}`),- storageRuleUnassignItem: (itemId: string, ruleId: string) =>- generatePath(`${x}/items/rules/unassign/${itemId}/${ruleId}`),- storageRuleAssignWorkCenter: (id: string) =>- generatePath(`${x}/resources/work-centers/rules/assign/${id}`),- storageRuleUnassignWorkCenter: (id: string, ruleId: string) =>- generatePath(- `${x}/resources/work-centers/rules/unassign/${id}/${ruleId}`- ),partSales: (id: string) => generatePath(`${x}/part/${id}/sales`),partSupplier: (itemId: string, id: string) =>generatePath(`${x}/part/${itemId}/purchasing/${id}`),- deletePartSupplier: (itemId: string, id: string) =>- generatePath(`${x}/part/${itemId}/purchasing/${id}/delete`),parts: `${x}/items/parts`,- partner: (id: string, abilityId: string) =>- generatePath(`${x}/resources/partners/${id}/${abilityId}`),- partners: `${x}/resources/partners`,+ payables: `${x}/invoicing/payables`,+ payablesAdjust: `${x}/invoicing/payables/adjust`,payment: (id: string) => generatePath(`${x}/payments/${id}`),paymentApplicationsSet: (id: string) =>generatePath(`${x}/payments/${id}/applications/set`),@@ -1493,66 +1587,62 @@ export const path = {paymentDelete: (id: string) => generatePath(`${x}/payments/${id}/delete`),paymentNew: `${x}/payments/new`,paymentPost: (id: string) => generatePath(`${x}/payments/${id}/post`),- paymentVoid: (id: string) => generatePath(`${x}/payments/${id}/void`),payments: `${x}/invoicing/payments`,- receivables: `${x}/invoicing/receivables`,- receivablesAdjust: `${x}/invoicing/receivables/adjust`,- payables: `${x}/invoicing/payables`,- payablesAdjust: `${x}/invoicing/payables/adjust`,paymentTerm: (id: string) =>generatePath(`${x}/accounting/payment-terms/${id}`),paymentTerms: `${x}/accounting/payment-terms`,+ paymentVoid: (id: string) => generatePath(`${x}/payments/${id}/void`),people: `${x}/people/employee`,+ peopleSettings: `${x}/settings/people`,peopleTimecard: `${x}/people/timecard`,- timecard: (id: string) => generatePath(`${x}/people/timecard/${id}`),- contact: `${x}/people/contact`,person: (id: string) => generatePath(`${x}/person/${id}`),+ personAttributeCategory: (personId: string, categoryId: string) =>+ generatePath(`${x}/person/${personId}/attributes/${categoryId}`),personDetails: (id: string) => generatePath(`${x}/person/${id}/details`),personJob: (id: string) => generatePath(`${x}/person/${id}/job`),personTimecard: (id: string) => generatePath(`${x}/person/${id}/timecard`),- personAttributeCategory: (personId: string, categoryId: string) =>- generatePath(`${x}/person/${personId}/attributes/${categoryId}`),- stockTransfer: (id: string) => generatePath(`${x}/stock-transfer/${id}`),- stockTransferComplete: (id: string) =>- generatePath(`${x}/stock-transfer/${id}/complete`),- stockTransferLine: (id: string, lineId: string) =>- generatePath(`${x}/stock-transfer/${id}/line/${lineId}`),- stockTransferLineQuantity: (id: string) =>- generatePath(`${x}/stock-transfer/${id}/line/quantity`),- stockTransferScan: (id: string, lineId: string) =>- generatePath(`${x}/stock-transfer/${id}/scan/${lineId}`),- stockTransferStatus: (id: string) =>- generatePath(`${x}/stock-transfer/${id}/status`),- stockTransfers: `${x}/inventory/stock-transfers`,- suggestion: (id: string) =>- generatePath(`${x}/resources/suggestions/${id}`),- suggestions: `${x}/resources/suggestions`,+ pickingList: (id: string) => generatePath(`${x}/picking-list/${id}`),+ pickingListDelete: (id: string) =>+ generatePath(`${x}/picking-list/${id}/delete`),+ pickingListDetails: (id: string) =>+ generatePath(`${x}/picking-list/${id}/details`),+ pickingListLine: (pickingListId: string, lineId: string) =>+ generatePath(`${x}/picking-list/${pickingListId}/details/${lineId}`),+ pickingListLineQuantity: (id: string) =>+ generatePath(`${x}/picking-list/${id}/line/quantity`),+ pickingListStatus: (id: string) =>+ generatePath(`${x}/picking-list/${id}/status`),+ pickingLists: `${x}/inventory/picking-lists`,+ pickingListsTable: `${x}/inventory/picking-lists`,+ pickingListTracked: (pickingListId: string, lineId: string) =>+ generatePath(`${x}/picking-list/${pickingListId}/tracked/${lineId}`),+ pickingSchedule: `${x}/picking-list/schedule`,+ postJournalEntry: (id: string) =>+ generatePath(`${x}/journal-entry/${id}/post`),+ priceOverride: (id: string) => generatePath(`${x}/sales/price-list/${id}`),+ pricingRule: (id: string) => generatePath(`${x}/sales/pricing-rules/${id}`),+ printingSettings: `${x}/settings/printing`,+ printingSettingsJobs: `${x}/settings/printing/jobs`,procedure: (id: string) => generatePath(`${x}/procedure/${id}`),+ procedureParameter: (id: string, parameterId: string) =>+ generatePath(`${x}/procedure/${id}/parameters/${parameterId}`),procedureStep: (id: string, attributeId: string) =>generatePath(`${x}/procedure/${id}/steps/${attributeId}`),procedureStepOrder: (id: string) =>generatePath(`${x}/procedure/${id}/steps/order`),- procedureParameter: (id: string, parameterId: string) =>- generatePath(`${x}/procedure/${id}/parameters/${parameterId}`),procedures: `${x}/production/procedures`,process: (id: string) => generatePath(`${x}/resources/processes/${id}`),- processes: `${x}/resources/processes`,processActivate: (id: string) =>generatePath(`${x}/resources/processes/activate/${id}`),processDeactivate: (id: string) =>generatePath(`${x}/resources/processes/deactivate/${id}`),- printingSettings: `${x}/settings/printing`,- printingSettingsJobs: `${x}/settings/printing/jobs`,- deletePrinterRoute: (id: string) =>- generatePath(`${x}/settings/printing/${id}/delete`),+ processes: `${x}/resources/processes`,production: `${x}/production`,productionPlanning: `${x}/production/planning`,productionPlanningItem: (itemId: string) =>generatePath(`${x}/production/planning/${itemId}`),- peopleSettings: `${x}/settings/people`,productionSettings: `${x}/settings/production`,profile: `${x}/account/profile`,- accountSecurity: `${x}/account/security`,purchaseInvoice: (id: string) =>generatePath(`${x}/purchase-invoice/${id}`),purchaseInvoiceDelivery: (id: string) =>@@ -1573,48 +1663,67 @@ export const path = {purchaseInvoiceVoid: (id: string) =>generatePath(`${x}/purchase-invoice/${id}/void`),purchaseOrder: (id: string) => generatePath(`${x}/purchase-order/${id}`),- purchaseOrderDuplicate: (id: string) =>- generatePath(`${x}/purchase-order/${id}/duplicate`),purchaseOrderDelivery: (id: string) =>generatePath(`${x}/purchase-order/${id}/delivery`),purchaseOrderDetails: (id: string) =>generatePath(`${x}/purchase-order/${id}/details`),+ purchaseOrderDuplicate: (id: string) =>+ generatePath(`${x}/purchase-order/${id}/duplicate`),purchaseOrderExchangeRate: (id: string) =>generatePath(`${x}/purchase-order/${id}/exchange-rate`),purchaseOrderExternalDocuments: (id: string) =>generatePath(`${x}/purchase-order/${id}/external`),purchaseOrderFavorite: `${x}/purchasing/orders/favorite`,+ purchaseOrderFinalize: (id: string) =>+ generatePath(`${x}/purchase-order/${id}/finalize`),purchaseOrderLine: (orderId: string, id: string) =>generatePath(`${x}/purchase-order/${orderId}/${id}/details`),- purchaseOrderLineReceiving: (orderId: string, id: string) =>- generatePath(`${x}/purchase-order/${orderId}/${id}/receiving`),purchaseOrderLineOrder: (orderId: string) =>generatePath(`${x}/purchase-order/${orderId}/line-order`),+ purchaseOrderLineReceiving: (orderId: string, id: string) =>+ generatePath(`${x}/purchase-order/${orderId}/${id}/receiving`),purchaseOrderPayment: (id: string) =>generatePath(`${x}/purchase-order/${id}/payment`),- purchaseOrderFinalize: (id: string) =>- generatePath(`${x}/purchase-order/${id}/finalize`),- supplierDefaultAttachments: (supplierId: string) =>- generatePath(`${x}/supplier/${supplierId}/default-attachments`),purchaseOrderRoot: `${x}/purchase-order`,purchaseOrderStatus: (id: string) =>generatePath(`${x}/purchase-order/${id}/status`),purchaseOrders: `${x}/purchasing/orders`,purchasing: `${x}/purchasing`,purchasingPlanning: `${x}/purchasing/planning`,++ // Purchasing RFQ paths+ purchasingRfq: (id: string) => generatePath(`${x}/purchasing-rfq/${id}`),+ purchasingRfqCompare: (id: string) =>+ generatePath(`${x}/purchasing-rfq/${id}/compare`),+ purchasingRfqConvert: (id: string) =>+ generatePath(`${x}/purchasing-rfq/${id}/convert`),+ purchasingRfqDetails: (id: string) =>+ generatePath(`${x}/purchasing-rfq/${id}/details`),+ purchasingRfqFavorite: `${x}/purchasing/rfqs/favorite`,+ purchasingRfqFinalize: (id: string) =>+ generatePath(`${x}/purchasing-rfq/${id}/finalize`),+ purchasingRfqLine: (id: string, lineId: string) =>+ generatePath(`${x}/purchasing-rfq/${id}/${lineId}/details`),+ purchasingRfqLineOrder: (id: string) =>+ generatePath(`${x}/purchasing-rfq/${id}/line-order`),+ purchasingRfqPreview: (id: string) =>+ generatePath(`/share/purchasing-rfq/${id}`),+ purchasingRfqRoot: `${x}/purchasing-rfq`,+ purchasingRfqStatus: (id: string) =>+ generatePath(`${x}/purchasing-rfq/${id}/status`),+ purchasingRfqSuppliers: (id: string) =>+ generatePath(`${x}/purchasing-rfq/${id}/suppliers`),+ purchasingRfqs: `${x}/purchasing/rfqs`,purchasingSettings: `${x}/settings/purchasing`,quality: `${x}/quality`,qualityActions: `${x}/quality/actions`,- inboundInspections: `${x}/quality/inbound-inspections`,- inboundInspection: (id: string) =>- generatePath(`${x}/quality/inbound-inspections/${id}`),qualityDocument: (id: string) =>generatePath(`${x}/quality-document/${id}`),- qualityDocuments: `${x}/quality/documents`,qualityDocumentStep: (id: string, attributeId: string) =>generatePath(`${x}/quality-document/${id}/steps/${attributeId}`),qualityDocumentStepOrder: (id: string) =>generatePath(`${x}/quality-document/${id}/steps/order`),+ qualityDocuments: `${x}/quality/documents`,qualitySettings: `${x}/settings/quality`,quote: (id: string) => generatePath(`${x}/quote/${id}`),quoteAssembly: (quoteId: string, lineId: string, assemblyId: string) =>@@ -1634,8 +1743,6 @@ export const path = {generatePath(`${x}/quote/${id}/internal`),quoteLine: (quoteId: string, id: string) =>generatePath(`${x}/quote/${quoteId}/${id}/details`),- quoteLineOrder: (quoteId: string) =>- generatePath(`${x}/quote/${quoteId}/line-order`),quoteLineConfigure: (quoteId: string, lineId: string) =>generatePath(`${x}/quote/${quoteId}/${lineId}/configure`),quoteLineMakeMethod: (@@ -1645,6 +1752,8 @@ export const path = {) => generatePath(`${x}/quote/${quoteId}/${lineId}/make/${makeMethodId}`),quoteLineMethod: (quoteId: string, quoteLineId: string, methodId: string) =>generatePath(`${x}/quote/${quoteId}/${quoteLineId}/method/${methodId}`),+ quoteLineOrder: (quoteId: string) =>+ generatePath(`${x}/quote/${quoteId}/line-order`),quoteLineRecalculatePrice: (quoteId: string, lineId: string) =>generatePath(`${x}/quote/${quoteId}/${lineId}/recalculate-price`),quoteLineUpdatePrecision: (quoteId: string, lineId: string) =>@@ -1656,14 +1765,14 @@ export const path = {quoteMethodSave: `${x}/quote/methods/save`,quoteOperation: (quoteId: string, lineId: string, id: string) =>generatePath(`${x}/quote/methods/${quoteId}/${lineId}/operation/${id}`),- quoteOperationsOrder: `${x}/quote/methods/operation/order`,- quoteOperationsDelete: `${x}/quote/methods/operation/delete`,+ quoteOperationParameter: (id: string) =>+ generatePath(`${x}/quote/methods/operation/parameter/${id}`),quoteOperationStep: (id: string) =>generatePath(`${x}/quote/methods/operation/step/${id}`),quoteOperationStepOrder: (operationId: string) =>generatePath(`${x}/quote/methods/operation/${operationId}/step/order`),- quoteOperationParameter: (id: string) =>- generatePath(`${x}/quote/methods/operation/parameter/${id}`),+ quoteOperationsDelete: `${x}/quote/methods/operation/delete`,+ quoteOperationsOrder: `${x}/quote/methods/operation/order`,quoteOperationTool: (id: string) =>generatePath(`${x}/quote/methods/operation/tool/${id}`),quotePayment: (id: string) => generatePath(`${x}/quote/${id}/payment`),@@ -1671,44 +1780,36 @@ export const path = {quoteStatus: (id: string) => generatePath(`${x}/quote/${id}/status`),quotes: `${x}/sales/quotes`,receipt: (id: string) => generatePath(`${x}/receipt/${id}`),- receiptInvoice: (id: string) => generatePath(`${x}/receipt/${id}/invoice`),receiptDetails: (id: string) => generatePath(`${x}/receipt/${id}/details`),+ receiptFixedAssetLineUpdate: `${x}/receipt/fixed-asset-lines/update`,+ receiptInvoice: (id: string) => generatePath(`${x}/receipt/${id}/invoice`),receiptLineDelete: (id: string) =>generatePath(`${x}/receipt/lines/${id}/delete`),- receiptFixedAssetLineUpdate: `${x}/receipt/fixed-asset-lines/update`,receiptLineSplit: `${x}/receipt/lines/split`,receiptLines: (id: string) => generatePath(`${x}/receipt/${id}/lines`),receiptLinesTracking: (id: string) =>generatePath(`${x}/receipt/lines/tracking`),- receipts: `${x}/inventory/receipts`,receiptPost: (id: string) => generatePath(`${x}/receipt/${id}/post`),receiptRoot: `${x}/receipt`,+ receipts: `${x}/inventory/receipts`,receiptVoid: (id: string) => generatePath(`${x}/receipt/${id}/void`),- inventoryCounts: `${x}/inventory/inventory-count`,- newInventoryCount: `${x}/inventory/inventory-count/new`,- inventoryCount: (id: string) => generatePath(`${x}/inventory-count/${id}`),- inventoryCountConfirm: (id: string) =>- generatePath(`${x}/inventory-count/${id}/confirm`),- inventoryCountReopen: (id: string) =>- generatePath(`${x}/inventory-count/${id}/reopen`),- inventoryCountPost: (id: string) =>- generatePath(`${x}/inventory-count/${id}/post`),- inventoryCountRectify: (id: string) =>- generatePath(`${x}/inventory-count/${id}/rectify`),- inventoryCountDelete: (id: string) =>- generatePath(`${x}/inventory-count/${id}/delete`),- inventoryCountLineUpdate: `${x}/inventory-count/lines/update`,+ receivables: `${x}/invoicing/receivables`,+ receivablesAdjust: `${x}/invoicing/receivables/adjust`,refreshSession: "/refresh-session",+ repeatDepreciationRun: (id: string) =>+ generatePath(`${x}/depreciation-run/${id}/repeat`),requiredAction: (id: string) =>generatePath(`${x}/quality/required-actions/${id}`),requiredActions: `${x}/quality/required-actions`,resendInvite: `${x}/users/resend-invite`,resources: `${x}/resources`,resourcesSettings: `${x}/settings/resources`,+ reverseJournalEntry: (id: string) =>+ generatePath(`${x}/journal-entry/${id}/reverse`),revision: (id: string) => generatePath(`${x}/items/revisions/${id}`),revokeInvite: `${x}/users/revoke-invite`,- risks: `${x}/quality/risks`,risk: (id: string) => generatePath(`${x}/quality/risks/${id}`),+ risks: `${x}/quality/risks`,root: "/",routings: `${x}/items/routing`,sales: `${x}/sales`,@@ -1729,19 +1830,11 @@ export const path = {generatePath(`${x}/sales-invoice/${id}/status`),salesInvoiceVoid: (id: string) =>generatePath(`${x}/sales-invoice/${id}/void`),- // Credit / Debit memos — payment-shaped documents (the `memo` table). The- // list lives in the invoicing nav beside Payments; details mirror payments.- memo: (id: string) => generatePath(`${x}/credits/${id}`),- memoDelete: (id: string) => generatePath(`${x}/credits/${id}/delete`),- memoNew: `${x}/credits/new`,- memoPost: (id: string) => generatePath(`${x}/credits/${id}/post`),- memoVoid: (id: string) => generatePath(`${x}/credits/${id}/void`),- memos: `${x}/invoicing/credits`,salesOrder: (id: string) => generatePath(`${x}/sales-order/${id}`),+ salesOrderCancelPreview: (id: string) =>+ generatePath(`${x}/sales-order/${id}/cancel-preview`),salesOrderConfirm: (id: string) =>generatePath(`${x}/sales-order/${id}/confirm`),- salesOrderShipment: (id: string) =>- generatePath(`${x}/sales-order/${id}/shipment`),salesOrderDetails: (id: string) =>generatePath(`${x}/sales-order/${id}/details`),salesOrderExchangeRate: (id: string) =>@@ -1755,30 +1848,21 @@ export const path = {generatePath(`${x}/sales-order/${orderId}/${id}/details`),salesOrderLineOrder: (orderId: string) =>generatePath(`${x}/sales-order/${orderId}/line-order`),- salesOrderLineToJob: (orderId: string, lineId: string) =>- generatePath(`${x}/sales-order/${orderId}/${lineId}/job`),salesOrderLinesToJobs: (orderId: string) =>generatePath(`${x}/sales-order/${orderId}/lines/jobs`),+ salesOrderLineToJob: (orderId: string, lineId: string) =>+ generatePath(`${x}/sales-order/${orderId}/${lineId}/job`),salesOrderPayment: (id: string) =>generatePath(`${x}/sales-order/${id}/payment`),salesOrderRelease: (id: string) =>generatePath(`${x}/sales-order/${id}/release`),+ salesOrderShipment: (id: string) =>+ generatePath(`${x}/sales-order/${id}/shipment`),salesOrderStatus: (id: string) =>generatePath(`${x}/sales-order/${id}/status`),- salesOrderCancelPreview: (id: string) =>- generatePath(`${x}/sales-order/${id}/cancel-preview`),salesOrders: `${x}/sales/orders`,salesPriceList: `${x}/sales/price-list`,- deletePriceOverride: (id: string) =>- generatePath(`${x}/sales/price-list/delete/${id}`),- newPriceOverride: `${x}/sales/price-list/new`,- duplicatePriceList: `${x}/sales/price-list/duplicate`,- priceOverride: (id: string) => generatePath(`${x}/sales/price-list/${id}`),salesPricingRules: `${x}/sales/pricing-rules`,- pricingRule: (id: string) => generatePath(`${x}/sales/pricing-rules/${id}`),- newPricingRule: `${x}/sales/pricing-rules/new`,- deletePricingRule: (id: string) =>- generatePath(`${x}/sales/pricing-rules/delete/${id}`),salesRfq: (id: string) => generatePath(`${x}/sales-rfq/${id}`),salesRfqConvert: (id: string) =>generatePath(`${x}/sales-rfq/${id}/convert`),@@ -1794,77 +1878,40 @@ export const path = {salesRfqStatus: (id: string) => generatePath(`${x}/sales-rfq/${id}/status`),salesRfqs: `${x}/sales/rfqs`,salesSettings: `${x}/settings/sales`,+ saveInspectionDocument: (id: string) =>+ generatePath(`${x}/inspection/${id}/save`),- // Purchasing RFQ paths- purchasingRfq: (id: string) => generatePath(`${x}/purchasing-rfq/${id}`),- purchasingRfqDetails: (id: string) =>- generatePath(`${x}/purchasing-rfq/${id}/details`),- purchasingRfqFavorite: `${x}/purchasing/rfqs/favorite`,- purchasingRfqLine: (id: string, lineId: string) =>- generatePath(`${x}/purchasing-rfq/${id}/${lineId}/details`),- purchasingRfqLineOrder: (id: string) =>- generatePath(`${x}/purchasing-rfq/${id}/line-order`),- purchasingRfqRoot: `${x}/purchasing-rfq`,- purchasingRfqStatus: (id: string) =>- generatePath(`${x}/purchasing-rfq/${id}/status`),- cancelPurchasingRfq: (id: string) =>- generatePath(`${x}/purchasing-rfq/${id}/cancel`),- purchasingRfqFinalize: (id: string) =>- generatePath(`${x}/purchasing-rfq/${id}/finalize`),- purchasingRfqs: `${x}/purchasing/rfqs`,- newPurchasingRFQ: `${x}/purchasing-rfq/new`,- newPurchasingRFQLine: (id: string) =>- generatePath(`${x}/purchasing-rfq/${id}/new`),- deletePurchasingRfq: (id: string) =>- generatePath(`${x}/purchasing-rfq/${id}/delete`),- deletePurchasingRfqLine: (id: string, lineId: string) =>- generatePath(`${x}/purchasing-rfq/${id}/${lineId}/delete`),- purchasingRfqConvert: (id: string) =>- generatePath(`${x}/purchasing-rfq/${id}/convert`),- purchasingRfqCompare: (id: string) =>- generatePath(`${x}/purchasing-rfq/${id}/compare`),- purchasingRfqSuppliers: (id: string) =>- generatePath(`${x}/purchasing-rfq/${id}/suppliers`),- purchasingRfqPreview: (id: string) =>- generatePath(`/share/purchasing-rfq/${id}`),+ saveViewOrder: `${x}/shared/view/order`,saveViews: `${x}/shared/views`,-- saveViewOrder: `${x}/shared/view/order`,- scheduleOperation: `${x}/schedule/operations`,- scheduleOperationUpdate: `${x}/schedule/operations/update`,scheduleDates: `${x}/schedule/dates`,scheduleDatesUpdate: `${x}/schedule/dates/update`,+ scheduleOperation: `${x}/schedule/operations`,+ scheduleOperationUpdate: `${x}/schedule/operations/update`,scrapReason: (id: string) =>generatePath(`${x}/production/scrap-reasons/${id}`),scrapReasons: `${x}/production/scrap-reasons`,- serialNumbers: `${x}/inventory/serial-numbers`,+ selectCompany,+ sequences: `${x}/settings/sequences`,serialNumber: (id: string) =>generatePath(`${x}/inventory/serial-numbers/${id}`),+ serialNumbers: `${x}/inventory/serial-numbers`,service: (id: string) => generatePath(`${x}/service/${id}`),- services: `${x}/items/services`,serviceCosting: (id: string) => generatePath(`${x}/service/${id}/costing`),serviceDetails: (id: string) => `${x}/service/${id}/details`,serviceMake: (id: string, makeMethodId: string) =>generatePath(`${x}/service/${id}/make/${makeMethodId}`),+ servicePurchasing: (id: string) =>+ generatePath(`${x}/service/${id}/purchasing`),serviceQuality: (id: string) => generatePath(`${x}/service/${id}/quality`),serviceRoot: `${x}/service`,serviceSales: (id: string) => generatePath(`${x}/service/${id}/sales`),- servicePurchasing: (id: string) =>- generatePath(`${x}/service/${id}/purchasing`),serviceSupplier: (serviceId: string, id: string) =>generatePath(`${x}/service/${serviceId}/purchasing/${id}`),+ services: `${x}/items/services`,settings: `${x}/settings`,- sequences: `${x}/settings/sequences`,- storageUnit: (id: string) =>- generatePath(`${x}/inventory/storage-units/${id}`),- storageUnits: `${x}/inventory/storage-units`,- storageType: (id: string) =>- generatePath(`${x}/inventory/storage-types/${id}`),- storageTypes: `${x}/inventory/storage-types`,shift: (id: string) => generatePath(`${x}/people/shifts/${id}`),shifts: `${x}/people/shifts`,- shipments: `${x}/inventory/shipments`,shipment: (id: string) => generatePath(`${x}/shipment/${id}`),shipmentDetails: (id: string) =>generatePath(`${x}/shipment/${id}/details`),@@ -1875,55 +1922,61 @@ export const path = {shipmentLinesTracking: (id: string) =>generatePath(`${x}/shipment/lines/tracking`),shipmentPost: (id: string) => generatePath(`${x}/shipment/${id}/post`),+ shipments: `${x}/inventory/shipments`,shipmentVoid: (id: string) => generatePath(`${x}/shipment/${id}/void`),shippingMethod: (id: string) =>generatePath(`${x}/inventory/shipping-methods/${id}`),- warehouseTransfers: `${x}/inventory/warehouse-transfers`,- warehouseTransfer: (id: string) =>- generatePath(`${x}/warehouse-transfer/${id}`),- warehouseTransferDetails: (id: string) =>- generatePath(`${x}/warehouse-transfer/${id}/details`),- warehouseTransferStatus: (id: string) =>- generatePath(`${x}/warehouse-transfer/${id}/status`),- warehouseTransferShip: (id: string) =>- generatePath(`${x}/warehouse-transfer/${id}/ship`),- warehouseTransferReceive: (id: string) =>- generatePath(`${x}/warehouse-transfer/${id}/receive`),- warehouseTransferLines: (transferId: string) =>- generatePath(`${x}/warehouse-transfer/${transferId}/lines`),- warehouseTransferLine: (transferId: string, lineId: string) =>- generatePath(`${x}/warehouse-transfer/${transferId}/details/${lineId}`),- pickingLists: `${x}/inventory/picking-lists`,- pickingSchedule: `${x}/picking-list/schedule`,- pickingListsTable: `${x}/inventory/picking-lists`,- newPickingList: `${x}/picking-list/new`,- pickingList: (id: string) => generatePath(`${x}/picking-list/${id}`),- pickingListDetails: (id: string) =>- generatePath(`${x}/picking-list/${id}/details`),- pickingListStatus: (id: string) =>- generatePath(`${x}/picking-list/${id}/status`),- pickingListDelete: (id: string) =>- generatePath(`${x}/picking-list/${id}/delete`),- pickingListLine: (pickingListId: string, lineId: string) =>- generatePath(`${x}/picking-list/${pickingListId}/details/${lineId}`),- pickingListTracked: (pickingListId: string, lineId: string) =>- generatePath(`${x}/picking-list/${pickingListId}/tracked/${lineId}`),- pickingListLineQuantity: (id: string) =>- generatePath(`${x}/picking-list/${id}/line/quantity`),shippingMethods: `${x}/inventory/shipping-methods`,+ splitIssueItem: `${x}/issue/item/split`,+ stockMovements: `${x}/inventory/stock-movements`,+ stockTransfer: (id: string) => generatePath(`${x}/stock-transfer/${id}`),+ stockTransferComplete: (id: string) =>+ generatePath(`${x}/stock-transfer/${id}/complete`),+ stockTransferLine: (id: string, lineId: string) =>+ generatePath(`${x}/stock-transfer/${id}/line/${lineId}`),+ stockTransferLineQuantity: (id: string) =>+ generatePath(`${x}/stock-transfer/${id}/line/quantity`),+ stockTransferScan: (id: string, lineId: string) =>+ generatePath(`${x}/stock-transfer/${id}/scan/${lineId}`),+ stockTransferStatus: (id: string) =>+ generatePath(`${x}/stock-transfer/${id}/status`),+ stockTransfers: `${x}/inventory/stock-transfers`,+ storageRule: (id: string) =>+ generatePath(`${x}/inventory/storage-rules/${id}`),+ storageRuleAssignItem: (itemId: string) =>+ generatePath(`${x}/items/rules/assign/${itemId}`),+ storageRuleAssignWorkCenter: (id: string) =>+ generatePath(`${x}/resources/work-centers/rules/assign/${id}`),+ storageRules: `${x}/inventory/storage-rules`,+ storageRuleUnassignItem: (itemId: string, ruleId: string) =>+ generatePath(`${x}/items/rules/unassign/${itemId}/${ruleId}`),+ storageRuleUnassignWorkCenter: (id: string, ruleId: string) =>+ generatePath(+ `${x}/resources/work-centers/rules/unassign/${id}/${ruleId}`+ ),+ storageType: (id: string) =>+ generatePath(`${x}/inventory/storage-types/${id}`),+ storageTypes: `${x}/inventory/storage-types`,+ storageUnit: (id: string) =>+ generatePath(`${x}/inventory/storage-units/${id}`),+ storageUnits: `${x}/inventory/storage-units`,+ suggestion: (id: string) =>+ generatePath(`${x}/resources/suggestions/${id}`),+ suggestions: `${x}/resources/suggestions`,supplier: (id: string) => generatePath(`${x}/supplier/${id}`),- supplierApproval: (id: string) =>- generatePath(`${x}/supplier/${id}/approval`),- suppliers: `${x}/purchasing/suppliers`,- supplierAccounts: `${x}/users/suppliers`,supplierAccounting: (id: string) =>generatePath(`${x}/supplier/${id}/accounting`),+ supplierAccounts: `${x}/users/suppliers`,+ supplierApproval: (id: string) =>+ generatePath(`${x}/supplier/${id}/approval`),supplierContact: (supplierId: string, id: string) =>generatePath(`${x}/supplier/${supplierId}/contacts/${id}`),- supplierDetails: (id: string) =>- generatePath(`${x}/supplier/${id}/details`),supplierContacts: (id: string) =>generatePath(`${x}/supplier/${id}/contacts`),+ supplierDefaultAttachments: (supplierId: string) =>+ generatePath(`${x}/supplier/${supplierId}/default-attachments`),+ supplierDetails: (id: string) =>+ generatePath(`${x}/supplier/${id}/details`),supplierLocation: (supplierId: string, id: string) =>generatePath(`${x}/supplier/${supplierId}/locations/${id}`),supplierLocations: (id: string) =>@@ -1934,28 +1987,29 @@ export const path = {generatePath(`${x}/supplier/${supplierId}/processes/${id}`),supplierProcesses: (id: string) =>generatePath(`${x}/supplier/${id}/processes`),- supplierRisks: (id: string) => generatePath(`${x}/supplier/${id}/risks`),- supplierShipping: (id: string) =>- generatePath(`${x}/supplier/${id}/shipping`),- supplierTax: (id: string) => generatePath(`${x}/supplier/${id}/tax`),supplierQuote: (id: string) => generatePath(`${x}/supplier-quote/${id}`),- supplierQuotes: `${x}/purchasing/quotes`,- supplierQuoteFavorite: `${x}/purchasing/quotes/favorite`,supplierQuoteDetails: (id: string) =>generatePath(`${x}/supplier-quote/${id}/details`),supplierQuoteExchangeRate: (id: string) =>generatePath(`${x}/supplier-quote/${id}/exchange-rate`),+ supplierQuoteFavorite: `${x}/purchasing/quotes/favorite`,+ supplierQuoteFinalize: (id: string) =>+ generatePath(`${x}/supplier-quote/${id}/finalize`),supplierQuoteLine: (id: string, lineId: string) =>generatePath(`${x}/supplier-quote/${id}/${lineId}/details`),supplierQuoteLineOrder: (id: string) =>generatePath(`${x}/supplier-quote/${id}/line-order`),- supplierQuoteFinalize: (id: string) =>- generatePath(`${x}/supplier-quote/${id}/finalize`),supplierQuoteSend: (id: string) =>generatePath(`${x}/supplier-quote/${id}/send`),supplierQuoteStatus: (id: string) =>generatePath(`${x}/supplier-quote/${id}/status`),+ supplierQuotes: `${x}/purchasing/quotes`,+ supplierRisks: (id: string) => generatePath(`${x}/supplier/${id}/risks`),supplierRoot: `${x}/supplier`,+ supplierShipping: (id: string) =>+ generatePath(`${x}/supplier/${id}/shipping`),+ suppliers: `${x}/purchasing/suppliers`,+ supplierTax: (id: string) => generatePath(`${x}/supplier/${id}/tax`),supplierType: (id: string) =>generatePath(`${x}/purchasing/supplier-types/${id}`),supplierTypes: `${x}/purchasing/supplier-types`,@@ -1963,6 +2017,7 @@ export const path = {generatePath(`${x}/settings/sequences/${id}`),tags: `${x}/settings/tags`,theme: `${x}/account/theme`,+ timecard: (id: string) => generatePath(`${x}/people/timecard/${id}`),timecards: `${x}/timecards`,tool: (id: string) => generatePath(`${x}/tool/${id}`),toolCosting: (id: string) => generatePath(`${x}/tool/${id}/costing`),@@ -1979,10 +2034,9 @@ export const path = {toolPurchasing: (id: string) => generatePath(`${x}/tool/${id}/purchasing`),toolQuality: (id: string) => generatePath(`${x}/tool/${id}/quality`),toolRoot: `${x}/tool`,+ toolRules: (id: string) => generatePath(`${x}/tool/${id}/rules`),toolSupplier: (itemId: string, id: string) =>generatePath(`${x}/tool/${itemId}/suppliers/${id}`),- deleteToolSupplier: (itemId: string, id: string) =>- generatePath(`${x}/tool/${itemId}/purchasing/${id}/delete`),toolSuppliers: (id: string) => generatePath(`${x}/tool/${id}/suppliers`),tools: `${x}/items/tools`,traceability: `${x}/traceability`,@@ -1990,28 +2044,52 @@ export const path = {trackedEntities: `${x}/inventory/tracked-entities`,trackedEntityExpiry: `${x}/inventory/tracked-entity/expiry`,training: (id: string) => generatePath(`${x}/training/${id}`),- trainings: `${x}/resources/training`,++ trainingAssignment: (assignmentId: string) =>+ generatePath(`${x}/resources/assignments/assignment/${assignmentId}`),+ trainingAssignmentDetail: (trainingId: string) =>+ generatePath(`${x}/resources/assignments/${trainingId}`),+ trainingAssignments: `${x}/resources/assignments`,trainingQuestion: (id: string, questionId: string) =>generatePath(`${x}/training/${id}/questions/${questionId}`),trainingQuestionOrder: (id: string) =>generatePath(`${x}/training/${id}/questions/order`),- trainingAssignments: `${x}/resources/assignments`,- trainingAssignmentDetail: (trainingId: string) =>- generatePath(`${x}/resources/assignments/${trainingId}`),-- trainingAssignment: (assignmentId: string) =>- generatePath(`${x}/resources/assignments/assignment/${assignmentId}`),+ trainings: `${x}/resources/training`,+ trialBalance: `${x}/accounting/trial-balance`,+ trialBalanceLedger: (id: string) =>+ generatePath(`${x}/accounting/trial-balance/${id}`),uom: (id: string) => generatePath(`${x}/items/uom/${id}`),uoms: `${x}/items/uom`,+ updateAssemblyUnit: (id: string, unitId: string) =>+ generatePath(`${x}/assembly/${id}/units/${unitId}`),+ updateChangeOrder: `${x}/items/change-order/update`,+ updateInspectionDocumentName: (id: string) =>+ generatePath(`${x}/inspection/${id}/update-name`),+ updateIssueItem: `${x}/issue/item/update`,userAttribute: (id: string) => generatePath(`${x}/account/${id}/attribute`),users: `${x}/users`,+ warehouseTransfer: (id: string) =>+ generatePath(`${x}/warehouse-transfer/${id}`),+ warehouseTransferDetails: (id: string) =>+ generatePath(`${x}/warehouse-transfer/${id}/details`),+ warehouseTransferLine: (transferId: string, lineId: string) =>+ generatePath(`${x}/warehouse-transfer/${transferId}/details/${lineId}`),+ warehouseTransferLines: (transferId: string) =>+ generatePath(`${x}/warehouse-transfer/${transferId}/lines`),+ warehouseTransferReceive: (id: string) =>+ generatePath(`${x}/warehouse-transfer/${id}/receive`),+ warehouseTransferShip: (id: string) =>+ generatePath(`${x}/warehouse-transfer/${id}/ship`),+ warehouseTransferStatus: (id: string) =>+ generatePath(`${x}/warehouse-transfer/${id}/status`),+ warehouseTransfers: `${x}/inventory/warehouse-transfers`,webhook: (id: string) => generatePath(`${x}/settings/webhooks/${id}`),webhooks: `${x}/settings/webhooks`,- workCenters: `${x}/resources/work-centers`,workCenter: (id: string) =>generatePath(`${x}/resources/work-centers/${id}`),workCenterActivate: (id: string) =>- generatePath(`${x}/resources/work-centers/activate/${id}`)+ generatePath(`${x}/resources/work-centers/activate/${id}`),+ workCenters: `${x}/resources/work-centers`}} as const;@@ -2044,3 +2122,24 @@ export const getPrivateUrl = (path: string) => {export const getPublicModelUrl = (path: string) => {return `/file/model/public/${path}`;};++// Map an item to its type-specific detail route. Used where a CO references an+// item by name and we want a link to the item page. Assemblies and unknown/blank+// types default to the Part route (assemblies are Parts in practice).+export const getItemDetailPath = (+ type: string | null | undefined,+ id: string+): string => {+ switch (type) {+ case "Tool":+ return path.to.tool(id);+ case "Material":+ return path.to.material(id);+ case "Consumable":+ return path.to.consumable(id);+ case "Service":+ return path.to.service(id);+ default:+ return path.to.part(id);+ }+};diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.tsindex 18ff7471f5..c7d6603ece 100644--- a/apps/mes/app/utils/path.ts+++ b/apps/mes/app/utils/path.ts@@ -10,6 +10,11 @@ const file = `/file`;export const path = {to: {+ accountSettings: `${ERP_URL}/x/account`,+ acknowledge: `${x}/acknowledge`,+ active: `${x}/active`,+ addAndIssueMaintenanceDispatchItem: (dispatchId: string) =>+ generatePath(`${x}/dispatch/${dispatchId}/add-and-issue`),api: {batchNumbers: (itemId: string) =>generatePath(`${api}/batch-numbers?itemId=${itemId}`),@@ -28,6 +33,19 @@ export const path = {`${api}/suggested-allocation?itemId=${itemId}&locationId=${locationId}&quantity=${quantity}`)},+ assigned: `${x}/assigned`,+ authenticatedRoot: x,+ callback: "/callback",+ companySwitch: (companyId: string) =>+ generatePath(`${x}/company/switch/${companyId}`),+ complete: `${x}/complete`,+ consolePinIn: `${x}/console/pin-in`,+ consolePinOut: `${x}/console/pin-out`,+ consoleToggle: `${x}/console/toggle`,+ convertEntity: (id: string) => generatePath(`${x}/entity/${id}/convert`),+ endOperation: (id: string) => generatePath(`${x}/end/${id}`),+ endShift: `${x}/end-shift`,+ feedback: `${x}/feedback`,file: {jobTraveler: (id: string) => `${getAppUrl()}${file}/traveler/${id}.pdf`,operationLabelsPdf: (@@ -66,14 +84,14 @@ export const path = {return generatePath(url);},+ previewFile: (path: string) => generatePath(`${file}/preview/${path}`),previewImage: (bucket: string, path: string) =>generatePath(`${file}/preview/image?file=${bucket}/${path}`),- previewFile: (path: string) => generatePath(`${file}/preview/${path}`),- trackedEntityLabelZpl: (+ trackedEntityLabelPdf: (id: string,{ labelSize }: { labelSize?: string } = {}) => {- let url = `${file}/entity/${id}/labels.zpl`;+ let url = `${file}/entity/${id}/labels.pdf`;const params = new URLSearchParams();if (labelSize) params.append("labelSize", labelSize);@@ -83,11 +101,11 @@ export const path = {return generatePath(url);},- trackedEntityLabelPdf: (+ trackedEntityLabelZpl: (id: string,{ labelSize }: { labelSize?: string } = {}) => {- let url = `${file}/entity/${id}/labels.pdf`;+ let url = `${file}/entity/${id}/labels.zpl`;const params = new URLSearchParams();if (labelSize) params.append("labelSize", labelSize);@@ -98,50 +116,42 @@ export const path = {return generatePath(url);}},- accountSettings: `${ERP_URL}/x/account`,- acknowledge: `${x}/acknowledge`,- active: `${x}/active`,- assigned: `${x}/assigned`,- authenticatedRoot: x,- callback: "/callback",- companySwitch: (companyId: string) =>- generatePath(`${x}/company/switch/${companyId}`),- complete: `${x}/complete`,- consolePinIn: `${x}/console/pin-in`,- consolePinOut: `${x}/console/pin-out`,- consoleToggle: `${x}/console/toggle`,- convertEntity: (id: string) => generatePath(`${x}/entity/${id}/convert`),- endShift: `${x}/end-shift`,- endOperation: (id: string) => generatePath(`${x}/end/${id}`),- feedback: `${x}/feedback`,finish: `${x}/finish`,health: "/health",- kanbanComplete: (id: string) => `${ERP_URL}/api/kanban/complete/${id}`,inspectionSteps: `${x}/steps/inspection`,inventoryAdjustment: `${x}/adjustment`,- jobDag: (id: string) => generatePath(`${x}/job/${id}`),- jobs: `${x}/jobs`,issue: `${x}/issue`,issueTrackedEntity: `${x}/issue-tracked-entity`,- qualityIssueNew: `${x}/quality-issue/new`,+ itemMaster: (itemId: string, type: string) =>+ `${getAppUrl()}${x}/${type.toLowerCase()}/${itemId}/details`,+ jobDag: (id: string) => generatePath(`${x}/job/${id}`),+ jobDetail: (id: string) => `${getAppUrl()}${x}/job/${id}/details`,+ jobs: `${x}/jobs`,+ kanbanComplete: (id: string) => `${ERP_URL}/api/kanban/complete/${id}`,location: `${x}/location`,- manualPrint: `${x}/print`,login: "/login",logout: "/logout",maintenance: `${x}/maintenance`,maintenanceDetail: (id: string) => generatePath(`${x}/dispatch/${id}`),maintenanceDispatchItem: (id: string) =>generatePath(`${x}/dispatch/${id}/item`),- addAndIssueMaintenanceDispatchItem: (dispatchId: string) =>- generatePath(`${x}/dispatch/${dispatchId}/add-and-issue`),maintenanceEvent: `${x}/maintenance-event`,+ manualPrint: `${x}/print`,messagingNotify: `${x}/proxy/api/messaging/notify`,newMaintenanceDispatch: `${x}/dispatch/new`,onboarding: `${ERP_URL}/onboarding`,- printingSettings: `${ERP_URL}/x/settings/printing`,operation: (id: string) => generatePath(`${x}/operation/${id}`),operations: `${x}/operations?saved=1`,+ picking: `${x}/picking`,+ pickingDetail: (id: string) => generatePath(`${x}/picking/${id}`),+ pickingLineQuantity: (id: string) =>+ generatePath(`${x}/picking/${id}/line/quantity`),+ pickingStatus: (id: string) => generatePath(`${x}/picking/${id}/status`),+ pickingTracked: (id: string, lineId: string) =>+ generatePath(`${x}/picking/${id}/tracked/${lineId}`),+ printingSettings: `${ERP_URL}/x/settings/printing`,productionEvent: `${x}/event`,+ qualityIssueNew: `${x}/quality-issue/new`,recent: `${x}/recent`,record: `${x}/record`,recordDelete: (id: string) => generatePath(`${x}/record/${id}/delete`),@@ -150,33 +160,23 @@ export const path = {rework: `${x}/rework`,reworkTargets: (operationId: string) =>generatePath(`${x}/rework-targets/${operationId}`),- triggerRework: `${x}/trigger-rework`,root: "/",scrap: `${x}/scrap`,- scrapReasons: `${api}/scrap-reasons`,scrapEntity: (operationId: string, id: string, parentId?: string) => {const basePath = generatePath(`${x}/entity/${operationId}/${id}/scrap`);return parentId ? `${basePath}?parentId=${parentId}` : basePath;},+ scrapReasons: `${api}/scrap-reasons`,startOperation: (id: string) => generatePath(`${x}/start/${id}`),+ suggestion: `${x}/suggestion`,switchCompany: (companyId: string) =>generatePath(`${x}/company/switch/${companyId}`),- suggestion: `${x}/suggestion`,- timecard: `${api}/timecard`,timeCardPage: `${x}/timecard`,+ timecard: `${api}/timecard`,+ triggerRework: `${x}/trigger-rework`,unconsume: `${x}/unconsume`,- picking: `${x}/picking`,- pickingDetail: (id: string) => generatePath(`${x}/picking/${id}`),- pickingLineQuantity: (id: string) =>- generatePath(`${x}/picking/${id}/line/quantity`),- pickingTracked: (id: string, lineId: string) =>- generatePath(`${x}/picking/${id}/tracked/${lineId}`),- pickingStatus: (id: string) => generatePath(`${x}/picking/${id}/status`),workCenter: (workCenter: string) =>- generatePath(`${x}/operations/${workCenter}`),- itemMaster: (itemId: string, type: string) =>- `${getAppUrl()}${x}/${type.toLowerCase()}/${itemId}/details`,- jobDetail: (id: string) => `${getAppUrl()}${x}/job/${id}/details`+ generatePath(`${x}/operations/${workCenter}`)}} as const;diff --git a/biome.jsonc b/biome.jsoncindex 30a3b31eb1..0d61d1a1d0 100644--- a/biome.jsonc+++ b/biome.jsonc@@ -122,6 +122,13 @@}},"overrides": [+ {+ // Keep the typed path helpers alphabetically sorted. Applies on+ // `biome check --write` (pre-commit lint-staged + CI), not plain+ // `biome format`, which does not run assists.+ "includes": ["**/erp/app/utils/path.ts", "**/mes/app/utils/path.ts"],+ "assist": { "actions": { "source": { "useSortedKeys": "on" } } }+ },{"linter": {"rules": {diff --git a/docs/content/docs/reference/change-orders/change-types.mdx b/docs/content/docs/reference/change-orders/change-types.mdxnew file mode 100644index 0000000000..ff1319ba05--- /dev/null+++ b/docs/content/docs/reference/change-orders/change-types.mdx@@ -0,0 +1,72 @@+---+title: Change types+description: Version, Revision, and New Part — the per-affected-item choice that decides what you can edit and what release creates.+---++Change type is set per affected item (default **Version**) and is the most load-bearing field on the whole+change order. It decides two things at once: what you're allowed to edit on the draft, and what release+creates from it.++## The three types++| Change type | You edit | Release creates | Auto-supersession |+| --- | --- | --- | --- |+| Version | BoM and BoP on the **same item** | A new **method version**; the prior Active version is archived | None |+| Revision | Attributes, documents, BoM and BoP | A new **item revision** (same Part ID, next revision letter) | Old revision → new revision |+| New Part | Attributes, BoM and BoP | A brand-new **part number** derived from the affected part | Affected part → new part |++<Callout type="info" title="A Version bumps the method, not the item.">+Don't conflate the two. A **Version** produces a new recipe version on the *same* item row, so existing stock+and item history are untouched and nothing is superseded. A **Revision** and a **New Part** each mint a *new*+item row and leave the old one intact — which is why they auto-write a <Term>supersession</Term> so planning+knows to phase over. See [Supersession & cutover](/docs/reference/change-orders/supersession).+</Callout>++## When to use which++- **Version** — the design is the same part, made a little differently. A tweaked operation, a swapped+ component, a corrected quantity. There's no drawing-revision story and no reason to phase over stock.+- **Revision** — the part is formally revising (new drawing revision, new dimension) and you want old and new+ to coexist while stock phases over. This is the everyday engineering-change case.+- **New Part** — the change is significant enough to warrant a new part number, derived from the old one, with+ the old part superseded by it.++## What each type gates++Change type also controls the editable surface on the affected item:++- **Version** exposes the **Bill of Material** and **Bill of Process** editors on the draft method.+- **Revision** and **New Part** add **Part Properties** (attributes) and documents on top of BoM and BoP,+ because they're producing a genuinely new item, not just a new recipe.++<Callout type="warning" title="Purchased items and New Part have limits.">+A purchased (**Buy**) item has no bill of materials or process, so a **Version** is meaningless for it —+adding a Buy item coerces its change type to **Revision** (attributes and documents only). **New Part** is+restricted to Parts and Tools.+</Callout>++## Supplier parts on a purchased line++A **Revision** or **New Part** whose draft item is purchased (**Buy** or **Buy and Make**) gets a **Supplier+Parts** grid on its line, right alongside the properties editor. You use it to set up how the new part or+revision is bought: **Supplier**, **Supplier ID** (the supplier's own part number), **Unit Price**, **Unit of+Measure**, **Minimum Order Quantity**, and **Conversion Factor**. Add, edit, and delete rows here the same way+you would on a live part.++<Callout type="warning" title="Set suppliers up before you release, or the released part can't be bought.">+A draft item starts with **no** supplier parts — the source item's suppliers aren't copied onto the draft. If a+purchased Revision or New Part releases with an empty grid, the new part is stocked but has no way to buy it,+so a purchase order can't reference it. Fill the grid on the line first. The suppliers you add show up in the+change order's [changes](/docs/reference/change-orders/lifecycle#review-the-changes-then-release) as additions.+</Callout>++## Related++<Cards>+ <Card title="Lifecycle & release" href="/docs/reference/change-orders/lifecycle">+ What release does with each change type.+ </Card>+ <Card title="Methods & sourcing" href="/docs/reference/methods">+ Method versions and the Draft/Active/Archived states a change order drives.+ </Card>+</Cards>diff --git a/docs/content/docs/reference/change-orders/creating.mdx b/docs/content/docs/reference/change-orders/creating.mdxnew file mode 100644index 0000000000..e54ee1657a--- /dev/null+++ b/docs/content/docs/reference/change-orders/creating.mdx@@ -0,0 +1,73 @@+---+title: Create a change order+description: The entry points that open a change order, the fields on the create form, and how change orders surface back on a part or tool page.+---++There's no single "new change order" button tucked in one menu. Carbon lets you start a change order from+wherever you notice the change is needed — a standalone form, the part you're looking at, its method version+menu, or a quality issue. Every path lands on the same change-order detail page.++## Entry points++<FieldTable>+ <Field name="Items → Change Orders → New">The standalone form. Start here when the change spans several parts or you haven't opened a specific one yet.</Field>+ <Field name="Part or Tool header → Create Change Order">Opens the create form as a modal with the current part or tool pre-attached as the first affected item.</Field>+ <Field name="Parts table → row menu → Create Change Order">A one-click start: mints the change order, attaches that part, and drops you on its detail page.</Field>+ <Field name="Method version menu → New Change Order">On a part's method, the same version menu that holds **New Version** offers **New Change Order** — the natural place to reach for a change while you're looking at the recipe.</Field>+ <Field name="Quality issue → Create Change Order">From a non-conformance, this opens a change order with the issue linked, so the engineering fix is traceable back to the problem that prompted it.</Field>+</FieldTable>++<Callout type="info" title="Starting from a part pre-attaches it.">+The part-header, parts-table, and method-version entry points all pre-select the part or tool as the change+order's first affected item, so you land ready to pick a change type and edit. The standalone form leaves the+**Affected Parts & Tools** field empty for you to fill.+</Callout>++## The create form++The header form is short — the substance is in the affected items you edit later.++<FieldTable>+ <Field name="Name" required>What this change is, in a line.</Field>+ <Field name="Category">The change-order type, drawn from your configured categories. See [Categories & actions](/docs/reference/change-orders/setup).</Field>+ <Field name="Reason for Change">Why the change is needed. Rich text.</Field>+ <Field name="Description of Change">What's changing, in narrative. Rich text.</Field>+ <Field name="Owner">The employee responsible.</Field>+ <Field name="Priority">Low, Medium, or High.</Field>+ <Field name="Open Date" required>Defaults to today.</Field>+ <Field name="Due Date">Optional target.</Field>+ <Field name="Linked NCR">A non-conformance this change resolves. Pre-filled when you started from a quality issue.</Field>+ <Field name="Affected Parts & Tools">The parts and tools to change. Parts and tools only; you can add more from the detail page later.</Field>+</FieldTable>++Submitting creates the change order, attaches any affected items, and redirects to its detail page at+**"Draft"**.++## Where change orders surface on a part++Change orders don't just live in their own list — they show up on the parts and tools they touch, so nobody+edits a design that's mid-change without seeing it.++- **Open change order alert.** When a part is on one or more change orders that haven't reached **"Done"**,+ its detail page shows a warning: *"This part is on 1 open change order"* (or *"…# open change orders"*),+ with each change order id linked. This is the guardrail against two people revising the same part blind.+- **Change Orders history.** A card lists every change order that has touched the part, newest first, with+ released ones de-emphasized — the full "why did this part change?" trail.+- **Provenance back-link.** A revision or part created by a released change order carries a *"Created by+ CN-…"* reference to the change order that made it.++<Callout type="note" title="Change orders are numbered CN-.">+Each change order gets a per-company readable id like **CN-000001**. That's the id you'll see in the alert,+the history card, and the provenance link.+</Callout>++## Related++<Cards>+ <Card title="Change types" href="/docs/reference/change-orders/change-types">+ What you set on each affected item once it's attached.+ </Card>+ <Card title="Revise a part" href="/guides/change-order">+ The same flow told as a story.+ </Card>+</Cards>diff --git a/docs/content/docs/reference/change-orders/index.mdx b/docs/content/docs/reference/change-orders/index.mdxnew file mode 100644index 0000000000..d3260b082b--- /dev/null+++ b/docs/content/docs/reference/change-orders/index.mdx@@ -0,0 +1,75 @@+---+title: Change orders+description: How Carbon drafts an engineering change against real methods, reviews it as a diff, and releases it so downstream planning supersedes the versions it replaces.+---++A **change order** groups the parts and tools whose designs are changing, revises each one on a hidden+draft, and releases them together. It answers "what changed, who owns it, and what does the new version+supersede?" without touching a live method until you release.++The model is deliberately top-down. You pick the affected items first, then edit each item's real+<Term id="bom">method</Term> (its bill of materials and bill of process) inside the change order. Nothing+about the part moves for planning, jobs, or costing until release. Change orders live under **Items → Change+Orders**, and every action is gated by the `parts` permission.++## The affected item is the unit of work++A change order is a header plus a list of **affected items**. The picker accepts **Parts and Tools only** —+materials, consumables, and services carry no engineering revision, so they're excluded. Each affected item+carries its own <Term id="change-order-change-type">change type</Term>, its own edits, and its own cutover+configuration.++Adding an affected item snapshots the item's live **Active** method into a new **Draft** method stamped with+the change order's id. That draft is hidden from every version switcher, copy-target picker, and MRP, job, or+cost read until release. You edit it with the same **Bill of Material**, **Bill of Process**, and **Part+Properties** editors you use anywhere else.++<Callout type="note" title="The draft is a real method, not a staged copy.">+Carbon does not mirror your edits into shadow tables. An affected item's edits live on an actual make method+whose change-order id is set, which is why the diff is exact and release is just an activation. The draft is+invisible everywhere else precisely because that id is set — clearing it at release is what makes the draft+live.+</Callout>++## Find one in the list++**Items → Change Orders** lists every change order. Because the affected item is the unit of work, each row+**expands** to reveal the parts and tools it changes — one line per affected item, with its change type badge+and, for a Revision or New Part, the old item number arrowed to the new one (**P000123 → P000124**). You see+what a change order touches without opening it.++To find the change orders that touch a specific part, use the **Item** filter. Pick one or more items and the+list narrows to change orders that affect them. The **Items** column that backs the filter is hidden by+default; turn it on from the column toggle if you want it in view or in a CSV export.++## How the pieces fit++<Cards>+ <Card title="Create a change order" href="/docs/reference/change-orders/creating">+ Every entry point — the standalone form, a part or tool header, the parts table, the method version+ menu, and a quality issue — plus how change orders surface back on a part.+ </Card>+ <Card title="Change types" href="/docs/reference/change-orders/change-types">+ Version, Revision, and New Part: what each lets you edit and what release creates.+ </Card>+ <Card title="Lifecycle & release" href="/docs/reference/change-orders/lifecycle">+ The five stages, the diff review, the impact panel, and what release actually does.+ </Card>+ <Card title="Supersession & cutover" href="/docs/reference/change-orders/supersession">+ How a released revision phases over, and how MRP and Get Method honor it downstream.+ </Card>+ <Card title="Categories & actions" href="/docs/reference/change-orders/setup">+ The change-order category lookup and the reusable action-task templates.+ </Card>+</Cards>++## Related++<Cards>+ <Card title="Revise a part" href="/guides/change-order">+ The narrative tour: draft a change, review the diff, release, and let supersession carry it downstream.+ </Card>+ <Card title="Methods & sourcing" href="/docs/reference/methods">+ Method versions, Draft/Active/Archived, and Get Method — the machinery a change order drives.+ </Card>+</Cards>diff --git a/docs/content/docs/reference/change-orders/lifecycle.mdx b/docs/content/docs/reference/change-orders/lifecycle.mdxnew file mode 100644index 0000000000..8952c6af20--- /dev/null+++ b/docs/content/docs/reference/change-orders/lifecycle.mdx@@ -0,0 +1,99 @@+---+title: Lifecycle & release+description: The five change-order stages, the impact panel, the diff review, and exactly what release does when a change order reaches Done.+---++A change order advances forward one stage at a time. There's no approval toggle and no going back — the+stages *are* the workflow, and the change order is its own release gate.++## The five stages++<StatusFlow>+ <Status name="Draft">The change order is being written. Pick affected items, set change types, and edit each draft method. Nothing is broadcast.</Status>+ <Status name="Start">Work is underway. Advancing to Start broadcasts a notification to the team.</Status>+ <Status name="Engineering Complete">The design edits are finished and ready for implementation review. Silent, no broadcast.</Status>+ <Status name="Implementation" accent>The release stage. The **"Release"** action is available here; it reviews every affected item's diff and applies the change. Advancing here broadcasts.</Status>+ <Status name="Done" terminal>Released and locked. The change order becomes a read-only historical record; broadcasts on entry.</Status>+</StatusFlow>++The **"Start"**, **"Implementation"**, and **"Done"** transitions each notify the team; **"Engineering+Complete"** is silent. Once a change order reaches **"Done"** it is locked — every editor is read-only.++## The impact panel++Alongside the affected items, a change order shows an **Impact** panel: a where-used tree for each affected+item across jobs, job materials, method materials, purchase orders, receipts, quotes, issues, maintenance,+and assembly instructions.++<Callout type="note" title="Impact is informational — it never blocks release.">+The panel is there so you can see what a change touches before you commit, not to gate you. Nothing in it+stops a release; the copy says as much: *"Where the affected items are used across the system. Informational —+nothing here blocks releasing."*+</Callout>++## Review the changes, then release++You don't have to wait for release to see what a change order does. The overview page carries a **Changes**+card, between the description and the action tasks, that rolls up **every** affected item's diff as you author+it — each item labeled with its change type, its diff rendered read-only. It's the same view the release dialog+shows, available the whole time so you can check your work before you commit. An item with nothing edited yet+reads *"No changes yet."*++Release itself lives on the change order at **"Implementation"**. The **"Release change order"** dialog lays out+that same per-item diff one more time before you commit — *"Review each item's changes, then confirm —+releasing can't be undone."*++Each item's diff compares its edited draft against the method it was snapshotted from, across four sections:++- **Bill of Materials** — added, removed, and modified BoM lines, field by field.+- **Bill of Process** — added, removed, and modified operations and their steps, parameters, and tools.+- **Properties** — changed item fields (name, description, unit of measure, tracking type, replenishment+ system, and the rest), one row per changed column.+- **Supplier Parts** — for a purchased Revision or New Part, the [suppliers you set up on the+ line](/docs/reference/change-orders/change-types#supplier-parts-on-a-purchased-line), each listed as an+ addition with its part number, unit price, min order qty, order multiple, conversion factor, and purchasing+ unit. A draft starts with none, so every supplier you add shows here.++<Callout type="info" title="The diff is exact because the draft is real.">+There's no shadow copy of your edits to drift out of sync. You edited an actual draft method, so the diff is+simply that draft compared against the live one it came from. What you review is exactly what releases.+</Callout>++## What release does++On confirm, Carbon walks the affected items and, per [change+type](/docs/reference/change-orders/change-types):++1. **Activates the draft method** — it becomes the new **Active** version and the prior Active version is+ **Archived** (kept as history, never deleted).+2. **Reveals the new item** — for a Revision or New Part, the newly created item is switched live and stamped+ with the change order id. A Version has no new item.+3. **Writes the supersession** — for a Revision or New Part, from the old item to the new one, using that+ affected item's cutover settings. See [Supersession &+ cutover](/docs/reference/change-orders/supersession).++When every affected item is processed, the change order flips to **"Done"**.++<Callout type="note" title="Release is idempotent, not one big transaction.">+Each affected item is marked done the moment its draft's change-order id is cleared, so a re-run skips items+already released and resumes at the first unreleased one. The final flip to **"Done"** is a compare-and-swap+on the **"Implementation"** status, so two people releasing at once can't double-apply.+</Callout>++## Parallel change orders on the same part++Two change orders can revise the same part at once. Each drafts its own method version, and Carbon steps+around version collisions so they don't clobber each other. Whichever releases second activates on top of the+first, and the earlier version is archived as history rather than overwritten — so no work is lost. There's no+merge-conflict step to resolve.++## Related++<Cards>+ <Card title="Supersession & cutover" href="/docs/reference/change-orders/supersession">+ How a released revision phases over downstream.+ </Card>+ <Card title="Revise a part" href="/guides/change-order">+ The release flow told as a story.+ </Card>+</Cards>diff --git a/docs/content/docs/reference/change-orders/meta.json b/docs/content/docs/reference/change-orders/meta.jsonnew file mode 100644index 0000000000..ece0019e34--- /dev/null+++ b/docs/content/docs/reference/change-orders/meta.json@@ -0,0 +1,5 @@+{+ "title": "Change orders",+ "defaultOpen": false,+ "pages": ["creating", "change-types", "lifecycle", "supersession", "setup"]+}diff --git a/docs/content/docs/reference/change-orders/setup.mdx b/docs/content/docs/reference/change-orders/setup.mdxnew file mode 100644index 0000000000..ece7b11ad8--- /dev/null+++ b/docs/content/docs/reference/change-orders/setup.mdx@@ -0,0 +1,49 @@+---+title: Categories & actions+description: The two company-scoped lookups that sit alongside change orders — the category list and the reusable action-task templates.+---++Two configuration lists live next to change orders in the Items nav. Both are company-scoped and edited by+employees with the `parts` permission.++## Change order categories++**Items → Change Order Types** holds the values for a change order's **"Category"** field — the same idea as+issue types in Quality. Carbon seeds three: *Design improvement*, *Obsolescence*, and *Cost reduction*. Add,+rename, or remove them to match how your shop classifies changes.++Category is descriptive: it groups and filters change orders, but it doesn't change how release behaves. That+job belongs to the [change type](/docs/reference/change-orders/change-types) on each affected item.++## Change order actions++**Items → Change Order Actions** holds reusable **action-task templates** — the checklist items a change+order commonly needs. Carbon seeds seven:++- Engineering Review+- Update Drawings / CAD+- Update BOM / Routing+- Cost Impact Review+- Quality Review+- Inventory Disposition (rework / scrap / use-as-is)+- Notify Affected Parties++A new change order can seed its task list from the active templates. On the change order, each task tracks a+status — **Pending**, **In Progress**, **Completed**, or **Skipped** — plus an assignee, due date, and notes.++<Callout type="note" title="Action tasks are freeform, not gates.">+Tasks are a coordination checklist, not an approval workflow. A task's status never blocks a stage from+advancing or a change order from releasing — the [stages](/docs/reference/change-orders/lifecycle) are the+only gate.+</Callout>++## Related++<Cards>+ <Card title="Create a change order" href="/docs/reference/change-orders/creating">+ Where the category is set and tasks are seeded.+ </Card>+ <Card title="Lifecycle & release" href="/docs/reference/change-orders/lifecycle">+ The stages that actually gate a change order.+ </Card>+</Cards>diff --git a/docs/content/docs/reference/change-orders/supersession.mdx b/docs/content/docs/reference/change-orders/supersession.mdxnew file mode 100644index 0000000000..6052bcc6b0--- /dev/null+++ b/docs/content/docs/reference/change-orders/supersession.mdx@@ -0,0 +1,63 @@+---+title: Supersession & cutover+description: How a released Revision or New Part phases over, the cutover fields you tune per item, and how MRP and Get Method honor supersession downstream.+---++For every **Revision** and **New Part** affected item, release auto-writes a <Term>supersession</Term> from+the old item to the new one. You don't create it by hand — you only tune *how* the phase-over behaves, per+affected item, through the cutover fields. A **Version** change type supersedes nothing, because it's the same+item.++## Cutover fields++Set these on the affected item before you release.++<FieldTable>+ <Field name="Supersession Mode" type="enum" required>How planning treats the old item. See the modes below. Defaults to **Consume First**.</Field>+ <Field name="Discontinuation Date" type="date">When the old item stops being usable. Empty means no planned discontinuation.</Field>+ <Field name="Successor Effectivity Date" type="date">When the successor becomes effective for redirect. Empty means effective immediately at release.</Field>+</FieldTable>++## Supersession modes++The <Term id="supersession-mode">supersession mode</Term> controls what downstream planning does with the old+item:++| Mode | Behavior |+| --- | --- |+| Consume First | Exhaust on-hand of the old item, then redirect new demand to the successor. |+| Prefer New | Redirect new demand to the successor immediately. |+| Stock Only | Keep only a minimum service reserve of the old item; no production use. |+| No Stock | Drop the old item from planning entirely. |++<Callout type="info" title="Only Consume First and Prefer New redirect demand.">+Those two modes tell planning to route the old item's demand — times its conversion factor — to the+successor. Stock Only and No Stock govern the old item's own stocking rather than redirecting to a successor.+</Callout>++## How downstream honors it++Once a supersession is effective (on or after its successor-effectivity date), two systems act on it:++- **MRP** redirects planned demand for the old item to the successor, applying the conversion factor and+ collapsing multi-hop chains (if A was superseded by B and B by C, demand routes straight to C).+- **Get Method** substitutes the successor onto Buy and Pull bill-of-materials lines when a new job is+ created, recording the source item so the substitution is traceable.++<Callout type="warning" title="Release never touches work already in flight.">+Existing stock stays on the old item, and jobs already created keep the exact materials and method version+they were built against. Supersession only steers *forward* planning — a job created after the successor's+effectivity date picks up the new item; one created before it does not shift. That's what makes releasing safe+on a busy floor.+</Callout>++## Related++<Cards>+ <Card title="Reordering & planning" href="/docs/reference/reordering">+ How the replenishment system and reordering policy read supersession.+ </Card>+ <Card title="Change types" href="/docs/reference/change-orders/change-types">+ Which change types write a supersession, and which don't.+ </Card>+</Cards>diff --git a/docs/content/docs/reference/meta.json b/docs/content/docs/reference/meta.jsonindex 4a44511577..b95e87a231 100644--- a/docs/content/docs/reference/meta.json+++ b/docs/content/docs/reference/meta.json@@ -4,6 +4,7 @@"pages": ["items","methods",+ "change-orders","routings","work-centers","maintenance",diff --git a/docs/content/guides/change-order.mdx b/docs/content/guides/change-order.mdxnew file mode 100644index 0000000000..d011685fca--- /dev/null+++ b/docs/content/guides/change-order.mdx@@ -0,0 +1,131 @@+---+title: Revise a part+description: An engineering change, drafted against the real method, reviewed as a diff, and released so planning phases over on its own.+label: "(I)"+index: 0+flow: engineering-change+flowName: Engineering change+flowIndex: 4+---++The robot's arm bracket needs a thicker wall and one fewer fastener. In a lot of systems that means editing+the live part and hoping nothing in flight notices. Carbon makes you do it deliberately: you open a+<Term>change order</Term>, edit a hidden draft of the part's method, review exactly what changed, and release+when it's ready. Until that moment, every job, plan, and cost calculation still sees the old bracket.++> A change order is the paper trail and the workbench at once. You revise on a draft that no one else can+> see, and release turns that draft into the new truth.++## Start with the parts, not the change++You can start from **Items → Change Orders → New**, but you'll usually start from the bracket itself. Its part+header has a **"Create Change Order"** action, its row in the parts table has the same, and the method's+version menu — the one with **New Version** — offers **New Change Order** right where you're looking at the+recipe. Each of those pre-attaches the bracket as the first affected item. A change can even start from a+quality issue, which links the non-conformance to the change order so the fix traces back to the problem.++However you start, the header form is short: a **"Name"**, a **"Category"** (your change-order types, seeded+with *Design improvement*, *Obsolescence*, and *Cost reduction*), a **"Reason for Change"** and **"Description+of Change"**, an **"Owner"**, **"Priority"**, dates, and an optional **"Linked NCR"**. The affected item is+the unit of work, and the picker is deliberately narrow: **Parts and Tools only**. A raw material or a service+doesn't carry an engineering revision, so it never appears.++Before you touch the bracket, though, its own page already warned you this was coming. A part that's on an+open change order shows a heading right on its detail page — *"This part is on 1 open change order"* — with the+change order linked, so nobody revises a design that's already mid-change.++<Screenshot label="New change order form" caption="Name, category, reason, and the affected parts and tools — the header before any editing begins." ratio="wide" />++<Callout tone="blue" badge="TOP-DOWN, NOT BOTTOM-UP" title="You pick the parts first, then edit them in place.">+Carbon doesn't ask you to describe a change as a list of add-this, delete-that rows. You select the affected+part and then edit its actual bill of materials and bill of process inside the change order. The change is+whatever the finished draft says it is.+</Callout>++## Draft the change in place++Add the bracket and Carbon quietly snapshots its live <Term id="bom">method</Term> into a new **Draft**+version stamped to this change order. That draft is invisible everywhere else — it won't show in a version+switcher, a copy-target list, or anything MRP, jobs, or costing read. You edit it with the same **Bill of+Material** and **Bill of Process** editors you'd use on the part directly.++Before you edit, pick a **change type** on the affected item. It's the most consequential choice on the whole+change order, because it decides both what you can touch and what release will create.++<Screenshot label="Affected item with change-type selector" caption="The bracket's draft method open for editing, with its change type set on the item card." ratio="wide" />++- <Term id="change-order-change-type">Version</Term> revises how the *same* part is made. You edit its BoM and+ BoP; release publishes a new method version and archives the old one. No new part, nothing superseded.+- **Revision** mints a new revision of the part (same Part ID, next revision letter). You edit its attributes,+ documents, and method; release reveals the new revision.+- **New Part** derives a brand-new part number from this one. Release reveals it and points the old part at it.++<Callout tone="amber" badge="A VERSION MOVES THE METHOD, NOT THE PART" title="Only Revision and New Part create a new item.">+This trips people up. A **Version** bumps the recipe on the existing bracket, so existing stock and history+stay put and nothing is superseded. A **Revision** or a **New Part** creates a new item alongside the old+one, which is why each of those auto-writes a supersession at release. Pick the wrong type and you either+strand stock or fail to phase it over. A purchased part has no method to version, so adding a **Buy** item+lands on **Revision** automatically.+</Callout>++For the bracket we want the wall change to carry a new drawing revision and phase over cleanly, so this is a+**Revision**. You thicken the wall in the attributes, drop the extra fastener line from the BoM, and attach+the updated drawing — all on the draft.++<Callout tone="amber" badge="PURCHASED PARTS NEED A SUPPLIER" title="A bought revision releases un-buyable unless you set its supplier up first.">+If the revised part were purchased instead of made, its line would carry a **Supplier Parts** grid. The draft+starts with none, because the old revision's suppliers aren't copied over. Leave it empty and the new part+releases with nowhere to buy it — no purchase order can reference it. So for a **Buy** revision you add the+supplier, part number, price, and order quantities on the line before you release.+</Callout>++## Review the diff++Advance the change order through its stages: **Draft**, then **"Start"**, then **"Engineering Complete"**,+then **"Implementation"**. It only moves forward, one step at a time, and **"Start"**, **"Implementation"**,+and **"Done"** each notify the team. There's no separate approval step to configure — the stages are the+workflow, and the change order is its own gate.++You don't have to reach Implementation to see what you've done. The overview page carries a **Changes** card+that rolls up every affected item's diff as you edit — the dropped fastener, the thicker wall, any supplier you+added — so the review is available the whole time, not just at the gate.++At **"Implementation"** the **"Release"** action opens. It doesn't just apply the change: it shows you every+affected item's change as a read-only diff first. Materials added and removed, operations and their steps+changed, attributes that moved — laid out line by line against the method you snapshotted from.++<Screenshot label="Release change order — diff review" caption="The dropped fastener line and the thicker-wall attribute, shown as a diff before you confirm." ratio="tall" />++<Callout tone="neutral" badge="EXACT BY CONSTRUCTION" title="The diff is real because the draft is real.">+There's no shadow copy of your edits to drift out of sync. You edited an actual draft method, so the diff is+simply that draft compared against the live one it came from. What you review is exactly what releases.+</Callout>++## Release, and let supersession carry it++Confirm the release and Carbon walks the affected items. For the bracket revision it activates the draft+method, archives the prior version, reveals the new revision as a live item, and writes a+<Term>supersession</Term> from the old revision to the new one. When every item is done, the change order+flips to **"Done"** and locks as a read-only record.++You never wrote that supersession by hand. You only chose *how* it phases over, through the affected item's+cutover fields: a <Term id="supersession-mode">supersession mode</Term> (defaulting to **Consume First**), a+discontinuation date, and a successor effectivity date. From there, planning takes over.++<Figure illustration="conversion-factor" caption="Once effective, the old bracket's demand redirects to the new revision, times its conversion factor." />++**Consume First** exhausts on-hand of the old bracket before switching; **Prefer New** redirects new demand+immediately. Once the successor is effective, MRP redirects planned demand to the new revision and **Get+Method** substitutes it onto new jobs, recording where the substitution came from.++<Callout tone="green" badge="NOTHING IN FLIGHT SHIFTS" title="Release steers the future, not the past.">+Existing stock stays on the old bracket, and any job already created keeps the exact material and method+version it was built against. Supersession only touches forward planning — a job cut after the effectivity+date picks up the new revision, one cut before it does not. That's what makes releasing safe on a busy floor.+</Callout>++<Divider />++Afterward the new revision carries a *"Created by CN-…"* back-link to the change order that made it, and the+bracket's page shows its full change history. The trail from "the wall was too thin" to the released revision+is one click, and the floor never built a single bracket against a design that wasn't done.diff --git a/package.json b/package.jsonindex 24956c5a66..37b773f37e 100755--- a/package.json+++ b/package.json@@ -44,6 +44,7 @@"db:migrate:new": "pnpm --filter @carbon/database db:migrate:new","db:seed": "turbo run db:seed --no-cache","db:seed:dev": "pnpm --filter @carbon/database db:seed:dev --",+ "db:seed:change-orders": "pnpm --filter @carbon/database seed:change-orders --","db:types": "tsx scripts/generate-db-types.ts","deploy": "turbo run deploy","dev": "crbn up --no-portless",diff --git a/packages/auth/src/middleware/flash.client.ts b/packages/auth/src/middleware/flash.client.tsindex 859239f8ff..b67f1ae8c9 100644--- a/packages/auth/src/middleware/flash.client.ts+++ b/packages/auth/src/middleware/flash.client.ts@@ -17,9 +17,9 @@ export const flashClientMiddleware: MiddlewareFunction<const result = (rootData.result as Record<string, unknown>).result as Result | null;if (result?.success === true) {- toast.success(result.message);+ toast.success(result.message, { description: result.description });} else if (result?.message) {- toast.error(result.message);+ toast.error(result.message, { description: result.description });}}diff --git a/packages/auth/src/services/session.server.ts b/packages/auth/src/services/session.server.tsindex ce467af343..70ff413458 100644--- a/packages/auth/src/services/session.server.ts+++ b/packages/auth/src/services/session.server.ts@@ -88,6 +88,9 @@ export async function flash(request: Request, result: Result) {if (typeof result.success === "boolean") {session.flash("success", result.success);session.flash("message", result.message);+ if (result.description) {+ session.flash("description", result.description);+ }if (result.flash) {session.flash("flash", result.flash);}@@ -124,6 +127,7 @@ export async function getSessionFlash(request: Request) {const result: Result = {success: session.get("success") === true,message: session.get("message"),+ description: session.get("description"),flash: session.get("flash") as "success" | "error" | undefined};diff --git a/packages/auth/src/types.ts b/packages/auth/src/types.tsindex e652a86e34..c170c17ad4 100644--- a/packages/auth/src/types.ts+++ b/packages/auth/src/types.ts@@ -33,5 +33,7 @@ export type Permission = {export type Result = {success: boolean;message?: string;+ // Optional secondary line for the toast (e.g. the underlying error detail).+ description?: string;flash?: "success" | "error";};diff --git a/packages/auth/src/utils/result.ts b/packages/auth/src/utils/result.tsindex fbbbcbde32..e78609d430 100644--- a/packages/auth/src/utils/result.ts+++ b/packages/auth/src/utils/result.ts@@ -8,7 +8,7 @@ export function error(error: any, message = "Request failed"): Result {return {success: false,- message: message+ message};}diff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.jsonindex be45cf7a47..3dfbb4b0b4 100644--- a/packages/checks/src/conformance/baseline.json+++ b/packages/checks/src/conformance/baseline.json@@ -1,4 +1,6 @@[+ "module-shape::items::extra-models:changeOrder.models.ts",+ "module-shape::items::extra-service:changeOrder.service.ts","module-shape::settings::extra-service:backups.service.ts","module-shape::shared::extra-models:imports.models.ts","module-shape::shared::missing:ui",diff --git a/packages/config/tailwind/theme.css b/packages/config/tailwind/theme.cssindex a022d085eb..325da34844 100644--- a/packages/config/tailwind/theme.css+++ b/packages/config/tailwind/theme.css@@ -140,7 +140,6 @@/* ErrorBoundary (VOID//SYS) effects */--animate-scan: scan 6s linear infinite;--animate-flicker: flicker 1.6s steps(1, end) infinite;- --animate-marquee: marquee 24s linear infinite;--container-2xl: 1400px;}@@ -198,12 +197,3 @@opacity: 0.25;}}--@keyframes marquee {- from {- transform: translateX(0);- }- to {- transform: translateX(-100%);- }-}diff --git a/packages/database/package.json b/packages/database/package.jsonindex 058057ac38..c30ea42ac7 100644--- a/packages/database/package.json+++ b/packages/database/package.json@@ -33,6 +33,7 @@"db:migrate:new": "supabase migration new","db:seed": "tsx src/seed.ts","db:seed:dev": "tsx src/seed-dev.ts",+ "seed:change-orders": "tsx src/seed-change-orders.ts","deploy": "supabase link --project-ref $SUPABASE_PROJECT_ID && supabase db push","lint": "biome lint --write ","typecheck": "tsgo --noEmit"diff --git a/packages/database/src/audit.config.ts b/packages/database/src/audit.config.tsindex 5dd4d81c04..214a53fce8 100644--- a/packages/database/src/audit.config.ts+++ b/packages/database/src/audit.config.ts@@ -300,6 +300,16 @@ export const auditConfig = {}},+ changeOrder: {+ label: "Change Order",+ tables: {+ changeOrder: { role: "root" },+ changeOrderAffectedItem: { entityIdColumn: "changeOrderId" },+ changeOrderSupersession: { entityIdColumn: "changeOrderId" },+ changeOrderActionTask: { entityIdColumn: "changeOrderId" }+ }+ },+gauge: {label: "Gauge",tables: {diff --git a/packages/database/src/seed-change-orders.ts b/packages/database/src/seed-change-orders.tsnew file mode 100644index 0000000000..79f9970857--- /dev/null+++ b/packages/database/src/seed-change-orders.ts@@ -0,0 +1,1379 @@+/**+ * Change Orders seed script for Carbon+ *+ * Populates rich, re-runnable test data for the Change Orders (ECO) feature:+ * a bike-manufacturer catalog (parts, make methods with BOM + BOP), downstream+ * documents (open PO, in-progress job, sales order), an NCR, and seven change+ * orders spanning every stage of the flow (Draft → Start → Engineering+ * Complete → Implementation → Done).+ *+ * The change-content follows the v2 model: each CO selects affected items first+ * (changeOrderAffectedItem, with a per-item `changeType`), and each item's edits+ * live on a REAL CO-owned Draft `makeMethod` (`makeMethod.changeOrderId` set),+ * NOT in staging tables. Three change types are exercised:+ * - Version → a new Draft method version on the SAME item (copied from the+ * Active method, then edited). ECO-000001 is the worked example: it+ * swaps bracket PRT-001186.A → PRT-001186.B across four assemblies+ * (delete the bracketA BOM line on the draft + add bracketB) and+ * declares one manual changeOrderSupersession (bracketA → bracketB).+ * - Revision → a new inactive revision item (active:false, changeOrderId set)+ * with the method copied into its Draft (ECO-000004, SA-0065).+ * - New Part → a new inactive part number (new readableId) with the method+ * copied into its Draft (ECO-000004, derived from GA-0044).+ *+ * The pg connection needs SUPABASE_DB_URL, which lives in the repo-root+ * `.env.local` (not `.env`). Both are loaded below.+ *+ * Usage:+ * set -a; . ./.env.local; set +a+ * pnpm --filter @carbon/database seed:change-orders -- --company <companyId>+ * pnpm --filter @carbon/database seed:change-orders -- --email <email>+ *+ * Idempotency: at the start of the transaction the script deletes its own prior+ * seed for the company (by the exact readableIds / names it owns), so re-running+ * is clean and never touches unrelated data.+ */++import { existsSync } from "node:fs";+import path from "node:path";+import process from "node:process";+import { fileURLToPath } from "node:url";+import { parseArgs } from "node:util";+import * as dotenv from "dotenv";+import type { PoolClient } from "pg";+import { getPostgresConnectionPool } from "./client.ts";++// ---------------------------------------------------------------------------+// Environment — SUPABASE_DB_URL is in the repo-root .env.local (not .env).+// ---------------------------------------------------------------------------+const __dirname = path.dirname(fileURLToPath(import.meta.url));+// src/ -> packages/database/ -> packages/ -> repo root+const repoRoot = path.resolve(__dirname, "..", "..", "..");+dotenv.config();+for (const envPath of [+ path.join(repoRoot, ".env"),+ path.join(repoRoot, ".env.local")+]) {+ if (existsSync(envPath)) {+ dotenv.config({ path: envPath, override: true });+ }+}++// ---------------------------------------------------------------------------+// CLI args+// ---------------------------------------------------------------------------+const { values } = parseArgs({+ args: process.argv.slice(2).filter((a) => a !== "--"),+ options: {+ company: { type: "string", short: "c" },+ email: { type: "string", short: "e" }+ },+ strict: true+});++// ---------------------------------------------------------------------------+// Constants — the exact identifiers this script owns (used for delete-first).+// ---------------------------------------------------------------------------+const RICH = (text: string) =>+ JSON.stringify({+ type: "doc",+ content: [{ type: "paragraph", content: [{ type: "text", text }] }]+ });++// Purchased (Buy) parts — PRT-001186 appears twice (rev 0 = ".A", rev B = ".B").+const PURCHASED_PARTS = [+ { readableId: "PRT-001186", revision: "0", name: "Rear Dropout Bracket" },+ { readableId: "PRT-001186", revision: "B", name: "Rear Dropout Bracket v2" },+ { readableId: "FST-100", revision: "0", name: "M5 Bolt" },+ { readableId: "FST-101", revision: "0", name: "Alignment Dowel" },+ { readableId: "FST-102", revision: "0", name: "Locking Washer" },+ { readableId: "BRG-200", revision: "0", name: "Sealed Bearing" },+ { readableId: "CBL-300", revision: "0", name: "Cable Housing" }+] as const;++// Make parts — each gets an Active makeMethod with a BOM + BOP.+const MAKE_PARTS = [+ { readableId: "GA-0020", name: "Pedal4 Sync3 Stage 2" },+ { readableId: "GA-0022", name: "Pedal4 Sync3 Stage 3" },+ { readableId: "GA-0044", name: "Pedal4 Sync3 Stage 2 Alt" },+ { readableId: "SA-0065", name: "Pedal2 Sync3" },+ { readableId: "VEH0000001", name: "Pedal4 Sync3" },+ { readableId: "VEH000006", name: "Pedal2 Sync2" }+] as const;++// New-Part readableIds this seed mints (v2 New Part change type). Deterministic+// so delete-first cleanup can find them. (Revision new items reuse a seeded+// readableId with a bumped revision, so they're cleaned by the item delete.)+const NEW_PART_IDS = ["PRT-CO-NP1"];++const ALL_SEEDED_ITEM_IDS = [+ ...PURCHASED_PARTS.map((p) => p.readableId),+ ...MAKE_PARTS.map((p) => p.readableId),+ ...NEW_PART_IDS+];++const PROCESS_NAMES = ["Machining", "Welding", "Assembly", "Inspection"];+const WORK_CENTER_NAMES = [+ "CNC Mill",+ "Weld Cell",+ "Assembly Line 1",+ "QC Bench"+];+const SUPPLIER_NAMES = ["FastenerCo", "BracketWorks"];+const CUSTOMER_NAMES = ["VeloRetail", "CityBikes"];++const PO_ID = "PO-CO-001";+const JOB_ID = "J-CO-001";+const SO_ID = "SO-CO-001";+const NCR_ID = "NCR-CO-001";+const CHANGE_ORDER_IDS = [+ "ECO-000001",+ "ECO-000002",+ "ECO-000003",+ "ECO-000004",+ "ECO-000005",+ "ECO-000006",+ "ECO-000007"+];++// ---------------------------------------------------------------------------+// Company / context resolution+// ---------------------------------------------------------------------------+async function resolveContext(client: PoolClient) {+ let companyId = values.company;++ if (!companyId && values.email) {+ const res = await client.query(+ `SELECT utc."companyId"+ FROM "userToCompany" utc+ JOIN "user" u ON u.id = utc."userId"+ WHERE u.email = $1+ LIMIT 1`,+ [values.email]+ );+ if (res.rows.length === 0) {+ throw new Error(`No company found for email ${values.email}`);+ }+ companyId = res.rows[0].companyId;+ }++ if (!companyId) {+ // Fall back to the single non-system company if exactly one exists.+ const res = await client.query(+ `SELECT id FROM company WHERE id NOT IN ('system')`+ );+ if (res.rows.length === 1) {+ companyId = res.rows[0].id;+ } else {+ throw new Error(+ `Could not resolve company: pass --company <id> or --email <email> ` ++ `(found ${res.rows.length} companies).`+ );+ }+ }++ const companyRes = await client.query(+ `SELECT id, name FROM company WHERE id = $1`,+ [companyId]+ );+ if (companyRes.rows.length === 0) {+ throw new Error(`Company ${companyId} not found`);+ }+ const companyName = companyRes.rows[0].name as string;++ const userRes = await client.query(+ `SELECT "userId" FROM "userToCompany" WHERE "companyId" = $1 AND role = 'employee' LIMIT 1`,+ [companyId]+ );+ if (userRes.rows.length === 0) {+ throw new Error(`No employee user found for company ${companyId}`);+ }+ const userId = userRes.rows[0].userId as string;++ const locRes = await client.query(+ `SELECT id FROM location WHERE "companyId" = $1 LIMIT 1`,+ [companyId]+ );+ if (locRes.rows.length === 0) {+ throw new Error(`No location found for company ${companyId}`);+ }+ const locationId = locRes.rows[0].id as string;++ const nctRes = await client.query(+ `SELECT id FROM "nonConformanceType" WHERE "companyId" = $1 LIMIT 1`,+ [companyId]+ );+ if (nctRes.rows.length === 0) {+ throw new Error(`No nonConformanceType found for company ${companyId}`);+ }+ const nonConformanceTypeId = nctRes.rows[0].id as string;++ // Ensure UoM 'EA' exists (it should for any seeded company).+ const uomRes = await client.query(+ `SELECT code FROM "unitOfMeasure" WHERE "companyId" = $1 AND code = 'EA'`,+ [companyId]+ );+ if (uomRes.rows.length === 0) {+ throw new Error(`UoM 'EA' not found for company ${companyId}`);+ }++ return {+ companyId: companyId as string,+ companyName,+ userId,+ locationId,+ nonConformanceTypeId+ };+}++// Strict lookup: records are keyed by ids we just inserted, so a miss is a seed+// bug, not a runtime "maybe". Returns a definite value (satisfies+// noUncheckedIndexedAccess) and throws with the offending key otherwise.+function need<T>(rec: Record<string, T>, key: string): T {+ const v = rec[key];+ if (v === undefined) throw new Error(`Seed: missing "${key}"`);+ return v;+}++// ---------------------------------------------------------------------------+// Idempotency — delete this script's prior seed in FK-safe order.+// ---------------------------------------------------------------------------+async function deletePriorSeed(client: PoolClient, companyId: string) {+ // 0. v2: CO-owned drafts are SET NULL (not cascaded) when the CO is deleted, so+ // remove them WHILE the COs still exist. Delete CO-created items (Revision /+ // New Part, item.changeOrderId set) first — cascades their makeMethods — then+ // the Version draft methods (changeOrderId set) on existing items.+ const coSubquery = `SELECT id FROM "changeOrder" WHERE "companyId" = $1 AND "changeOrderId" = ANY($2)`;+ await client.query(+ `DELETE FROM item WHERE "companyId" = $1 AND "changeOrderId" IN (${coSubquery})`,+ [companyId, CHANGE_ORDER_IDS]+ );+ await client.query(+ `DELETE FROM "makeMethod" WHERE "changeOrderId" IN (${coSubquery})`,+ [companyId, CHANGE_ORDER_IDS]+ );++ // 1. Change orders (children cascade via ON DELETE CASCADE).+ await client.query(+ `DELETE FROM "changeOrder" WHERE "companyId" = $1 AND "changeOrderId" = ANY($2)`,+ [companyId, CHANGE_ORDER_IDS]+ );++ // 2. Seeded documents referencing items (must go before items).+ await client.query(+ `DELETE FROM "purchaseOrder" WHERE "companyId" = $1 AND "purchaseOrderId" = $2`,+ [companyId, PO_ID]+ );+ await client.query(+ `DELETE FROM job WHERE "companyId" = $1 AND "jobId" = $2`,+ [companyId, JOB_ID]+ );+ await client.query(+ `DELETE FROM "salesOrder" WHERE "companyId" = $1 AND "salesOrderId" = $2`,+ [companyId, SO_ID]+ );++ // 3. Method rows for the seeded items' make methods, then the items.+ // methodMaterial + methodOperation cascade off makeMethod, and makeMethod+ // cascades off item — but delete children explicitly for robustness in+ // case cascade rules differ.+ await client.query(+ `DELETE FROM "methodMaterial" mm+ USING "makeMethod" mk, item i+ WHERE mm."makeMethodId" = mk.id AND mk."itemId" = i.id+ AND i."companyId" = $1 AND i."readableId" = ANY($2)`,+ [companyId, ALL_SEEDED_ITEM_IDS]+ );+ await client.query(+ `DELETE FROM "methodOperation" mo+ USING "makeMethod" mk, item i+ WHERE mo."makeMethodId" = mk.id AND mk."itemId" = i.id+ AND i."companyId" = $1 AND i."readableId" = ANY($2)`,+ [companyId, ALL_SEEDED_ITEM_IDS]+ );+ // 3b. Any remaining methodMaterial referencing a seeded item as a COMPONENT+ // (itemId), regardless of which method owns it — otherwise the item delete+ // below violates methodMaterial_itemId_fkey.+ await client.query(+ `DELETE FROM "methodMaterial" mm+ USING item i+ WHERE mm."itemId" = i.id+ AND i."companyId" = $1 AND i."readableId" = ANY($2)`,+ [companyId, ALL_SEEDED_ITEM_IDS]+ );++ // 4. The seeded items (makeMethod + itemCost cascade off item). The `part`+ // extension row is positional (part.id = readableId), not FK-cascaded —+ // delete it explicitly.+ await client.query(+ `DELETE FROM item WHERE "companyId" = $1 AND "readableId" = ANY($2)`,+ [companyId, ALL_SEEDED_ITEM_IDS]+ );+ await client.query(+ `DELETE FROM part WHERE "companyId" = $1 AND id = ANY($2)`,+ [companyId, ALL_SEEDED_ITEM_IDS]+ );++ // 5. The seeded NCR.+ await client.query(+ `DELETE FROM "nonConformance" WHERE "companyId" = $1 AND "nonConformanceId" = $2`,+ [companyId, NCR_ID]+ );++ // 6. Seeded suppliers/customers/processes/work centers (by exact name).+ await client.query(+ `DELETE FROM supplier WHERE "companyId" = $1 AND name = ANY($2)`,+ [companyId, SUPPLIER_NAMES]+ );+ await client.query(+ `DELETE FROM customer WHERE "companyId" = $1 AND name = ANY($2)`,+ [companyId, CUSTOMER_NAMES]+ );+ await client.query(+ `DELETE FROM "workCenter" WHERE "companyId" = $1 AND name = ANY($2)`,+ [companyId, WORK_CENTER_NAMES]+ );+ await client.query(+ `DELETE FROM process WHERE "companyId" = $1 AND name = ANY($2)`,+ [companyId, PROCESS_NAMES]+ );+}++// ---------------------------------------------------------------------------+// Small helpers+// ---------------------------------------------------------------------------+type Ctx = {+ client: PoolClient;+ companyId: string;+ userId: string;+ locationId: string;+};++async function createPurchasedItem(+ ctx: Ctx,+ def: { readableId: string; revision: string; name: string }+): Promise<string> {+ const { client, companyId, userId } = ctx;+ const res = await client.query(+ `INSERT INTO item (+ "readableId", revision, name, type, "replenishmentSystem",+ "defaultMethodType", "itemTrackingType", "unitOfMeasureCode",+ active, "companyId", "createdBy"+ ) VALUES ($1, $2, $3, 'Part', 'Buy', 'Purchase to Order', 'Inventory', 'EA', true, $4, $5)+ RETURNING id`,+ [def.readableId, def.revision, def.name, companyId, userId]+ );+ const itemId = res.rows[0].id as string;+ // NB: the item-insert interceptor already creates the itemCost / itemReplenishment+ // / makeMethod rows — do NOT insert itemCost here or the `parts` view fans out+ // (it joins itemCost, so a duplicate row doubles every part in the list).+ // The `part` extension row is what the Parts list/view joins on (part.id =+ // item.readableId, per revision). ON CONFLICT: multiple revisions share one+ // part row.+ await client.query(+ `INSERT INTO part (id, "companyId", "createdBy") VALUES ($1, $2, $3)+ ON CONFLICT DO NOTHING`,+ [def.readableId, companyId, userId]+ );+ return itemId;+}++async function createMakeItem(+ ctx: Ctx,+ def: { readableId: string; name: string }+): Promise<{ itemId: string; makeMethodId: string }> {+ const { client, companyId, userId } = ctx;+ const res = await client.query(+ `INSERT INTO item (+ "readableId", name, type, "replenishmentSystem",+ "defaultMethodType", "itemTrackingType", "unitOfMeasureCode",+ active, "companyId", "createdBy"+ ) VALUES ($1, $2, 'Part', 'Make', 'Make to Order', 'Inventory', 'EA', true, $3, $4)+ RETURNING id`,+ [def.readableId, def.name, companyId, userId]+ );+ const itemId = res.rows[0].id as string;+ // itemCost is auto-created by the item-insert interceptor — do NOT duplicate+ // it (the `parts` view joins itemCost and would fan out). See createPurchasedItem.+ // `part` extension row (see createPurchasedItem) — required for the Parts view.+ await client.query(+ `INSERT INTO part (id, "companyId", "createdBy") VALUES ($1, $2, $3)+ ON CONFLICT DO NOTHING`,+ [def.readableId, companyId, userId]+ );+ // The item insert auto-creates a Draft makeMethod via a DB interceptor.+ const mmRes = await client.query(+ `SELECT id FROM "makeMethod" WHERE "itemId" = $1 ORDER BY version LIMIT 1`,+ [itemId]+ );+ if (mmRes.rows.length === 0) {+ throw new Error(`No auto-created makeMethod for item ${def.readableId}`);+ }+ const makeMethodId = mmRes.rows[0].id as string;+ await client.query(+ `UPDATE "makeMethod" SET status = 'Active', "updatedBy" = $2 WHERE id = $1`,+ [makeMethodId, userId]+ );+ return { itemId, makeMethodId };+}++async function addBomLine(+ ctx: Ctx,+ makeMethodId: string,+ componentItemId: string,+ quantity: number,+ order: number+) {+ const { client, companyId, userId } = ctx;+ await client.query(+ `INSERT INTO "methodMaterial" (+ "makeMethodId", "methodType", "itemType", "itemId", quantity,+ "unitOfMeasureCode", "companyId", "createdBy", "order",+ "scrapQuantity", kit, "storageUnitIds", "sourcingType"+ ) VALUES ($1, 'Pull from Inventory', 'Part', $2, $3, 'EA', $4, $5, $6, 0, false, '{}', 'Specified')`,+ [makeMethodId, componentItemId, quantity, companyId, userId, order]+ );+}++async function addBopOperation(+ ctx: Ctx,+ makeMethodId: string,+ processId: string,+ workCenterId: string | null,+ description: string,+ order: number+) {+ const { client, companyId, userId } = ctx;+ await client.query(+ `INSERT INTO "methodOperation" (+ "makeMethodId", description, "companyId", "createdBy",+ "processId", "workCenterId", "order"+ ) VALUES ($1, $2, $3, $4, $5, $6, $7)`,+ [+ makeMethodId,+ description,+ companyId,+ userId,+ processId,+ workCenterId,+ order+ ]+ );+}++// ---------------------------------------------------------------------------+// Change-order builders+// ---------------------------------------------------------------------------+type ChangeOrderInput = {+ changeOrderId: string;+ name: string;+ status: string;+ changeOrderTypeId: string;+ assignee: string | null;+ reasonForChange?: string;+ description?: string;+ nonConformanceId?: string | null;+};++async function createChangeOrder(+ ctx: Ctx,+ input: ChangeOrderInput+): Promise<string> {+ const { client, companyId, userId } = ctx;+ const res = await client.query(+ `INSERT INTO "changeOrder" (+ "changeOrderId", name, "openDate", "createdBy", status, "companyId",+ type, "changeOrderTypeId", assignee,+ "reasonForChange", "description", "nonConformanceId"+ ) VALUES ($1, $2, $3, $4, $5, $6, 'Engineering', $7, $8, $9, $10, $11)+ RETURNING id`,+ [+ input.changeOrderId,+ input.name,+ "2026-07-09",+ userId,+ input.status,+ companyId,+ input.changeOrderTypeId,+ input.assignee,+ RICH(input.reasonForChange ?? "Reason for change to be documented."),+ RICH(input.description ?? "Description of change to be documented."),+ input.nonConformanceId ?? null+ ]+ );+ return res.rows[0].id as string;+}++// ---------------------------------------------------------------------------+// v2 change-content builders — CO-owned Draft make methods (no staging tables).+//+// Mirrors createChangeOrderDraftMethod (changeOrder.service.ts):+// Version → new Draft method version on the SAME item, copying the Active+// method's BOM + BOP rows; changeOrderId stamped.+// Revision → new inactive revision item (same readableId, bumped revision);+// New Part → new inactive item with a new readableId. Both copy the+// source method into the new item's (trigger-created) Draft method.+// The user then edits the Draft's real methodMaterial rows (delete/add lines).+// ---------------------------------------------------------------------------++// Copy an Active method's BOM + BOP rows onto a target Draft make method.+async function copyMethodRows(+ ctx: Ctx,+ sourceMakeMethodId: string,+ targetMakeMethodId: string+) {+ const { client } = ctx;+ await client.query(+ `INSERT INTO "methodMaterial" (+ "makeMethodId", "methodType", "itemType", "itemId", quantity,+ "unitOfMeasureCode", "companyId", "createdBy", "order",+ "scrapQuantity", kit, "storageUnitIds", "sourcingType", "materialMakeMethodId"+ )+ SELECT $1, "methodType", "itemType", "itemId", quantity,+ "unitOfMeasureCode", "companyId", "createdBy", "order",+ "scrapQuantity", kit, "storageUnitIds", "sourcingType", "materialMakeMethodId"+ FROM "methodMaterial" WHERE "makeMethodId" = $2`,+ [targetMakeMethodId, sourceMakeMethodId]+ );+ await client.query(+ `INSERT INTO "methodOperation" (+ "makeMethodId", description, "companyId", "createdBy",+ "processId", "workCenterId", "order", "operationOrder",+ "setupTime", "setupUnit", "laborTime", "laborUnit",+ "machineTime", "machineUnit", "workInstruction"+ )+ SELECT $1, description, "companyId", "createdBy",+ "processId", "workCenterId", "order", "operationOrder",+ "setupTime", "setupUnit", "laborTime", "laborUnit",+ "machineTime", "machineUnit", "workInstruction"+ FROM "methodOperation" WHERE "makeMethodId" = $2`,+ [targetMakeMethodId, sourceMakeMethodId]+ );+}++// Version: new Draft method version on the SAME item, copying the Active method.+async function createDraftVersionMethod(+ ctx: Ctx,+ changeOrderId: string,+ activeMakeMethodId: string,+ targetItemId: string+): Promise<string> {+ const { client, userId } = ctx;+ const vRes = await client.query(+ `SELECT COALESCE(MAX(version), 0) + 1 AS v FROM "makeMethod" WHERE "itemId" = $1`,+ [targetItemId]+ );+ const nextVersion = vRes.rows[0].v;+ const mmRes = await client.query(+ `INSERT INTO "makeMethod" ("itemId", status, version, "changeOrderId", "companyId", "createdBy")+ SELECT "itemId", 'Draft', $2, $3, "companyId", $4 FROM "makeMethod" WHERE id = $1+ RETURNING id`,+ [activeMakeMethodId, nextVersion, changeOrderId, userId]+ );+ const draftId = mmRes.rows[0].id as string;+ await copyMethodRows(ctx, activeMakeMethodId, draftId);+ return draftId;+}++// Revision / New Part: create a new inactive item (Revision = same readableId ++// bumped revision; New Part = a new readableId), copy the source method into its+// auto-created Draft, and stamp changeOrderId on both the item and the draft.+async function createDraftItemMethod(+ ctx: Ctx,+ changeOrderId: string,+ source: { itemId: string; makeMethodId: string },+ kind: "Revision" | "NewPart",+ newReadableId: string,+ revision: string+): Promise<{ itemId: string; draftMakeMethodId: string }> {+ const { client, companyId, userId } = ctx;+ const itemRes = await client.query(+ `INSERT INTO item (+ "readableId", revision, name, type, "replenishmentSystem",+ "defaultMethodType", "itemTrackingType", "unitOfMeasureCode",+ active, "revisionStatus", "changeOrderId", "companyId", "createdBy"+ )+ SELECT $1, $2, name, type, "replenishmentSystem",+ "defaultMethodType", "itemTrackingType", "unitOfMeasureCode",+ false, 'Design', $3, "companyId", $4+ FROM item WHERE id = $5+ RETURNING id`,+ [newReadableId, revision, changeOrderId, userId, source.itemId]+ );+ const newItemId = itemRes.rows[0].id as string;+ if (kind === "NewPart") {+ await client.query(+ `INSERT INTO part (id, "companyId", "createdBy") VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`,+ [newReadableId, companyId, userId]+ );+ }+ // The item-insert interceptor auto-creates a Draft makeMethod; copy into it.+ const mmRes = await client.query(+ `SELECT id FROM "makeMethod" WHERE "itemId" = $1 ORDER BY version LIMIT 1`,+ [newItemId]+ );+ if (mmRes.rows.length === 0) {+ throw new Error(`No auto-created makeMethod for new item ${newReadableId}`);+ }+ const draftMakeMethodId = mmRes.rows[0].id as string;+ await copyMethodRows(ctx, source.makeMethodId, draftMakeMethodId);+ await client.query(+ `UPDATE "makeMethod" SET "changeOrderId" = $1 WHERE id = $2`,+ [changeOrderId, draftMakeMethodId]+ );+ return { itemId: newItemId, draftMakeMethodId };+}++// Add an affected item with its CO-owned Draft per change type. Returns the+// affected-item id + the draft make method id (for subsequent BOM edits).+async function addAffectedItem(+ ctx: Ctx,+ changeOrderId: string,+ source: { itemId: string; makeMethodId: string },+ changeType: "Version" | "Revision" | "NewPart",+ sortOrder: number,+ opts: {+ supersessionMode?: string;+ newReadableId?: string;+ revision?: string;+ } = {}+): Promise<{+ affectedItemId: string;+ draftMakeMethodId: string;+ newItemId: string | null;+}> {+ const { client, companyId, userId } = ctx;++ let draftMakeMethodId: string;+ let newItemId: string | null = null;+ if (changeType === "Version") {+ draftMakeMethodId = await createDraftVersionMethod(+ ctx,+ changeOrderId,+ source.makeMethodId,+ source.itemId+ );+ } else {+ const created = await createDraftItemMethod(+ ctx,+ changeOrderId,+ source,+ changeType,+ opts.newReadableId ?? `PRT-CO-${changeType}`,+ opts.revision ?? "1"+ );+ draftMakeMethodId = created.draftMakeMethodId;+ newItemId = created.itemId;+ }++ // The seed's "NewPart" scenario derives a new part from a source + writes a+ // supersession — that is the 1:1 replacement, now named 'Replacement Part' (the+ // net-new 'New Part' has no predecessor and isn't seeded here).+ const changeTypeValue =+ changeType === "NewPart" ? "Replacement Part" : changeType;++ const aiRes = await client.query(+ `INSERT INTO "changeOrderAffectedItem" (+ "changeOrderId", "itemId", "sortOrder", "changeType",+ "draftMakeMethodId", "baseMakeMethodId", "newItemId",+ "supersessionMode", "companyId", "createdBy"+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING id`,+ [+ changeOrderId,+ source.itemId,+ sortOrder,+ changeTypeValue,+ draftMakeMethodId,+ source.makeMethodId,+ newItemId,+ opts.supersessionMode ?? "Consume First",+ companyId,+ userId+ ]+ );+ return {+ affectedItemId: aiRes.rows[0].id as string,+ draftMakeMethodId,+ newItemId+ };+}++// Delete a BOM line from a Draft make method (models "remove a line").+async function deleteDraftMaterial(+ ctx: Ctx,+ draftMakeMethodId: string,+ componentItemId: string+) {+ const { client, companyId } = ctx;+ await client.query(+ `DELETE FROM "methodMaterial"+ WHERE "makeMethodId" = $1 AND "itemId" = $2 AND "companyId" = $3`,+ [draftMakeMethodId, componentItemId, companyId]+ );+}++async function addSupersession(+ ctx: Ctx,+ changeOrderId: string,+ predecessorItemId: string,+ successorItemId: string,+ supersessionMode = "Consume First"+) {+ const { client, companyId, userId } = ctx;+ await client.query(+ `INSERT INTO "changeOrderSupersession" (+ "changeOrderId", "predecessorItemId", "successorItemId", "supersessionMode",+ "companyId", "createdBy"+ ) VALUES ($1, $2, $3, $4, $5, $6)`,+ [+ changeOrderId,+ predecessorItemId,+ successorItemId,+ supersessionMode,+ companyId,+ userId+ ]+ );+}++async function addActionTask(+ ctx: Ctx,+ changeOrderId: string,+ name: string,+ status: string,+ assignee: string | null,+ dueDate: string | null,+ sortOrder: number+) {+ const { client, companyId, userId } = ctx;+ await client.query(+ `INSERT INTO "changeOrderActionTask" (+ "changeOrderId", name, status, assignee, "dueDate", "sortOrder", "companyId", "createdBy"+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,+ [+ changeOrderId,+ name,+ status,+ assignee,+ dueDate,+ sortOrder,+ companyId,+ userId+ ]+ );+}++// ---------------------------------------------------------------------------+// Main+// ---------------------------------------------------------------------------+async function seed() {+ if (!process.env.SUPABASE_DB_URL) {+ console.error(+ "Error: SUPABASE_DB_URL is not set. Load it first:\n" ++ " set -a; . ./.env.local; set +a"+ );+ process.exit(1);+ }++ const pgPool = getPostgresConnectionPool(1);+ const client = await pgPool.connect();++ try {+ const { companyId, companyName, userId, locationId, nonConformanceTypeId } =+ await resolveContext(client);++ console.log(`\nSeeding Change Orders for "${companyName}" (${companyId})`);+ console.log(` user=${userId} location=${locationId}\n`);++ await client.query("BEGIN");++ try {+ const ctx: Ctx = { client, companyId, userId, locationId };++ // --- Idempotency: clear prior seed ---+ console.log("1. Clearing prior seed (if any)...");+ await deletePriorSeed(client, companyId);++ // --- Change order categories ---+ const cotRes = await client.query(+ `SELECT id, name FROM "changeOrderType" WHERE "companyId" = $1 AND name = ANY($2)`,+ [companyId, ["Design improvement", "Obsolescence", "Cost reduction"]]+ );+ const cotByName: Record<string, string> = {};+ for (const r of cotRes.rows) cotByName[r.name] = r.id;+ // Self-create the default categories if this company predates the+ // seed.data.ts defaults (older dev companies lack them).+ for (const name of [+ "Design improvement",+ "Obsolescence",+ "Cost reduction"+ ]) {+ if (!cotByName[name]) {+ const ins = await client.query(+ `INSERT INTO "changeOrderType" (name, "companyId", "createdBy") VALUES ($1, $2, $3) RETURNING id`,+ [name, companyId, userId]+ );+ cotByName[name] = ins.rows[0].id;+ }+ }+ const cotDesign = need(cotByName, "Design improvement");+ const cotObsolescence = need(cotByName, "Obsolescence");+ const cotCost = need(cotByName, "Cost reduction");++ // --- Processes ---+ console.log("2. Creating processes and work centers...");+ const processId: Record<string, string> = {};+ for (const name of PROCESS_NAMES) {+ const r = await client.query(+ `INSERT INTO process (name, "defaultStandardFactor", "companyId", "createdBy")+ VALUES ($1, 'Hours/Piece', $2, $3) RETURNING id`,+ [name, companyId, userId]+ );+ processId[name] = r.rows[0].id;+ }++ // --- Work centers ---+ const workCenterId: Record<string, string> = {};+ for (const name of WORK_CENTER_NAMES) {+ const r = await client.query(+ `INSERT INTO "workCenter" (name, "locationId", "companyId", "createdBy")+ VALUES ($1, $2, $3, $4) RETURNING id`,+ [name, locationId, companyId, userId]+ );+ workCenterId[name] = r.rows[0].id;+ }++ // --- Suppliers / customers ---+ console.log("3. Creating suppliers and customers...");+ const supplierId: Record<string, string> = {};+ for (const name of SUPPLIER_NAMES) {+ const r = await client.query(+ `INSERT INTO supplier (name, "companyId", "createdBy") VALUES ($1, $2, $3) RETURNING id`,+ [name, companyId, userId]+ );+ supplierId[name] = r.rows[0].id;+ }+ const customerId: Record<string, string> = {};+ for (const name of CUSTOMER_NAMES) {+ const r = await client.query(+ `INSERT INTO customer (name, "companyId", "createdBy") VALUES ($1, $2, $3) RETURNING id`,+ [name, companyId, userId]+ );+ customerId[name] = r.rows[0].id;+ }++ // --- Purchased items (keyed by readableId + '.' + revision) ---+ console.log("4. Creating purchased parts...");+ const purchased: Record<string, string> = {};+ for (const def of PURCHASED_PARTS) {+ const key = `${def.readableId}.${def.revision}`;+ purchased[key] = await createPurchasedItem(ctx, def);+ }+ // Convenience references.+ const bracketA = need(purchased, "PRT-001186.0"); // ".A"+ const bracketB = need(purchased, "PRT-001186.B"); // ".B"+ const fst100 = need(purchased, "FST-100.0");+ const fst101 = need(purchased, "FST-101.0");+ const fst102 = need(purchased, "FST-102.0");+ const brg200 = need(purchased, "BRG-200.0");+ const cbl300 = need(purchased, "CBL-300.0");++ // --- Make items with BOM + BOP ---+ console.log("5. Creating make parts with BOM + BOP...");+ const make: Record<string, { itemId: string; makeMethodId: string }> = {};+ for (const def of MAKE_PARTS) {+ make[def.readableId] = await createMakeItem(ctx, def);+ }+ const ga0020 = need(make, "GA-0020");+ const ga0022 = need(make, "GA-0022");+ const ga0044 = need(make, "GA-0044");+ const sa0065 = need(make, "SA-0065");+ const veh1 = need(make, "VEH0000001");+ const veh6 = need(make, "VEH000006");++ // BOMs+ await addBomLine(ctx, ga0020.makeMethodId, bracketA, 1, 1);+ await addBomLine(ctx, ga0020.makeMethodId, fst100, 4, 2);+ await addBomLine(ctx, ga0020.makeMethodId, brg200, 2, 3);+ await addBopOperation(+ ctx,+ ga0020.makeMethodId,+ need(processId, "Machining"),+ need(workCenterId, "CNC Mill"),+ "Machining",+ 1+ );+ await addBopOperation(+ ctx,+ ga0020.makeMethodId,+ need(processId, "Assembly"),+ need(workCenterId, "Assembly Line 1"),+ "Assembly",+ 2+ );++ await addBomLine(ctx, ga0022.makeMethodId, bracketA, 1, 1);+ await addBomLine(ctx, ga0022.makeMethodId, fst100, 2, 2);+ await addBopOperation(+ ctx,+ ga0022.makeMethodId,+ need(processId, "Assembly"),+ need(workCenterId, "Assembly Line 1"),+ "Assembly",+ 1+ );++ await addBomLine(ctx, ga0044.makeMethodId, bracketA, 1, 1);+ await addBomLine(ctx, ga0044.makeMethodId, cbl300, 1, 2);+ await addBopOperation(+ ctx,+ ga0044.makeMethodId,+ need(processId, "Assembly"),+ need(workCenterId, "Assembly Line 1"),+ "Assembly",+ 1+ );++ await addBomLine(ctx, sa0065.makeMethodId, bracketA, 1, 1);+ await addBomLine(ctx, sa0065.makeMethodId, fst101, 1, 2);+ await addBopOperation(+ ctx,+ sa0065.makeMethodId,+ need(processId, "Welding"),+ need(workCenterId, "Weld Cell"),+ "Welding",+ 1+ );+ await addBopOperation(+ ctx,+ sa0065.makeMethodId,+ need(processId, "Inspection"),+ need(workCenterId, "QC Bench"),+ "Inspection",+ 2+ );++ await addBomLine(ctx, veh1.makeMethodId, ga0020.itemId, 1, 1);+ await addBomLine(ctx, veh1.makeMethodId, ga0022.itemId, 1, 2);+ await addBomLine(ctx, veh1.makeMethodId, sa0065.itemId, 1, 3);+ await addBopOperation(+ ctx,+ veh1.makeMethodId,+ need(processId, "Assembly"),+ need(workCenterId, "Assembly Line 1"),+ "Assembly",+ 1+ );+ await addBopOperation(+ ctx,+ veh1.makeMethodId,+ need(processId, "Inspection"),+ need(workCenterId, "QC Bench"),+ "Inspection",+ 2+ );++ await addBomLine(ctx, veh6.makeMethodId, sa0065.itemId, 1, 1);+ await addBomLine(ctx, veh6.makeMethodId, ga0044.itemId, 1, 2);+ await addBopOperation(+ ctx,+ veh6.makeMethodId,+ need(processId, "Assembly"),+ need(workCenterId, "Assembly Line 1"),+ "Assembly",+ 1+ );++ // --- Downstream: PO, Job, Sales Order ---+ console.log("6. Creating downstream PO / Job / Sales Order...");++ // Open PO for PRT-001186.A (drives Implementation impact panel)+ const siRes = await client.query(+ `INSERT INTO "supplierInteraction" ("companyId", "supplierId") VALUES ($1, $2) RETURNING id`,+ [companyId, need(supplierId, "FastenerCo")]+ );+ const supplierInteractionId = siRes.rows[0].id;+ const poRes = await client.query(+ `INSERT INTO "purchaseOrder" (+ "purchaseOrderId", "supplierId", "supplierInteractionId", status,+ "purchaseOrderType", "exchangeRate", "companyId", "createdBy"+ ) VALUES ($1, $2, $3, 'To Receive', 'Purchase', 1, $4, $5) RETURNING id`,+ [+ PO_ID,+ need(supplierId, "FastenerCo"),+ supplierInteractionId,+ companyId,+ userId+ ]+ );+ const purchaseOrderId = poRes.rows[0].id;+ await client.query(+ `INSERT INTO "purchaseOrderDelivery" (id, "locationId", "companyId") VALUES ($1, $2, $3)`,+ [purchaseOrderId, locationId, companyId]+ );+ await client.query(+ `INSERT INTO "purchaseOrderLine" (+ "purchaseOrderId", "purchaseOrderLineType", "itemId",+ "purchaseQuantity", "quantityReceived", "quantityInvoiced",+ "supplierUnitPrice", "supplierShippingCost", "supplierTaxAmount",+ "exchangeRate", "setupPrice", "conversionFactor",+ "purchaseUnitOfMeasureCode", "inventoryUnitOfMeasureCode",+ "companyId", "createdBy"+ ) VALUES ($1, 'Part', $2, 200, 0, 0, 12.50, 0, 0, 1, 0, 1, 'EA', 'EA', $3, $4)`,+ [purchaseOrderId, bracketA, companyId, userId]+ );++ // In-progress job for VEH0000001+ await client.query(+ `INSERT INTO job (+ "jobId", "itemId", quantity, "locationId", status, "unitOfMeasureCode", "companyId", "createdBy"+ ) VALUES ($1, $2, 5, $3, 'In Progress', 'EA', $4, $5)`,+ [JOB_ID, veh1.itemId, locationId, companyId, userId]+ );++ // Sales order (To Ship) for VEH0000001+ const soRes = await client.query(+ `INSERT INTO "salesOrder" (+ "salesOrderId", "customerId", "currencyCode", status, "companyId", "createdBy"+ ) VALUES ($1, $2, 'USD', 'To Ship', $3, $4) RETURNING id`,+ [SO_ID, need(customerId, "VeloRetail"), companyId, userId]+ );+ const salesOrderId = soRes.rows[0].id;+ await client.query(+ `INSERT INTO "salesOrderShipment" (id, "locationId", "companyId") VALUES ($1, $2, $3)`,+ [salesOrderId, locationId, companyId]+ );+ await client.query(+ `INSERT INTO "salesOrderLine" (+ "salesOrderId", "salesOrderLineType", "itemId",+ "saleQuantity", "unitPrice", "unitOfMeasureCode", "companyId", "createdBy"+ ) VALUES ($1, 'Part', $2, 5, 899.00, 'EA', $3, $4)`,+ [salesOrderId, veh1.itemId, companyId, userId]+ );++ // --- NCR (linked from ECO-000001) ---+ console.log("7. Creating NCR...");+ const ncrRes = await client.query(+ `INSERT INTO "nonConformance" (+ "nonConformanceId", name, source, "locationId", "nonConformanceTypeId",+ "openDate", "companyId", "createdBy"+ ) VALUES ($1, $2, 'Internal', $3, $4, $5, $6, $7) RETURNING id`,+ [+ NCR_ID,+ "Derailleur thread failure under load",+ locationId,+ nonConformanceTypeId,+ "2026-07-05",+ companyId,+ userId+ ]+ );+ const ncrId = ncrRes.rows[0].id;++ // --- Change orders ---+ console.log("8. Creating change orders...");++ // ECO-000001 — Implementation+ const co1 = await createChangeOrder(ctx, {+ changeOrderId: "ECO-000001",+ name: "Sync 3 Derailleur Mount",+ status: "Implementation",+ changeOrderTypeId: cotDesign,+ assignee: userId,+ reasonForChange:+ "Field returns show the derailleur mount thread fails under sustained load. " ++ "Root-caused to the Rear Dropout Bracket geometry (see NCR-CO-001).",+ description:+ "Supersede Rear Dropout Bracket (PRT-001186.A) with the redesigned " ++ "PRT-001186.B across all affected assemblies. New CAD released via Onshape.",+ nonConformanceId: ncrId+ });+ // Top-to-bottom: the user selects the affected ASSEMBLIES first, then edits+ // each one's staged (snapshotted) BOM. Here the PRD change is swapping the+ // bracket PRT-001186.A → PRT-001186.B on every assembly that uses it.+ const co1Assemblies: {+ key: string;+ a: { itemId: string; makeMethodId: string };+ }[] = [+ { key: "GA-0020", a: ga0020 },+ { key: "GA-0022", a: ga0022 },+ { key: "GA-0044", a: ga0044 },+ { key: "SA-0065", a: sa0065 }+ ];+ let co1Sort = 0;+ for (const { a } of co1Assemblies) {+ // 1. Version change: spin a CO-owned Draft method (copy of Active).+ const { draftMakeMethodId } = await addAffectedItem(+ ctx,+ co1,+ a,+ "Version",+ co1Sort+++ );+ // 2. Edit the Draft's real BOM: remove bracketA (a "removed" line) and+ // add bracketB (an "added" line). The diff derives from Draft-vs-base.+ await deleteDraftMaterial(ctx, draftMakeMethodId, bracketA);+ await addBomLine(ctx, draftMakeMethodId, bracketB, 1, 1);+ }+ // Optional manual supersession row (bracketA → bracketB) to exercise that+ // surface (different-part obsolescence, distinct from the auto revision cutover).+ await addSupersession(ctx, co1, bracketA, bracketB, "Consume First");+ await addActionTask(+ ctx,+ co1,+ "Submit PRT-001186.B CAD for Onshape approval",+ "Completed",+ userId,+ null,+ 1+ );+ await addActionTask(+ ctx,+ co1,+ "Update work instruction WI-0089",+ "Pending",+ null,+ "2026-07-20",+ 2+ );++ // ECO-000002 — Engineering Complete+ const co2 = await createChangeOrder(ctx, {+ changeOrderId: "ECO-000002",+ name: "VEH3 Battery Lock Update",+ status: "Engineering Complete",+ changeOrderTypeId: cotDesign,+ assignee: userId,+ reasonForChange:+ "Battery lock rattle under vibration; replace fastener with a sealed bearing detent.",+ description:+ "Remove M5 Bolt from Stage 3 and add a Sealed Bearing detent."+ });+ // One affected item (GA-0022, Version): swap M5 Bolt → Sealed Bearing detent.+ const co2Affected = await addAffectedItem(ctx, co2, ga0022, "Version", 0);+ await deleteDraftMaterial(ctx, co2Affected.draftMakeMethodId, fst100);+ await addBomLine(ctx, co2Affected.draftMakeMethodId, brg200, 1, 1);++ // ECO-000003 — Start+ const co3 = await createChangeOrder(ctx, {+ changeOrderId: "ECO-000003",+ name: "Cargo Box Bracket Redesign",+ status: "Start",+ changeOrderTypeId: cotDesign,+ assignee: userId,+ reasonForChange:+ "Cargo box bracket alignment dowel is over-specified; remove to reduce cost and weight.",+ description: "Delete Alignment Dowel from Pedal2 Sync3 sub-assembly."+ });+ // One affected item (SA-0065, Version): delete the Alignment Dowel line.+ const co3Affected = await addAffectedItem(ctx, co3, sa0065, "Version", 0);+ await deleteDraftMaterial(ctx, co3Affected.draftMakeMethodId, fst101);++ // ECO-000004 — Start. Demonstrates the Revision + New Part change types.+ const co4 = await createChangeOrder(ctx, {+ changeOrderId: "ECO-000004",+ name: "Cable Routing Doc Update + FFF Replacement",+ status: "Start",+ changeOrderTypeId: cotDesign,+ assignee: userId,+ reasonForChange:+ "Documentation revision for the sub-assembly, plus a fit-form-function " ++ "replacement introduced as a new part number.",+ description:+ "Revision: bump SA-0065 for a non-FFF doc/spec update (new revision, " ++ "no BoM change). New Part: introduce a new P/N derived from GA-0044 " ++ "(FFF replacement), superseding it at release."+ });+ // Revision change type — new inactive revision item of SA-0065 (method+ // copied into its Draft; no BoM edit — Revision is docs/attrs only).+ await addAffectedItem(ctx, co4, sa0065, "Revision", 0);+ // New Part change type — a new part number derived from GA-0044.+ await addAffectedItem(ctx, co4, ga0044, "NewPart", 1, {+ newReadableId: NEW_PART_IDS[0]+ });+ await addActionTask(+ ctx,+ co4,+ "Reroute cable channel",+ "In Progress",+ userId,+ null,+ 1+ );++ // ECO-000005 — Done (already-applied CO)+ const co5 = await createChangeOrder(ctx, {+ changeOrderId: "ECO-000005",+ name: "Saddle Supersession Royal MW",+ status: "Done",+ changeOrderTypeId: cotObsolescence,+ assignee: userId,+ reasonForChange:+ "Original saddle supplier discontinued the SKU; superseded by Royal MW.",+ description:+ "Obsolescence supersession applied across affected vehicles."+ });+ await addActionTask(+ ctx,+ co5,+ "Confirm inventory drawdown of obsolete saddle",+ "Completed",+ userId,+ null,+ 1+ );++ // ECO-000006 — Draft (Unassigned, blank)+ await createChangeOrder(ctx, {+ changeOrderId: "ECO-000006",+ name: "Luxembourg Handlebar Stem",+ status: "Draft",+ changeOrderTypeId: cotCost,+ assignee: null+ });++ // ECO-000007 — Start. One affected item (VEH0000001, a top-level product not+ // touched by another open CO): add a Locking Washer to its staged BOM.+ const co7 = await createChangeOrder(ctx, {+ changeOrderId: "ECO-000007",+ name: "Fork Crown Reinforcement",+ status: "Start",+ changeOrderTypeId: cotDesign,+ assignee: userId,+ reasonForChange:+ "Add a locking washer to the fork crown assembly to prevent loosening.",+ description:+ "Add Locking Washer (FST-102) x2 to the top-level Pedal4 Sync3 assembly."+ });+ // Version change on the top-level product: add FST-102 to the Draft BOM.+ const co7Affected = await addAffectedItem(ctx, co7, veh1, "Version", 0);+ await addBomLine(ctx, co7Affected.draftMakeMethodId, fst102, 2, 99);++ // --- Bump the CO sequence past the seeded ids ---+ console.log("9. Bumping changeOrder sequence...");+ await client.query(+ `UPDATE sequence SET next = 8 WHERE "table" = 'changeOrder' AND "companyId" = $1 AND next < 8`,+ [companyId]+ );++ await client.query("COMMIT");+ console.log(" Transaction committed successfully.\n");++ await printSummary(client, companyId);+ } catch (err) {+ await client.query("ROLLBACK");+ console.error(" Transaction rolled back due to error.");+ throw err;+ }+ } catch (error) {+ console.error("\nError seeding change orders:");+ console.error(error);+ process.exit(1);+ } finally {+ client.release();+ await pgPool.end();+ }+}++// ---------------------------------------------------------------------------+// Summary+// ---------------------------------------------------------------------------+async function printSummary(client: PoolClient, companyId: string) {+ const q = async (sql: string, params: unknown[] = []) =>+ (await client.query(sql, params)).rows;++ const items = await q(+ `SELECT count(*)::int n FROM item WHERE "companyId" = $1 AND "readableId" = ANY($2)`,+ [companyId, ALL_SEEDED_ITEM_IDS]+ );+ const makeMethods = await q(+ `SELECT count(*)::int n FROM "makeMethod" mk JOIN item i ON i.id = mk."itemId"+ WHERE i."companyId" = $1 AND i."readableId" = ANY($2) AND mk.status = 'Active'`,+ [companyId, MAKE_PARTS.map((p) => p.readableId)]+ );+ const bomLines = await q(+ `SELECT count(*)::int n FROM "methodMaterial" mm JOIN "makeMethod" mk ON mk.id = mm."makeMethodId"+ JOIN item i ON i.id = mk."itemId" WHERE i."companyId" = $1 AND i."readableId" = ANY($2)`,+ [companyId, ALL_SEEDED_ITEM_IDS]+ );+ const bopOps = await q(+ `SELECT count(*)::int n FROM "methodOperation" mo JOIN "makeMethod" mk ON mk.id = mo."makeMethodId"+ JOIN item i ON i.id = mk."itemId" WHERE i."companyId" = $1 AND i."readableId" = ANY($2)`,+ [companyId, ALL_SEEDED_ITEM_IDS]+ );+ const cosByStatus = await q(+ `SELECT status, count(*)::int n FROM "changeOrder"+ WHERE "companyId" = $1 AND "changeOrderId" = ANY($2) GROUP BY status ORDER BY status`,+ [companyId, CHANGE_ORDER_IDS]+ );+ const affectedItems = await q(+ `SELECT count(*)::int n FROM "changeOrderAffectedItem" ai+ JOIN "changeOrder" co ON co.id = ai."changeOrderId"+ WHERE co."companyId" = $1 AND co."changeOrderId" = ANY($2)`,+ [companyId, CHANGE_ORDER_IDS]+ );+ const draftMethods = await q(+ `SELECT count(*)::int n FROM "makeMethod" mk+ JOIN "changeOrder" co ON co.id = mk."changeOrderId"+ WHERE co."companyId" = $1 AND co."changeOrderId" = ANY($2)`,+ [companyId, CHANGE_ORDER_IDS]+ );+ const draftMaterials = await q(+ `SELECT count(*)::int n FROM "methodMaterial" mm+ JOIN "makeMethod" mk ON mk.id = mm."makeMethodId"+ JOIN "changeOrder" co ON co.id = mk."changeOrderId"+ WHERE co."companyId" = $1 AND co."changeOrderId" = ANY($2)`,+ [companyId, CHANGE_ORDER_IDS]+ );+ const changeTypes = await q(+ `SELECT "changeType", count(*)::int n FROM "changeOrderAffectedItem" ai+ JOIN "changeOrder" co ON co.id = ai."changeOrderId"+ WHERE co."companyId" = $1 AND co."changeOrderId" = ANY($2)+ GROUP BY "changeType" ORDER BY "changeType"`,+ [companyId, CHANGE_ORDER_IDS]+ );+ const supersessions = await q(+ `SELECT count(*)::int n FROM "changeOrderSupersession" s+ JOIN "changeOrder" co ON co.id = s."changeOrderId"+ WHERE co."companyId" = $1 AND co."changeOrderId" = ANY($2)`,+ [companyId, CHANGE_ORDER_IDS]+ );+ const actions = await q(+ `SELECT count(*)::int n FROM "changeOrderActionTask" t+ JOIN "changeOrder" co ON co.id = t."changeOrderId"+ WHERE co."companyId" = $1 AND co."changeOrderId" = ANY($2)`,+ [companyId, CHANGE_ORDER_IDS]+ );+ const ncrs = await q(+ `SELECT count(*)::int n FROM "nonConformance" WHERE "companyId" = $1 AND "nonConformanceId" = $2`,+ [companyId, NCR_ID]+ );++ console.log("========================================");+ console.log("Change Orders seed summary");+ console.log("========================================");+ console.log(` Items: ${items[0].n} (7 purchased + 6 make)`);+ console.log(` Active makeMethods: ${makeMethods[0].n}`);+ console.log(` BOM lines: ${bomLines[0].n}`);+ console.log(` BOP operations: ${bopOps[0].n}`);+ console.log(+ ` Suppliers/Customers: ${SUPPLIER_NAMES.length}/${CUSTOMER_NAMES.length}`+ );+ console.log(` Purchase Order: ${PO_ID} (To Receive, PRT-001186.A x200)`);+ console.log(` Job: ${JOB_ID} (In Progress, VEH0000001)`);+ console.log(` Sales Order: ${SO_ID} (To Ship, VEH0000001)`);+ console.log(` NCR: ${ncrs[0].n > 0 ? NCR_ID : "MISSING"}`);+ console.log(" Change Orders by status:");+ for (const r of cosByStatus) console.log(` ${r.status.padEnd(22)} ${r.n}`);+ console.log(` Affected items: ${affectedItems[0].n}`);+ console.log(" Affected items by change type:");+ for (const r of changeTypes)+ console.log(` ${String(r.changeType).padEnd(20)} ${r.n}`);+ console.log(` CO-owned draft methods: ${draftMethods[0].n}`);+ console.log(` Draft BOM lines: ${draftMaterials[0].n}`);+ console.log(` Supersessions: ${supersessions[0].n}`);+ console.log(` Action tasks: ${actions[0].n}`);+ console.log("========================================\n");+}++seed();diff --git a/packages/database/src/seed-dev.ts b/packages/database/src/seed-dev.tsindex 648cb7c374..f3fe488b0f 100644--- a/packages/database/src/seed-dev.ts+++ b/packages/database/src/seed-dev.ts@@ -15,6 +15,8 @@ import * as dotenv from "dotenv";import {accountDefaults,accounts,+ changeOrderRequiredActions,+ changeOrderTypes,currencies,customerStatuses,defaultLocation,@@ -358,6 +360,14 @@ async function seedDev() {);}+ // Seed change order categories+ for (const cot of changeOrderTypes) {+ await client.query(+ `INSERT INTO "changeOrderType" (name, "companyId", "createdBy") VALUES ($1, $2, 'system')`,+ [cot.name, companyId]+ );+ }+// Seed non-conformance required actionsfor (const nca of nonConformanceRequiredActions) {await client.query(@@ -366,6 +376,14 @@ async function seedDev() {);}+ // Seed change order default actions+ for (const ca of changeOrderRequiredActions) {+ await client.query(+ `INSERT INTO "changeOrderRequiredAction" (name, "companyId", "createdBy") VALUES ($1, $2, 'system')`,+ [ca.name, companyId]+ );+ }+// Seed sequencesfor (const seq of sequences) {await client.query(diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex a6ec38f474..8a406bcbf3 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -4299,6 +4299,1277 @@ export type Database = {},]}+ changeOrder: {+ Row: {+ approvalRequirements: string[] | null+ assignee: string | null+ changeOrderId: string+ changeOrderTypeId: string | null+ companyId: string+ createdAt: string+ createdBy: string+ customFields: Json | null+ description: Json+ dueDate: string | null+ id: string+ name: string+ nonConformanceId: string | null+ openDate: string+ priority: Database["public"]["Enums"]["nonConformancePriority"] | null+ reasonForChange: Json+ requiredActionIds: string[] | null+ sourceId: string | null+ sourceType: string | null+ status: Database["public"]["Enums"]["changeOrderStatus"]+ tags: string[] | null+ type: Database["public"]["Enums"]["changeOrderTypeEnum"]+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ approvalRequirements?: string[] | null+ assignee?: string | null+ changeOrderId: string+ changeOrderTypeId?: string | null+ companyId: string+ createdAt?: string+ createdBy: string+ customFields?: Json | null+ description?: Json+ dueDate?: string | null+ id?: string+ name: string+ nonConformanceId?: string | null+ openDate: string+ priority?:+ | Database["public"]["Enums"]["nonConformancePriority"]+ | null+ reasonForChange?: Json+ requiredActionIds?: string[] | null+ sourceId?: string | null+ sourceType?: string | null+ status?: Database["public"]["Enums"]["changeOrderStatus"]+ tags?: string[] | null+ type?: Database["public"]["Enums"]["changeOrderTypeEnum"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ approvalRequirements?: string[] | null+ assignee?: string | null+ changeOrderId?: string+ changeOrderTypeId?: string | null+ companyId?: string+ createdAt?: string+ createdBy?: string+ customFields?: Json | null+ description?: Json+ dueDate?: string | null+ id?: string+ name?: string+ nonConformanceId?: string | null+ openDate?: string+ priority?:+ | Database["public"]["Enums"]["nonConformancePriority"]+ | null+ reasonForChange?: Json+ requiredActionIds?: string[] | null+ sourceId?: string | null+ sourceType?: string | null+ status?: Database["public"]["Enums"]["changeOrderStatus"]+ tags?: string[] | null+ type?: Database["public"]["Enums"]["changeOrderTypeEnum"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrder_changeOrderTypeId_fkey"+ columns: ["changeOrderTypeId"]+ isOneToOne: false+ referencedRelation: "changeOrderType"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrder_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrder_nonConformanceId_fkey"+ columns: ["nonConformanceId"]+ isOneToOne: false+ referencedRelation: "issues"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_nonConformanceId_fkey"+ columns: ["nonConformanceId"]+ isOneToOne: false+ referencedRelation: "nonConformance"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ changeOrderActionTask: {+ Row: {+ actionTypeId: string | null+ assignee: string | null+ changeOrderId: string+ companyId: string+ completedDate: string | null+ createdAt: string+ createdBy: string+ dueDate: string | null+ id: string+ name: string | null+ notes: Json+ sortOrder: number+ status: Database["public"]["Enums"]["changeOrderTaskStatus"]+ tags: string[] | null+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ actionTypeId?: string | null+ assignee?: string | null+ changeOrderId: string+ companyId: string+ completedDate?: string | null+ createdAt?: string+ createdBy: string+ dueDate?: string | null+ id?: string+ name?: string | null+ notes?: Json+ sortOrder?: number+ status?: Database["public"]["Enums"]["changeOrderTaskStatus"]+ tags?: string[] | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ actionTypeId?: string | null+ assignee?: string | null+ changeOrderId?: string+ companyId?: string+ completedDate?: string | null+ createdAt?: string+ createdBy?: string+ dueDate?: string | null+ id?: string+ name?: string | null+ notes?: Json+ sortOrder?: number+ status?: Database["public"]["Enums"]["changeOrderTaskStatus"]+ tags?: string[] | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "changeOrderActionTask_actionTypeId_fkey"+ columns: ["actionTypeId"]+ isOneToOne: false+ referencedRelation: "changeOrderRequiredAction"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrderActionTask_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrder"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrders"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderActionTask_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderActionTask_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrderActionTask_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ changeOrderAffectedItem: {+ Row: {+ baseMakeMethodId: string | null+ changeOrderId: string+ changeSummary: Json | null+ changeType: Database["public"]["Enums"]["changeOrderChangeType"]+ companyId: string+ createdAt: string+ createdBy: string+ discontinuationDate: string | null+ draftMakeMethodId: string | null+ id: string+ itemId: string+ newItemId: string | null+ sortOrder: number+ successorEffectivityDate: string | null+ supersessionMode: Database["public"]["Enums"]["supersessionMode"]+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ baseMakeMethodId?: string | null+ changeOrderId: string+ changeSummary?: Json | null+ changeType?: Database["public"]["Enums"]["changeOrderChangeType"]+ companyId: string+ createdAt?: string+ createdBy: string+ discontinuationDate?: string | null+ draftMakeMethodId?: string | null+ id?: string+ itemId: string+ newItemId?: string | null+ sortOrder?: number+ successorEffectivityDate?: string | null+ supersessionMode?: Database["public"]["Enums"]["supersessionMode"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ baseMakeMethodId?: string | null+ changeOrderId?: string+ changeSummary?: Json | null+ changeType?: Database["public"]["Enums"]["changeOrderChangeType"]+ companyId?: string+ createdAt?: string+ createdBy?: string+ discontinuationDate?: string | null+ draftMakeMethodId?: string | null+ id?: string+ itemId?: string+ newItemId?: string | null+ sortOrder?: number+ successorEffectivityDate?: string | null+ supersessionMode?: Database["public"]["Enums"]["supersessionMode"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "changeOrderAffectedItem_baseMakeMethodId_fkey"+ columns: ["baseMakeMethodId"]+ isOneToOne: false+ referencedRelation: "activeMakeMethods"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_baseMakeMethodId_fkey"+ columns: ["baseMakeMethodId"]+ isOneToOne: false+ referencedRelation: "jobOperationsWithMakeMethods"+ referencedColumns: ["makeMethodId"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_baseMakeMethodId_fkey"+ columns: ["baseMakeMethodId"]+ isOneToOne: false+ referencedRelation: "makeMethod"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_baseMakeMethodId_fkey"+ columns: ["baseMakeMethodId"]+ isOneToOne: false+ referencedRelation: "quoteOperationsWithMakeMethods"+ referencedColumns: ["makeMethodId"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrder"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrders"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_draftMakeMethodId_fkey"+ columns: ["draftMakeMethodId"]+ isOneToOne: false+ referencedRelation: "activeMakeMethods"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_draftMakeMethodId_fkey"+ columns: ["draftMakeMethodId"]+ isOneToOne: false+ referencedRelation: "jobOperationsWithMakeMethods"+ referencedColumns: ["makeMethodId"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_draftMakeMethodId_fkey"+ columns: ["draftMakeMethodId"]+ isOneToOne: false+ referencedRelation: "makeMethod"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_draftMakeMethodId_fkey"+ columns: ["draftMakeMethodId"]+ isOneToOne: false+ referencedRelation: "quoteOperationsWithMakeMethods"+ referencedColumns: ["makeMethodId"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "services"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_newItemId_fkey"+ columns: ["newItemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_newItemId_fkey"+ columns: ["newItemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_newItemId_fkey"+ columns: ["newItemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_newItemId_fkey"+ columns: ["newItemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_newItemId_fkey"+ columns: ["newItemId"]+ isOneToOne: false+ referencedRelation: "services"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_newItemId_fkey"+ columns: ["newItemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ changeOrderRequiredAction: {+ Row: {+ active: boolean+ companyId: string+ createdAt: string+ createdBy: string+ customFields: Json | null+ id: string+ name: string+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ active?: boolean+ companyId: string+ createdAt?: string+ createdBy: string+ customFields?: Json | null+ id?: string+ name: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ active?: boolean+ companyId?: string+ createdAt?: string+ createdBy?: string+ customFields?: Json | null+ id?: string+ name?: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "changeOrderRequiredAction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ changeOrderSupersession: {+ Row: {+ changeOrderId: string+ companyId: string+ createdAt: string+ createdBy: string+ discontinuationDate: string | null+ id: string+ predecessorItemId: string+ successorEffectivityDate: string | null+ successorItemId: string | null+ supersessionMode: Database["public"]["Enums"]["supersessionMode"]+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ changeOrderId: string+ companyId: string+ createdAt?: string+ createdBy: string+ discontinuationDate?: string | null+ id?: string+ predecessorItemId: string+ successorEffectivityDate?: string | null+ successorItemId?: string | null+ supersessionMode?: Database["public"]["Enums"]["supersessionMode"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ changeOrderId?: string+ companyId?: string+ createdAt?: string+ createdBy?: string+ discontinuationDate?: string | null+ id?: string+ predecessorItemId?: string+ successorEffectivityDate?: string | null+ successorItemId?: string | null+ supersessionMode?: Database["public"]["Enums"]["supersessionMode"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "changeOrderSupersession_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrder"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrders"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderSupersession_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderSupersession_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrderSupersession_predecessorItemId_fkey"+ columns: ["predecessorItemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_predecessorItemId_fkey"+ columns: ["predecessorItemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_predecessorItemId_fkey"+ columns: ["predecessorItemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_predecessorItemId_fkey"+ columns: ["predecessorItemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_predecessorItemId_fkey"+ columns: ["predecessorItemId"]+ isOneToOne: false+ referencedRelation: "services"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_predecessorItemId_fkey"+ columns: ["predecessorItemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_successorItemId_fkey"+ columns: ["successorItemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_successorItemId_fkey"+ columns: ["successorItemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_successorItemId_fkey"+ columns: ["successorItemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_successorItemId_fkey"+ columns: ["successorItemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_successorItemId_fkey"+ columns: ["successorItemId"]+ isOneToOne: false+ referencedRelation: "services"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_successorItemId_fkey"+ columns: ["successorItemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ changeOrderType: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ id: string+ name: string+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ id?: string+ name: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ id?: string+ name?: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "changeOrderType_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderType_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderType_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrderType_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }company: {Row: {active: boolean@@ -4963,6 +6234,7 @@ export type Database = {materialGeneratedIds: booleanoperationsDispatchNotificationGroup: string[] | nullotherDispatchNotificationGroup: string[] | null+ plmReleaseControl: stringprinting: Json | nullproductLabelSize: string | nullpurchasePriceUpdateTiming: Database["public"]["Enums"]["purchasePriceUpdateTiming"]@@ -5006,6 +6278,7 @@ export type Database = {materialGeneratedIds?: booleanoperationsDispatchNotificationGroup?: string[] | nullotherDispatchNotificationGroup?: string[] | null+ plmReleaseControl?: stringprinting?: Json | nullproductLabelSize?: string | nullpurchasePriceUpdateTiming?: Database["public"]["Enums"]["purchasePriceUpdateTiming"]@@ -5049,6 +6322,7 @@ export type Database = {materialGeneratedIds?: booleanoperationsDispatchNotificationGroup?: string[] | nullotherDispatchNotificationGroup?: string[] | null+ plmReleaseControl?: stringprinting?: Json | nullproductLabelSize?: string | nullpurchasePriceUpdateTiming?: Database["public"]["Enums"]["purchasePriceUpdateTiming"]@@ -16654,6 +17928,7 @@ export type Database = {Row: {active: booleanassignee: string | null+ changeOrderId: string | nullcompanyId: string | nullcreatedAt: stringcreatedBy: string@@ -16671,6 +17946,7 @@ export type Database = {replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]requiresInspection: booleanrevision: string | null+ revisionStatus: Database["public"]["Enums"]["itemRevisionStatus"]sourcingType: Database["public"]["Enums"]["sourcingType"]thumbnailPath: string | nulltrackingMethod: string | null@@ -16682,6 +17958,7 @@ export type Database = {Insert: {active?: booleanassignee?: string | null+ changeOrderId?: string | nullcompanyId?: string | nullcreatedAt?: stringcreatedBy: string@@ -16699,6 +17976,7 @@ export type Database = {replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]requiresInspection?: booleanrevision?: string | null+ revisionStatus?: Database["public"]["Enums"]["itemRevisionStatus"]sourcingType?: Database["public"]["Enums"]["sourcingType"]thumbnailPath?: string | nulltrackingMethod?: string | null@@ -16710,6 +17988,7 @@ export type Database = {Update: {active?: booleanassignee?: string | null+ changeOrderId?: string | nullcompanyId?: string | nullcreatedAt?: stringcreatedBy?: string@@ -16727,6 +18006,7 @@ export type Database = {replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]requiresInspection?: booleanrevision?: string | null+ revisionStatus?: Database["public"]["Enums"]["itemRevisionStatus"]sourcingType?: Database["public"]["Enums"]["sourcingType"]thumbnailPath?: string | nulltrackingMethod?: string | null@@ -16771,6 +18051,20 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},+ {+ foreignKeyName: "item_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrder"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "item_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrders"+ referencedColumns: ["id"]+ },{foreignKeyName: "item_companyId_fkey"columns: ["companyId"]@@ -23856,6 +25150,7 @@ export type Database = {}makeMethod: {Row: {+ changeOrderId: string | nullcompanyId: stringcreatedAt: stringcreatedBy: string@@ -23869,6 +25164,7 @@ export type Database = {version: number}Insert: {+ changeOrderId?: string | nullcompanyId: stringcreatedAt?: stringcreatedBy: string@@ -23882,6 +25178,7 @@ export type Database = {version?: number}Update: {+ changeOrderId?: string | nullcompanyId?: stringcreatedAt?: stringcreatedBy?: string@@ -23895,6 +25192,20 @@ export type Database = {version?: number}Relationships: [+ {+ foreignKeyName: "makeMethod_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrder"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "makeMethod_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrders"+ referencedColumns: ["id"]+ },{foreignKeyName: "method_companyId_fkey"columns: ["companyId"]@@ -55291,6 +56602,192 @@ export type Database = {},]}+ changeOrders: {+ Row: {+ affectedItems: Json | null+ approvalRequirements: string[] | null+ assignee: string | null+ changeOrderId: string | null+ changeOrderTypeId: string | null+ companyId: string | null+ createdAt: string | null+ createdBy: string | null+ customFields: Json | null+ description: Json | null+ dueDate: string | null+ id: string | null+ itemIds: string[] | null+ name: string | null+ nonConformanceId: string | null+ openDate: string | null+ priority: Database["public"]["Enums"]["nonConformancePriority"] | null+ reasonForChange: Json | null+ requiredActionIds: string[] | null+ sourceId: string | null+ sourceType: string | null+ status: Database["public"]["Enums"]["changeOrderStatus"] | null+ tags: string[] | null+ type: Database["public"]["Enums"]["changeOrderTypeEnum"] | null+ updatedAt: string | null+ updatedBy: string | null+ }+ Relationships: [+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrder_changeOrderTypeId_fkey"+ columns: ["changeOrderTypeId"]+ isOneToOne: false+ referencedRelation: "changeOrderType"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrder_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrder_nonConformanceId_fkey"+ columns: ["nonConformanceId"]+ isOneToOne: false+ referencedRelation: "issues"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_nonConformanceId_fkey"+ columns: ["nonConformanceId"]+ isOneToOne: false+ referencedRelation: "nonConformance"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }companies: {Row: {active: boolean | null@@ -62777,14 +64274,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -66170,14 +67667,14 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -66725,14 +68222,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -72519,6 +74016,20 @@ export type Database = {| "Note"| "Media"assemblyStepStatus: "Todo" | "Review" | "Done"+ changeOrderChangeType:+ | "Version"+ | "Revision"+ | "Replacement Part"+ | "New Part"+ changeOrderStatus:+ | "Draft"+ | "Start"+ | "Engineering Complete"+ | "Implementation"+ | "Done"+ | "Cancelled"+ changeOrderTaskStatus: "Pending" | "In Progress" | "Completed" | "Skipped"+ changeOrderTypeEnum: "Engineering" | "Manufacturing" | "Documentation"configurationParameterDataType:| "text"| "numeric"@@ -72736,6 +74247,7 @@ export type Database = {| "Fixed Reorder Quantity"| "Maximum Quantity"itemReplenishmentSystem: "Buy" | "Make" | "Buy and Make"+ itemRevisionStatus: "Design" | "Prototype" | "Production" | "Obsolete"itemTrackingSourceDocument:| "Receipt"| "Job Production"@@ -73852,6 +75364,22 @@ export const Constants = {"Media",],assemblyStepStatus: ["Todo", "Review", "Done"],+ changeOrderChangeType: [+ "Version",+ "Revision",+ "Replacement Part",+ "New Part",+ ],+ changeOrderStatus: [+ "Draft",+ "Start",+ "Engineering Complete",+ "Implementation",+ "Done",+ "Cancelled",+ ],+ changeOrderTaskStatus: ["Pending", "In Progress", "Completed", "Skipped"],+ changeOrderTypeEnum: ["Engineering", "Manufacturing", "Documentation"],configurationParameterDataType: ["text","numeric",@@ -74090,6 +75618,7 @@ export const Constants = {"Maximum Quantity",],itemReplenishmentSystem: ["Buy", "Make", "Buy and Make"],+ itemRevisionStatus: ["Design", "Prototype", "Production", "Obsolete"],itemTrackingSourceDocument: ["Receipt","Job Production",diff --git a/packages/database/supabase/functions/lib/seed.data.ts b/packages/database/supabase/functions/lib/seed.data.tsindex 78440c0d50..40230a73fe 100644--- a/packages/database/supabase/functions/lib/seed.data.ts+++ b/packages/database/supabase/functions/lib/seed.data.ts@@ -174,6 +174,23 @@ export const nonConformanceTypes = [{ name: "Customer Complaint", createdBy: "system" }] as const;+// Change Order types (the changeOrderType lookup). Kept in sync with the+// one-time seed in the change-orders migration so new companies get the same+// default types the migration gave existing ones.+export const changeOrderTypes = [+ { name: "Design Improvement", createdBy: "system" },+ { name: "Cost Reduction", createdBy: "system" },+ { name: "Quality / Reliability Improvement", createdBy: "system" },+ { name: "Supplier / Sourcing Change", createdBy: "system" },+ { name: "Material or Component Change", createdBy: "system" },+ { name: "Obsolescence / End-of-Life", createdBy: "system" },+ { name: "Regulatory / Compliance", createdBy: "system" },+ { name: "Safety", createdBy: "system" },+ { name: "Manufacturing / Producibility", createdBy: "system" },+ { name: "Customer Request", createdBy: "system" },+ { name: "Documentation Error / Correction", createdBy: "system" }+] as const;+export const nonConformanceRequiredActions = [{ name: "Corrective Action", systemType: "Corrective" as const, createdBy: "system" },{ name: "Preventive Action", systemType: "Preventive" as const, createdBy: "system" },@@ -189,6 +206,19 @@ export const nonConformanceRequiredActions = [{ name: "Documentation", createdBy: "system" }] as const;+// Default change-order actions (the changeOrderRequiredAction templates). Kept in+// sync with the one-time backfill in the change-order-required-actions migration so+// new companies get the same defaults existing ones were backfilled with.+export const changeOrderRequiredActions = [+ { name: "Engineering Review", createdBy: "system" },+ { name: "Update Drawings / CAD", createdBy: "system" },+ { name: "Update BOM / Routing", createdBy: "system" },+ { name: "Cost Impact Review", createdBy: "system" },+ { name: "Quality Review", createdBy: "system" },+ { name: "Inventory Disposition (rework / scrap / use-as-is)", createdBy: "system" },+ { name: "Notify Affected Parties", createdBy: "system" }+] as const;+export const sequences = [{table: "journalEntry",@@ -253,6 +283,15 @@ export const sequences = [size: 6,step: 1},+ {+ table: "changeOrder",+ name: "Change Order",+ prefix: "ECO-",+ suffix: null,+ next: 0,+ size: 6,+ step: 1+ },{table: "purchaseOrder",name: "Purchase Order",diff --git a/packages/database/supabase/functions/lib/seed.ts b/packages/database/supabase/functions/lib/seed.tsindex 6d409f158b..57cf851319 100644--- a/packages/database/supabase/functions/lib/seed.ts+++ b/packages/database/supabase/functions/lib/seed.ts@@ -6,6 +6,8 @@export {accountDefaults,accounts,+ changeOrderRequiredActions,+ changeOrderTypes,currencies,customerStatuses,dimensions,diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex a6ec38f474..8a406bcbf3 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -4299,6 +4299,1277 @@ export type Database = {},]}+ changeOrder: {+ Row: {+ approvalRequirements: string[] | null+ assignee: string | null+ changeOrderId: string+ changeOrderTypeId: string | null+ companyId: string+ createdAt: string+ createdBy: string+ customFields: Json | null+ description: Json+ dueDate: string | null+ id: string+ name: string+ nonConformanceId: string | null+ openDate: string+ priority: Database["public"]["Enums"]["nonConformancePriority"] | null+ reasonForChange: Json+ requiredActionIds: string[] | null+ sourceId: string | null+ sourceType: string | null+ status: Database["public"]["Enums"]["changeOrderStatus"]+ tags: string[] | null+ type: Database["public"]["Enums"]["changeOrderTypeEnum"]+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ approvalRequirements?: string[] | null+ assignee?: string | null+ changeOrderId: string+ changeOrderTypeId?: string | null+ companyId: string+ createdAt?: string+ createdBy: string+ customFields?: Json | null+ description?: Json+ dueDate?: string | null+ id?: string+ name: string+ nonConformanceId?: string | null+ openDate: string+ priority?:+ | Database["public"]["Enums"]["nonConformancePriority"]+ | null+ reasonForChange?: Json+ requiredActionIds?: string[] | null+ sourceId?: string | null+ sourceType?: string | null+ status?: Database["public"]["Enums"]["changeOrderStatus"]+ tags?: string[] | null+ type?: Database["public"]["Enums"]["changeOrderTypeEnum"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ approvalRequirements?: string[] | null+ assignee?: string | null+ changeOrderId?: string+ changeOrderTypeId?: string | null+ companyId?: string+ createdAt?: string+ createdBy?: string+ customFields?: Json | null+ description?: Json+ dueDate?: string | null+ id?: string+ name?: string+ nonConformanceId?: string | null+ openDate?: string+ priority?:+ | Database["public"]["Enums"]["nonConformancePriority"]+ | null+ reasonForChange?: Json+ requiredActionIds?: string[] | null+ sourceId?: string | null+ sourceType?: string | null+ status?: Database["public"]["Enums"]["changeOrderStatus"]+ tags?: string[] | null+ type?: Database["public"]["Enums"]["changeOrderTypeEnum"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrder_changeOrderTypeId_fkey"+ columns: ["changeOrderTypeId"]+ isOneToOne: false+ referencedRelation: "changeOrderType"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrder_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrder_nonConformanceId_fkey"+ columns: ["nonConformanceId"]+ isOneToOne: false+ referencedRelation: "issues"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_nonConformanceId_fkey"+ columns: ["nonConformanceId"]+ isOneToOne: false+ referencedRelation: "nonConformance"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ changeOrderActionTask: {+ Row: {+ actionTypeId: string | null+ assignee: string | null+ changeOrderId: string+ companyId: string+ completedDate: string | null+ createdAt: string+ createdBy: string+ dueDate: string | null+ id: string+ name: string | null+ notes: Json+ sortOrder: number+ status: Database["public"]["Enums"]["changeOrderTaskStatus"]+ tags: string[] | null+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ actionTypeId?: string | null+ assignee?: string | null+ changeOrderId: string+ companyId: string+ completedDate?: string | null+ createdAt?: string+ createdBy: string+ dueDate?: string | null+ id?: string+ name?: string | null+ notes?: Json+ sortOrder?: number+ status?: Database["public"]["Enums"]["changeOrderTaskStatus"]+ tags?: string[] | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ actionTypeId?: string | null+ assignee?: string | null+ changeOrderId?: string+ companyId?: string+ completedDate?: string | null+ createdAt?: string+ createdBy?: string+ dueDate?: string | null+ id?: string+ name?: string | null+ notes?: Json+ sortOrder?: number+ status?: Database["public"]["Enums"]["changeOrderTaskStatus"]+ tags?: string[] | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "changeOrderActionTask_actionTypeId_fkey"+ columns: ["actionTypeId"]+ isOneToOne: false+ referencedRelation: "changeOrderRequiredAction"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrderActionTask_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrder"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrders"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderActionTask_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderActionTask_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrderActionTask_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderActionTask_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ changeOrderAffectedItem: {+ Row: {+ baseMakeMethodId: string | null+ changeOrderId: string+ changeSummary: Json | null+ changeType: Database["public"]["Enums"]["changeOrderChangeType"]+ companyId: string+ createdAt: string+ createdBy: string+ discontinuationDate: string | null+ draftMakeMethodId: string | null+ id: string+ itemId: string+ newItemId: string | null+ sortOrder: number+ successorEffectivityDate: string | null+ supersessionMode: Database["public"]["Enums"]["supersessionMode"]+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ baseMakeMethodId?: string | null+ changeOrderId: string+ changeSummary?: Json | null+ changeType?: Database["public"]["Enums"]["changeOrderChangeType"]+ companyId: string+ createdAt?: string+ createdBy: string+ discontinuationDate?: string | null+ draftMakeMethodId?: string | null+ id?: string+ itemId: string+ newItemId?: string | null+ sortOrder?: number+ successorEffectivityDate?: string | null+ supersessionMode?: Database["public"]["Enums"]["supersessionMode"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ baseMakeMethodId?: string | null+ changeOrderId?: string+ changeSummary?: Json | null+ changeType?: Database["public"]["Enums"]["changeOrderChangeType"]+ companyId?: string+ createdAt?: string+ createdBy?: string+ discontinuationDate?: string | null+ draftMakeMethodId?: string | null+ id?: string+ itemId?: string+ newItemId?: string | null+ sortOrder?: number+ successorEffectivityDate?: string | null+ supersessionMode?: Database["public"]["Enums"]["supersessionMode"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "changeOrderAffectedItem_baseMakeMethodId_fkey"+ columns: ["baseMakeMethodId"]+ isOneToOne: false+ referencedRelation: "activeMakeMethods"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_baseMakeMethodId_fkey"+ columns: ["baseMakeMethodId"]+ isOneToOne: false+ referencedRelation: "jobOperationsWithMakeMethods"+ referencedColumns: ["makeMethodId"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_baseMakeMethodId_fkey"+ columns: ["baseMakeMethodId"]+ isOneToOne: false+ referencedRelation: "makeMethod"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_baseMakeMethodId_fkey"+ columns: ["baseMakeMethodId"]+ isOneToOne: false+ referencedRelation: "quoteOperationsWithMakeMethods"+ referencedColumns: ["makeMethodId"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrder"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrders"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_draftMakeMethodId_fkey"+ columns: ["draftMakeMethodId"]+ isOneToOne: false+ referencedRelation: "activeMakeMethods"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_draftMakeMethodId_fkey"+ columns: ["draftMakeMethodId"]+ isOneToOne: false+ referencedRelation: "jobOperationsWithMakeMethods"+ referencedColumns: ["makeMethodId"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_draftMakeMethodId_fkey"+ columns: ["draftMakeMethodId"]+ isOneToOne: false+ referencedRelation: "makeMethod"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_draftMakeMethodId_fkey"+ columns: ["draftMakeMethodId"]+ isOneToOne: false+ referencedRelation: "quoteOperationsWithMakeMethods"+ referencedColumns: ["makeMethodId"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "services"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_newItemId_fkey"+ columns: ["newItemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_newItemId_fkey"+ columns: ["newItemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_newItemId_fkey"+ columns: ["newItemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_newItemId_fkey"+ columns: ["newItemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_newItemId_fkey"+ columns: ["newItemId"]+ isOneToOne: false+ referencedRelation: "services"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_newItemId_fkey"+ columns: ["newItemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderAffectedItem_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ changeOrderRequiredAction: {+ Row: {+ active: boolean+ companyId: string+ createdAt: string+ createdBy: string+ customFields: Json | null+ id: string+ name: string+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ active?: boolean+ companyId: string+ createdAt?: string+ createdBy: string+ customFields?: Json | null+ id?: string+ name: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ active?: boolean+ companyId?: string+ createdAt?: string+ createdBy?: string+ customFields?: Json | null+ id?: string+ name?: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "changeOrderRequiredAction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderRequiredAction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ changeOrderSupersession: {+ Row: {+ changeOrderId: string+ companyId: string+ createdAt: string+ createdBy: string+ discontinuationDate: string | null+ id: string+ predecessorItemId: string+ successorEffectivityDate: string | null+ successorItemId: string | null+ supersessionMode: Database["public"]["Enums"]["supersessionMode"]+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ changeOrderId: string+ companyId: string+ createdAt?: string+ createdBy: string+ discontinuationDate?: string | null+ id?: string+ predecessorItemId: string+ successorEffectivityDate?: string | null+ successorItemId?: string | null+ supersessionMode?: Database["public"]["Enums"]["supersessionMode"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ changeOrderId?: string+ companyId?: string+ createdAt?: string+ createdBy?: string+ discontinuationDate?: string | null+ id?: string+ predecessorItemId?: string+ successorEffectivityDate?: string | null+ successorItemId?: string | null+ supersessionMode?: Database["public"]["Enums"]["supersessionMode"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "changeOrderSupersession_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrder"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrders"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderSupersession_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderSupersession_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrderSupersession_predecessorItemId_fkey"+ columns: ["predecessorItemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_predecessorItemId_fkey"+ columns: ["predecessorItemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_predecessorItemId_fkey"+ columns: ["predecessorItemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_predecessorItemId_fkey"+ columns: ["predecessorItemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_predecessorItemId_fkey"+ columns: ["predecessorItemId"]+ isOneToOne: false+ referencedRelation: "services"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_predecessorItemId_fkey"+ columns: ["predecessorItemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_successorItemId_fkey"+ columns: ["successorItemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_successorItemId_fkey"+ columns: ["successorItemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_successorItemId_fkey"+ columns: ["successorItemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_successorItemId_fkey"+ columns: ["successorItemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_successorItemId_fkey"+ columns: ["successorItemId"]+ isOneToOne: false+ referencedRelation: "services"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_successorItemId_fkey"+ columns: ["successorItemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderSupersession_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ changeOrderType: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ id: string+ name: string+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ id?: string+ name: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ id?: string+ name?: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "changeOrderType_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderType_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrderType_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrderType_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrderType_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }company: {Row: {active: boolean@@ -4963,6 +6234,7 @@ export type Database = {materialGeneratedIds: booleanoperationsDispatchNotificationGroup: string[] | nullotherDispatchNotificationGroup: string[] | null+ plmReleaseControl: stringprinting: Json | nullproductLabelSize: string | nullpurchasePriceUpdateTiming: Database["public"]["Enums"]["purchasePriceUpdateTiming"]@@ -5006,6 +6278,7 @@ export type Database = {materialGeneratedIds?: booleanoperationsDispatchNotificationGroup?: string[] | nullotherDispatchNotificationGroup?: string[] | null+ plmReleaseControl?: stringprinting?: Json | nullproductLabelSize?: string | nullpurchasePriceUpdateTiming?: Database["public"]["Enums"]["purchasePriceUpdateTiming"]@@ -5049,6 +6322,7 @@ export type Database = {materialGeneratedIds?: booleanoperationsDispatchNotificationGroup?: string[] | nullotherDispatchNotificationGroup?: string[] | null+ plmReleaseControl?: stringprinting?: Json | nullproductLabelSize?: string | nullpurchasePriceUpdateTiming?: Database["public"]["Enums"]["purchasePriceUpdateTiming"]@@ -16654,6 +17928,7 @@ export type Database = {Row: {active: booleanassignee: string | null+ changeOrderId: string | nullcompanyId: string | nullcreatedAt: stringcreatedBy: string@@ -16671,6 +17946,7 @@ export type Database = {replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]requiresInspection: booleanrevision: string | null+ revisionStatus: Database["public"]["Enums"]["itemRevisionStatus"]sourcingType: Database["public"]["Enums"]["sourcingType"]thumbnailPath: string | nulltrackingMethod: string | null@@ -16682,6 +17958,7 @@ export type Database = {Insert: {active?: booleanassignee?: string | null+ changeOrderId?: string | nullcompanyId?: string | nullcreatedAt?: stringcreatedBy: string@@ -16699,6 +17976,7 @@ export type Database = {replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]requiresInspection?: booleanrevision?: string | null+ revisionStatus?: Database["public"]["Enums"]["itemRevisionStatus"]sourcingType?: Database["public"]["Enums"]["sourcingType"]thumbnailPath?: string | nulltrackingMethod?: string | null@@ -16710,6 +17988,7 @@ export type Database = {Update: {active?: booleanassignee?: string | null+ changeOrderId?: string | nullcompanyId?: string | nullcreatedAt?: stringcreatedBy?: string@@ -16727,6 +18006,7 @@ export type Database = {replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]requiresInspection?: booleanrevision?: string | null+ revisionStatus?: Database["public"]["Enums"]["itemRevisionStatus"]sourcingType?: Database["public"]["Enums"]["sourcingType"]thumbnailPath?: string | nulltrackingMethod?: string | null@@ -16771,6 +18051,20 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},+ {+ foreignKeyName: "item_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrder"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "item_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrders"+ referencedColumns: ["id"]+ },{foreignKeyName: "item_companyId_fkey"columns: ["companyId"]@@ -23856,6 +25150,7 @@ export type Database = {}makeMethod: {Row: {+ changeOrderId: string | nullcompanyId: stringcreatedAt: stringcreatedBy: string@@ -23869,6 +25164,7 @@ export type Database = {version: number}Insert: {+ changeOrderId?: string | nullcompanyId: stringcreatedAt?: stringcreatedBy: string@@ -23882,6 +25178,7 @@ export type Database = {version?: number}Update: {+ changeOrderId?: string | nullcompanyId?: stringcreatedAt?: stringcreatedBy?: string@@ -23895,6 +25192,20 @@ export type Database = {version?: number}Relationships: [+ {+ foreignKeyName: "makeMethod_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrder"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "makeMethod_changeOrderId_fkey"+ columns: ["changeOrderId"]+ isOneToOne: false+ referencedRelation: "changeOrders"+ referencedColumns: ["id"]+ },{foreignKeyName: "method_companyId_fkey"columns: ["companyId"]@@ -55291,6 +56602,192 @@ export type Database = {},]}+ changeOrders: {+ Row: {+ affectedItems: Json | null+ approvalRequirements: string[] | null+ assignee: string | null+ changeOrderId: string | null+ changeOrderTypeId: string | null+ companyId: string | null+ createdAt: string | null+ createdBy: string | null+ customFields: Json | null+ description: Json | null+ dueDate: string | null+ id: string | null+ itemIds: string[] | null+ name: string | null+ nonConformanceId: string | null+ openDate: string | null+ priority: Database["public"]["Enums"]["nonConformancePriority"] | null+ reasonForChange: Json | null+ requiredActionIds: string[] | null+ sourceId: string | null+ sourceType: string | null+ status: Database["public"]["Enums"]["changeOrderStatus"] | null+ tags: string[] | null+ type: Database["public"]["Enums"]["changeOrderTypeEnum"] | null+ updatedAt: string | null+ updatedBy: string | null+ }+ Relationships: [+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrder_changeOrderTypeId_fkey"+ columns: ["changeOrderTypeId"]+ isOneToOne: false+ referencedRelation: "changeOrderType"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrder_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "changeOrder_nonConformanceId_fkey"+ columns: ["nonConformanceId"]+ isOneToOne: false+ referencedRelation: "issues"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_nonConformanceId_fkey"+ columns: ["nonConformanceId"]+ isOneToOne: false+ referencedRelation: "nonConformance"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "changeOrder_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }companies: {Row: {active: boolean | null@@ -62777,14 +64274,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -66170,14 +67667,14 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -66725,14 +68222,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -72519,6 +74016,20 @@ export type Database = {| "Note"| "Media"assemblyStepStatus: "Todo" | "Review" | "Done"+ changeOrderChangeType:+ | "Version"+ | "Revision"+ | "Replacement Part"+ | "New Part"+ changeOrderStatus:+ | "Draft"+ | "Start"+ | "Engineering Complete"+ | "Implementation"+ | "Done"+ | "Cancelled"+ changeOrderTaskStatus: "Pending" | "In Progress" | "Completed" | "Skipped"+ changeOrderTypeEnum: "Engineering" | "Manufacturing" | "Documentation"configurationParameterDataType:| "text"| "numeric"@@ -72736,6 +74247,7 @@ export type Database = {| "Fixed Reorder Quantity"| "Maximum Quantity"itemReplenishmentSystem: "Buy" | "Make" | "Buy and Make"+ itemRevisionStatus: "Design" | "Prototype" | "Production" | "Obsolete"itemTrackingSourceDocument:| "Receipt"| "Job Production"@@ -73852,6 +75364,22 @@ export const Constants = {"Media",],assemblyStepStatus: ["Todo", "Review", "Done"],+ changeOrderChangeType: [+ "Version",+ "Revision",+ "Replacement Part",+ "New Part",+ ],+ changeOrderStatus: [+ "Draft",+ "Start",+ "Engineering Complete",+ "Implementation",+ "Done",+ "Cancelled",+ ],+ changeOrderTaskStatus: ["Pending", "In Progress", "Completed", "Skipped"],+ changeOrderTypeEnum: ["Engineering", "Manufacturing", "Documentation"],configurationParameterDataType: ["text","numeric",@@ -74090,6 +75618,7 @@ export const Constants = {"Maximum Quantity",],itemReplenishmentSystem: ["Buy", "Make", "Buy and Make"],+ itemRevisionStatus: ["Design", "Prototype", "Production", "Obsolete"],itemTrackingSourceDocument: ["Receipt","Job Production",diff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.tsindex 0dc35a249d..6c8bd9bf74 100644--- a/packages/database/supabase/functions/seed-company/index.ts+++ b/packages/database/supabase/functions/seed-company/index.ts@@ -11,6 +11,8 @@ import {failureModes,fiscalYearSettings,fixedAssetClasses,+ changeOrderRequiredActions,+ changeOrderTypes,gaugeTypes,groupCompanyTemplate,groups,@@ -292,6 +294,24 @@ serve(async (req: Request) => {).execute();+ // change-order default types (the changeOrderType lookup). New on this+ // branch and not yet in the cloud-generated Kysely types, so the insert+ // goes through a cast (mirrors changeOrderRequiredAction below).+ await (trx as any)+ .insertInto("changeOrderType")+ .values(changeOrderTypes.map((ct) => ({ ...ct, companyId })))+ .execute();++ // change-order default actions (system template rows). New on this branch+ // and not yet in the cloud-generated Kysely types, so the insert goes+ // through a cast (mirrors periodCloseTaskDefinition below).+ await (trx as any)+ .insertInto("changeOrderRequiredAction")+ .values(+ changeOrderRequiredActions.map((ca) => ({ ...ca, companyId }))+ )+ .execute();+await trx.insertInto("sequence").values(sequences.map((s) => ({ ...s, companyId })))diff --git a/packages/database/supabase/migrations/20260716101500_change-orders.sql b/packages/database/supabase/migrations/20260716101500_change-orders.sqlnew file mode 100644index 0000000000..4fc49f9297--- /dev/null+++ b/packages/database/supabase/migrations/20260716101500_change-orders.sql@@ -0,0 +1,479 @@+-- =============================================================================+-- Change Orders (ECO) module — top-to-bottom model.+--+-- The user picks affected parts first, then edits each part's BOM/BOP/attributes+-- on a CO-owned Draft makeMethod (via the normal editors, hidden until release).+-- At release the drafts are activated and propagated via itemSupersession.+--+-- Conventions clone quality/nonConformance (20250327140050_ncr.sql): id('<prefix>')+-- PK, audit columns, RLS via get_companies_with_employee_permission('parts_*')+-- for writes and get_companies_with_employee_role() for reads on lookup tables.+-- Change orders live under the Items/Parts area, so the permission domain is parts.+-- =============================================================================++-- -----------------------------------------------------------------------------+-- 0. Idempotency teardown — makes this migration rerunnable after a partial apply+-- (a migration only re-runs after a prior apply failed midway). Safe no-op on a+-- clean DB. Drops in dependency order, including the columns added to shared+-- tables below.+-- -----------------------------------------------------------------------------+ALTER TABLE "item" DROP CONSTRAINT IF EXISTS "item_changeOrderId_fkey";+ALTER TABLE "item" DROP COLUMN IF EXISTS "changeOrderId";+ALTER TABLE "item" DROP COLUMN IF EXISTS "revisionStatus";+ALTER TABLE "makeMethod" DROP CONSTRAINT IF EXISTS "makeMethod_changeOrderId_fkey";+ALTER TABLE "makeMethod" DROP COLUMN IF EXISTS "changeOrderId";+ALTER TABLE "companySettings" DROP COLUMN IF EXISTS "plmReleaseControl";++DROP TABLE IF EXISTS "changeOrderActionTask" CASCADE;+DROP TABLE IF EXISTS "changeOrderSupersession" CASCADE;+DROP TABLE IF EXISTS "changeOrderAffectedItem" CASCADE;+DROP TABLE IF EXISTS "changeOrderRequiredAction" CASCADE;+DROP TABLE IF EXISTS "changeOrder" CASCADE;+DROP TABLE IF EXISTS "changeOrderType" CASCADE;++DROP TYPE IF EXISTS "changeOrderChangeType";+DROP TYPE IF EXISTS "changeOrderTaskStatus";+DROP TYPE IF EXISTS "itemRevisionStatus";+DROP TYPE IF EXISTS "changeOrderStatus";+DROP TYPE IF EXISTS "changeOrderTypeEnum";++-- -----------------------------------------------------------------------------+-- 1. Enums+-- -----------------------------------------------------------------------------+-- Named "changeOrderTypeEnum" (not "changeOrderType") because a table of that name+-- exists below and Postgres registers an implicit composite type per table, so an+-- enum and a table cannot share a name in pg_type.+CREATE TYPE "changeOrderTypeEnum" AS ENUM (+ 'Engineering',+ 'Manufacturing',+ 'Documentation'+);++-- Forward-only stage flow, one step at a time. Start/Implementation/Done broadcast+-- a team notification.+CREATE TYPE "changeOrderStatus" AS ENUM (+ 'Draft',+ 'Start',+ 'Engineering Complete',+ 'Implementation',+ 'Done'+);++CREATE TYPE "itemRevisionStatus" AS ENUM (+ 'Design',+ 'Prototype',+ 'Production',+ 'Obsolete'+);++-- Mirrors nonConformanceTaskStatus.+CREATE TYPE "changeOrderTaskStatus" AS ENUM (+ 'Pending',+ 'In Progress',+ 'Completed',+ 'Skipped'+);++-- Per-affected-item change type — drives the release action and the editing surface:+-- Version = new method version on the same item; no supersession.+-- Revision = new revision item, attributes/docs only; auto supersession.+-- New Part = new part number derived from and superseding the part; auto supersession.+CREATE TYPE "changeOrderChangeType" AS ENUM (+ 'Version',+ 'Revision',+ 'New Part'+);++-- -----------------------------------------------------------------------------+-- 2. changeOrderType — the "Category" lookup (clones nonConformanceType)+-- -----------------------------------------------------------------------------+CREATE TABLE "changeOrderType" (+ "id" TEXT NOT NULL DEFAULT id('cot'),+ "name" TEXT NOT NULL,+ "companyId" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,+ "createdBy" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,++ CONSTRAINT "changeOrderType_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "changeOrderType_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "changeOrderType_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "changeOrderType_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE+);++CREATE INDEX "changeOrderType_companyId_idx" ON "changeOrderType" ("companyId");++ALTER TABLE "changeOrderType" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."changeOrderType"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+);++CREATE POLICY "INSERT" ON "public"."changeOrderType"+FOR INSERT WITH CHECK (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_create'))::text[])+);++CREATE POLICY "UPDATE" ON "public"."changeOrderType"+FOR UPDATE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_update'))::text[])+);++CREATE POLICY "DELETE" ON "public"."changeOrderType"+FOR DELETE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_delete'))::text[])+);++-- Seed default categories for every existing company.+INSERT INTO "changeOrderType" ("name", "companyId", "createdBy")+SELECT co_types.name, c."id", 'system'+FROM "company" c+CROSS JOIN (VALUES+ ('Design Improvement'),+ ('Cost Reduction'),+ ('Quality / Reliability Improvement'),+ ('Supplier / Sourcing Change'),+ ('Material or Component Change'),+ ('Obsolescence / End-of-Life'),+ ('Regulatory / Compliance'),+ ('Safety'),+ ('Manufacturing / Producibility'),+ ('Customer Request'),+ ('Documentation Error / Correction')+) AS co_types(name);++-- -----------------------------------------------------------------------------+-- 3. changeOrder (parent) — clones nonConformance+-- -----------------------------------------------------------------------------+CREATE TABLE "changeOrder" (+ "id" TEXT NOT NULL DEFAULT id('co'),+ "changeOrderId" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ -- reasonForChange = why; description = what. Both are rich-text JSON editors.+ "reasonForChange" JSON NOT NULL DEFAULT '{}',+ "description" JSON NOT NULL DEFAULT '{}',+ "type" "changeOrderTypeEnum" NOT NULL DEFAULT 'Engineering',+ "status" "changeOrderStatus" NOT NULL DEFAULT 'Draft',+ "priority" "nonConformancePriority",+ "changeOrderTypeId" TEXT,+ -- Optional link to the NCR that originated this change (navigable both ways;+ -- SET NULL so deleting the NCR doesn't cascade-delete the CO).+ "nonConformanceId" TEXT,+ "openDate" DATE NOT NULL,+ "dueDate" DATE,+ "requiredActionIds" TEXT[] DEFAULT ARRAY[]::TEXT[],+ "approvalRequirements" TEXT[] DEFAULT ARRAY[]::TEXT[],+ "sourceType" TEXT,+ "sourceId" TEXT,+ "assignee" TEXT,+ "customFields" JSONB,+ "tags" TEXT[] DEFAULT ARRAY[]::TEXT[],+ "companyId" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,+ "createdBy" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,++ CONSTRAINT "changeOrder_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "changeOrder_companyId_changeOrderId_key" UNIQUE ("companyId", "changeOrderId"),+ CONSTRAINT "changeOrder_changeOrderTypeId_fkey" FOREIGN KEY ("changeOrderTypeId") REFERENCES "changeOrderType"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "changeOrder_nonConformanceId_fkey" FOREIGN KEY ("nonConformanceId") REFERENCES "nonConformance"("id") ON DELETE SET NULL ON UPDATE CASCADE,+ CONSTRAINT "changeOrder_assignee_fkey" FOREIGN KEY ("assignee") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "changeOrder_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "changeOrder_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "changeOrder_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE+);++CREATE INDEX "changeOrder_companyId_idx" ON "changeOrder" ("companyId");+CREATE INDEX "changeOrder_changeOrderTypeId_idx" ON "changeOrder" ("changeOrderTypeId");+CREATE INDEX "changeOrder_nonConformanceId_idx" ON "changeOrder" ("nonConformanceId");+CREATE INDEX "changeOrder_status_idx" ON "changeOrder" ("status");+CREATE INDEX "changeOrder_assignee_idx" ON "changeOrder" ("assignee");++ALTER TABLE "changeOrder" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."changeOrder"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_view'))::text[])+);++CREATE POLICY "INSERT" ON "public"."changeOrder"+FOR INSERT WITH CHECK (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_create'))::text[])+);++CREATE POLICY "UPDATE" ON "public"."changeOrder"+FOR UPDATE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_update'))::text[])+);++CREATE POLICY "DELETE" ON "public"."changeOrder"+FOR DELETE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_delete'))::text[])+);++-- -----------------------------------------------------------------------------+-- 4. makeMethod.changeOrderId — a Draft makeMethod with a non-null changeOrderId is+-- CO-owned and hidden from version-list/switcher/copy-target reads until release.+-- MRP/jobs/cost key off activeMakeMethods (non-Archived), so they're unaffected.+-- SET NULL so deleting the CO doesn't cascade-delete method history.+-- -----------------------------------------------------------------------------+ALTER TABLE "makeMethod" ADD COLUMN IF NOT EXISTS "changeOrderId" TEXT;+ALTER TABLE "makeMethod" ADD CONSTRAINT "makeMethod_changeOrderId_fkey"+ FOREIGN KEY ("changeOrderId") REFERENCES "changeOrder"("id") ON DELETE SET NULL ON UPDATE CASCADE;+CREATE INDEX IF NOT EXISTS "makeMethod_changeOrderId_idx" ON "makeMethod" ("changeOrderId");++-- -----------------------------------------------------------------------------+-- 5. changeOrderAffectedItem — the parts the user selects to change. Per-item edits+-- live on a CO-owned Draft makeMethod (draftMakeMethodId), edited via the normal+-- BillOfMaterial/BillOfProcess/PartProperties editors and hidden until release.+-- -----------------------------------------------------------------------------+CREATE TABLE "changeOrderAffectedItem" (+ "id" TEXT NOT NULL DEFAULT id('coai'),+ "changeOrderId" TEXT NOT NULL,+ "itemId" TEXT NOT NULL,+ "sortOrder" INTEGER NOT NULL DEFAULT 0,+ "changeType" "changeOrderChangeType" NOT NULL DEFAULT 'Version',+ -- The CO-owned Draft makeMethod this affected item edits (created on add).+ "draftMakeMethodId" TEXT,+ -- The Active method version the draft was copied from (merge base for the+ -- release diff). Nullable for a New Part with no source method.+ "baseMakeMethodId" TEXT,+ -- Per-item revision cutover config: the oldRev→newRev supersession is auto-written+ -- at release; the user only tunes mode + dates (empty successorEffectivityDate =+ -- effective immediately at release).+ "supersessionMode" "supersessionMode" NOT NULL DEFAULT 'Consume First',+ "discontinuationDate" DATE,+ "successorEffectivityDate" DATE,+ -- Release idempotency marker: the created revision's itemId, set at release.+ -- Non-null => this affected item is already applied; skip on re-run.+ "newItemId" TEXT,+ "changeSummary" JSONB,+ "companyId" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,+ "createdBy" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,++ CONSTRAINT "changeOrderAffectedItem_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "changeOrderAffectedItem_changeOrderId_itemId_key" UNIQUE ("changeOrderId", "itemId"),+ CONSTRAINT "changeOrderAffectedItem_changeOrderId_fkey" FOREIGN KEY ("changeOrderId") REFERENCES "changeOrder"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "changeOrderAffectedItem_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "changeOrderAffectedItem_newItemId_fkey" FOREIGN KEY ("newItemId") REFERENCES "item"("id") ON DELETE SET NULL ON UPDATE CASCADE,+ CONSTRAINT "changeOrderAffectedItem_draftMakeMethodId_fkey" FOREIGN KEY ("draftMakeMethodId") REFERENCES "makeMethod"("id") ON DELETE SET NULL ON UPDATE CASCADE,+ CONSTRAINT "changeOrderAffectedItem_baseMakeMethodId_fkey" FOREIGN KEY ("baseMakeMethodId") REFERENCES "makeMethod"("id") ON DELETE SET NULL ON UPDATE CASCADE,+ CONSTRAINT "changeOrderAffectedItem_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "changeOrderAffectedItem_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "changeOrderAffectedItem_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE+);++CREATE INDEX "changeOrderAffectedItem_changeOrderId_idx" ON "changeOrderAffectedItem" ("changeOrderId");+CREATE INDEX "changeOrderAffectedItem_itemId_idx" ON "changeOrderAffectedItem" ("itemId");+CREATE INDEX "changeOrderAffectedItem_newItemId_idx" ON "changeOrderAffectedItem" ("newItemId");+CREATE INDEX "changeOrderAffectedItem_draftMakeMethodId_idx" ON "changeOrderAffectedItem" ("draftMakeMethodId");+CREATE INDEX "changeOrderAffectedItem_baseMakeMethodId_idx" ON "changeOrderAffectedItem" ("baseMakeMethodId");+CREATE INDEX "changeOrderAffectedItem_companyId_idx" ON "changeOrderAffectedItem" ("companyId");++ALTER TABLE "changeOrderAffectedItem" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."changeOrderAffectedItem"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_view'))::text[])+);++CREATE POLICY "INSERT" ON "public"."changeOrderAffectedItem"+FOR INSERT WITH CHECK (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_create'))::text[])+);++CREATE POLICY "UPDATE" ON "public"."changeOrderAffectedItem"+FOR UPDATE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_update'))::text[])+);++CREATE POLICY "DELETE" ON "public"."changeOrderAffectedItem"+FOR DELETE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_delete'))::text[])+);++-- -----------------------------------------------------------------------------+-- 6. changeOrderSupersession — manual different-part obsolescence declarations+-- (NOT revision cutover, which is auto-generated from changeOrderAffectedItem).+-- -----------------------------------------------------------------------------+CREATE TABLE "changeOrderSupersession" (+ "id" TEXT NOT NULL DEFAULT id('cosup'),+ "changeOrderId" TEXT NOT NULL,+ "predecessorItemId" TEXT NOT NULL,+ "successorItemId" TEXT,+ "supersessionMode" "supersessionMode" NOT NULL DEFAULT 'Consume First',+ "discontinuationDate" DATE,+ "successorEffectivityDate" DATE,+ "companyId" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,+ "createdBy" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,++ CONSTRAINT "changeOrderSupersession_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "changeOrderSupersession_changeOrderId_fkey" FOREIGN KEY ("changeOrderId") REFERENCES "changeOrder"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "changeOrderSupersession_predecessorItemId_fkey" FOREIGN KEY ("predecessorItemId") REFERENCES "item"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "changeOrderSupersession_successorItemId_fkey" FOREIGN KEY ("successorItemId") REFERENCES "item"("id") ON DELETE SET NULL ON UPDATE CASCADE,+ CONSTRAINT "changeOrderSupersession_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "changeOrderSupersession_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "changeOrderSupersession_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE+);++CREATE INDEX "changeOrderSupersession_changeOrderId_idx" ON "changeOrderSupersession" ("changeOrderId");+CREATE INDEX "changeOrderSupersession_predecessorItemId_idx" ON "changeOrderSupersession" ("predecessorItemId");+CREATE INDEX "changeOrderSupersession_successorItemId_idx" ON "changeOrderSupersession" ("successorItemId");+CREATE INDEX "changeOrderSupersession_companyId_idx" ON "changeOrderSupersession" ("companyId");++ALTER TABLE "changeOrderSupersession" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."changeOrderSupersession"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_view'))::text[])+);++CREATE POLICY "INSERT" ON "public"."changeOrderSupersession"+FOR INSERT WITH CHECK (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_create'))::text[])+);++CREATE POLICY "UPDATE" ON "public"."changeOrderSupersession"+FOR UPDATE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_update'))::text[])+);++CREATE POLICY "DELETE" ON "public"."changeOrderSupersession"+FOR DELETE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_delete'))::text[])+);++-- -----------------------------------------------------------------------------+-- 7. changeOrderActionTask — freeform, non-gating tasks (clones nonConformanceActionTask).+-- actionTypeId (template link) is added in the follow-up required-actions migration.+-- -----------------------------------------------------------------------------+CREATE TABLE "changeOrderActionTask" (+ "id" TEXT NOT NULL DEFAULT id('coat'),+ "changeOrderId" TEXT NOT NULL,+ "name" TEXT,+ "status" "changeOrderTaskStatus" NOT NULL DEFAULT 'Pending',+ "dueDate" DATE,+ "completedDate" DATE,+ "assignee" TEXT,+ "notes" JSON NOT NULL DEFAULT '{}',+ "sortOrder" INTEGER NOT NULL DEFAULT 0,+ "tags" TEXT[] DEFAULT ARRAY[]::TEXT[],+ "companyId" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,+ "createdBy" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,++ CONSTRAINT "changeOrderActionTask_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "changeOrderActionTask_changeOrderId_fkey" FOREIGN KEY ("changeOrderId") REFERENCES "changeOrder"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "changeOrderActionTask_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "changeOrderActionTask_assignee_fkey" FOREIGN KEY ("assignee") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "changeOrderActionTask_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "changeOrderActionTask_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE+);++CREATE INDEX "changeOrderActionTask_changeOrderId_idx" ON "changeOrderActionTask" ("changeOrderId");+CREATE INDEX "changeOrderActionTask_assignee_idx" ON "changeOrderActionTask" ("assignee");+CREATE INDEX "changeOrderActionTask_status_idx" ON "changeOrderActionTask" ("status");++ALTER TABLE "changeOrderActionTask" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."changeOrderActionTask"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_view'))::text[])+);++CREATE POLICY "INSERT" ON "public"."changeOrderActionTask"+FOR INSERT WITH CHECK (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_create'))::text[])+);++CREATE POLICY "UPDATE" ON "public"."changeOrderActionTask"+FOR UPDATE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_update'))::text[])+);++CREATE POLICY "DELETE" ON "public"."changeOrderActionTask"+FOR DELETE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_delete'))::text[])+);++-- -----------------------------------------------------------------------------+-- 8. Columns added to the existing item table.+-- revisionStatus — lifecycle state of the revision.+-- changeOrderId — revision→CO back-link, stamped at release on each newly-created+-- revision item; powers the "Created by CO-…" chip and change+-- history. SET NULL so deleting a CO doesn't cascade items.+-- -----------------------------------------------------------------------------+ALTER TABLE "item" ADD COLUMN "revisionStatus" "itemRevisionStatus" NOT NULL DEFAULT 'Design';+ALTER TABLE "item" ADD COLUMN "changeOrderId" TEXT;+ALTER TABLE "item" ADD CONSTRAINT "item_changeOrderId_fkey" FOREIGN KEY ("changeOrderId") REFERENCES "changeOrder"("id") ON DELETE SET NULL ON UPDATE CASCADE;+CREATE INDEX "item_changeOrderId_idx" ON "item" ("changeOrderId");++-- -----------------------------------------------------------------------------+-- 9. companySettings.plmReleaseControl — how strictly release rules are enforced.+-- TEXT + CHECK is the convention for constrained string settings; existing RLS+-- on companySettings covers new columns automatically.+-- -----------------------------------------------------------------------------+ALTER TABLE "companySettings" ADD COLUMN "plmReleaseControl" TEXT NOT NULL DEFAULT 'enforce' CHECK ("plmReleaseControl" IN ('off', 'warn', 'enforce'));++-- -----------------------------------------------------------------------------+-- 10. Custom-fields registration (idempotent — the registry row survives a re-run+-- of this migration because it lives outside the CO-owned tables).+-- -----------------------------------------------------------------------------+INSERT INTO "customFieldTable" ("table", "name", "module")+VALUES ('changeOrder', 'Change Order', 'Items')+ON CONFLICT ("table") DO NOTHING;++-- -----------------------------------------------------------------------------+-- 11. Sequence seed — change order readable id per company (ECO-000001, size 6).+-- -----------------------------------------------------------------------------+INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step", "companyId")+SELECT 'changeOrder', 'Change Order', 'ECO-', NULL, 0, 6, 1, "id"+FROM "company"+ON CONFLICT ("table", "companyId") DO NOTHING;++-- -----------------------------------------------------------------------------+-- 12. Realtime — the change-orders list uses useRealtime("changeOrder").+-- -----------------------------------------------------------------------------+ALTER PUBLICATION supabase_realtime ADD TABLE "changeOrder";++-- -----------------------------------------------------------------------------+-- 13. changeOrders view — powers the change-orders list. Rolls each CO's affected+-- items up into an "itemIds" text[] (so the list can filter by item through+-- the generic .overlaps() filter path) and an "affectedItems" jsonb array (so+-- a list row can be expanded to show its affected items without a 2nd query).+-- SECURITY_INVOKER so the underlying tables' RLS applies to the caller.+-- -----------------------------------------------------------------------------+DROP VIEW IF EXISTS "changeOrders";+CREATE OR REPLACE VIEW "changeOrders" WITH (SECURITY_INVOKER=true) AS+ SELECT+ co.*,+ COALESCE(ai."itemIds", ARRAY[]::text[]) AS "itemIds",+ COALESCE(ai."affectedItems", '[]'::jsonb) AS "affectedItems"+ FROM "changeOrder" co+ LEFT JOIN (+ SELECT+ "changeOrderId",+ array_agg(DISTINCT "itemId") AS "itemIds",+ jsonb_agg(+ jsonb_build_object(+ 'id', "id",+ 'itemId', "itemId",+ 'changeType', "changeType",+ 'newItemId', "newItemId"+ )+ ORDER BY "sortOrder", "createdAt"+ ) AS "affectedItems"+ FROM "changeOrderAffectedItem"+ GROUP BY "changeOrderId"+ ) ai ON ai."changeOrderId" = co."id";diff --git a/packages/database/supabase/migrations/20260716101600_change-order-required-actions.sql b/packages/database/supabase/migrations/20260716101600_change-order-required-actions.sqlnew file mode 100644index 0000000000..c04170c567--- /dev/null+++ b/packages/database/supabase/migrations/20260716101600_change-order-required-actions.sql@@ -0,0 +1,90 @@+-- Configurable template actions for Change Orders. Mirrors nonConformanceRequiredAction,+-- but company-scoped with a composite PK and no systemType/protection (all CO templates+-- are freely deletable). New change orders instantiate one changeOrderActionTask per+-- active row (insertChangeOrder -> seedDefaultChangeOrderActions).++CREATE TABLE IF NOT EXISTS "changeOrderRequiredAction" (+ "id" TEXT NOT NULL DEFAULT id('cora'),+ "companyId" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "active" BOOLEAN NOT NULL DEFAULT TRUE,+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "customFields" JSONB,++ PRIMARY KEY ("id", "companyId"),+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE+);++CREATE INDEX IF NOT EXISTS "changeOrderRequiredAction_companyId_idx" ON "changeOrderRequiredAction" ("companyId");+CREATE INDEX IF NOT EXISTS "changeOrderRequiredAction_createdBy_idx" ON "changeOrderRequiredAction" ("createdBy");++ALTER TABLE "changeOrderRequiredAction" DROP CONSTRAINT IF EXISTS "changeOrderRequiredAction_companyId_name_key";+ALTER TABLE "changeOrderRequiredAction" ADD CONSTRAINT "changeOrderRequiredAction_companyId_name_key" UNIQUE ("companyId", "name");++-- Single-column unique on the (globally unique) id so changeOrderActionTask.actionTypeId+-- can FK to it despite the composite PK.+ALTER TABLE "changeOrderRequiredAction" DROP CONSTRAINT IF EXISTS "changeOrderRequiredAction_id_key";+ALTER TABLE "changeOrderRequiredAction" ADD CONSTRAINT "changeOrderRequiredAction_id_key" UNIQUE ("id");++ALTER TABLE "public"."changeOrderRequiredAction" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."changeOrderRequiredAction"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+);++CREATE POLICY "INSERT" ON "public"."changeOrderRequiredAction"+FOR INSERT WITH CHECK (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_create'))::text[])+);++CREATE POLICY "UPDATE" ON "public"."changeOrderRequiredAction"+FOR UPDATE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_update'))::text[])+);++CREATE POLICY "DELETE" ON "public"."changeOrderRequiredAction"+FOR DELETE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_delete'))::text[])+);++-- Backfill defaults for existing companies (system user for the createdBy FK;+-- idempotent via the (companyId, name) unique constraint).+INSERT INTO "changeOrderRequiredAction" ("companyId", "name", "createdBy")+SELECT c."id", action.name, 'system'+FROM "company" c+CROSS JOIN (VALUES+ ('Engineering Review'),+ ('Update Drawings / CAD'),+ ('Update BOM / Routing'),+ ('Cost Impact Review'),+ ('Quality Review'),+ ('Inventory Disposition (rework / scrap / use-as-is)'),+ ('Notify Affected Parties')+) AS action(name)+ON CONFLICT ("companyId", "name") DO NOTHING;++-- Link each instantiated action task back to its template (mirrors+-- nonConformanceActionTask.actionTypeId). Powers the sidebar's Required Actions+-- multiselect: selected = the templates that have a task.+ALTER TABLE "changeOrderActionTask" ADD COLUMN IF NOT EXISTS "actionTypeId" TEXT;++ALTER TABLE "changeOrderActionTask" DROP CONSTRAINT IF EXISTS "changeOrderActionTask_actionTypeId_fkey";+ALTER TABLE "changeOrderActionTask"+ ADD CONSTRAINT "changeOrderActionTask_actionTypeId_fkey"+ FOREIGN KEY ("actionTypeId") REFERENCES "changeOrderRequiredAction"("id")+ ON UPDATE CASCADE ON DELETE SET NULL;++CREATE INDEX IF NOT EXISTS "changeOrderActionTask_actionTypeId_idx"+ ON "changeOrderActionTask" ("actionTypeId");++-- Backfill the link for any tasks already seeded by name (per company).+UPDATE "changeOrderActionTask" cat+SET "actionTypeId" = cra."id"+FROM "changeOrderRequiredAction" cra+WHERE cra."name" = cat."name"+ AND cra."companyId" = cat."companyId"+ AND cat."actionTypeId" IS NULL;diff --git a/packages/database/supabase/migrations/20260717143512_change-order-cancelled-status.sql b/packages/database/supabase/migrations/20260717143512_change-order-cancelled-status.sqlnew file mode 100644index 0000000000..d1e803b110--- /dev/null+++ b/packages/database/supabase/migrations/20260717143512_change-order-cancelled-status.sql@@ -0,0 +1,5 @@+-- Add a "Cancelled" terminal status to change orders so a CO can be closed+-- (abandoned before release) from any open stage and later reopened to Draft.+-- Mirrors the job lifecycle (Cancel -> Cancelled -> Reopen). Appended at the end+-- of the enum; ADD VALUE IF NOT EXISTS is idempotent across retries / DB resets.+ALTER TYPE "changeOrderStatus" ADD VALUE IF NOT EXISTS 'Cancelled';diff --git a/packages/database/supabase/migrations/20260718224137_active-revision-view-pick.sql b/packages/database/supabase/migrations/20260718224137_active-revision-view-pick.sqlnew file mode 100644index 0000000000..10599923a3--- /dev/null+++ b/packages/database/supabase/migrations/20260718224137_active-revision-view-pick.sql@@ -0,0 +1,548 @@+-- Prefer ACTIVE revisions when the item list views collapse to one row per+-- (readableId, companyId).+--+-- A Change Order that adds a Revision/New Part affected item mints the new+-- revision item as `active = false` (revealed to `active = true` only at+-- release). The list views' `latest_items` DISTINCT ON pick ordered solely by+-- "newest named revision, then createdAt DESC" — so an unreleased inactive draft+-- revision (highest createdAt) hijacked the surfaced row and showed up as the+-- item's current revision before the CO was ever released.+--+-- Fix: make `active DESC` the first tiebreaker after the DISTINCT ON columns, so+-- an active revision always wins over an inactive one. Falling back to (rather+-- than excluding) inactive rows keeps an item visible if it has no active+-- revision at all. Only the `latest_items` ordering changes; output columns are+-- identical (required by CREATE OR REPLACE VIEW).+--+-- Applied to all five item list views. Change Order affected items are+-- Parts/Tools only (so only those two can carry a CO draft revision today), but+-- materials/consumables/services share the identical revision pick and would hit+-- the same bug for any manually-deactivated latest revision — fixed for+-- consistency.++CREATE OR REPLACE VIEW "parts" WITH (SECURITY_INVOKER=true) AS+WITH latest_items AS (+ SELECT DISTINCT ON (i."readableId", i."companyId")+ i.*,+ mu.id as "modelUploadId",++ mu."modelPath",+ mu."thumbnailPath" as "modelThumbnailPath",+ mu."name" as "modelName",+ mu."size" as "modelSize"+ FROM "item" i+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ WHERE i."type" = 'Part'+ ORDER BY i."readableId", i."companyId",+ i."active" DESC,+ CASE WHEN i."revision" = '0' OR i."revision" = '' OR i."revision" IS NULL THEN 0 ELSE 1 END DESC,+ i."createdAt" DESC NULLS LAST+),+item_revisions AS (+ SELECT+ i."readableId",+ i."companyId",+ json_agg(+ json_build_object(+ 'id', i.id,+ 'revision', i."revision",+ 'name', i."name",+ 'description', i."description",+ 'active', i."active",+ 'createdAt', i."createdAt"+ ) ORDER BY+ CASE WHEN i."revision" = '0' OR i."revision" = '' OR i."revision" IS NULL THEN 0 ELSE 1 END,+ i."createdAt"+ ) as "revisions"+ FROM "item" i+ WHERE i."type" = 'Part'+ GROUP BY i."readableId", i."companyId"+)+SELECT+ li."active",+ li."assignee",+ li."defaultMethodType",+ li."sourcingType",+ li."description",+ li."itemTrackingType",+ li."name",+ li."replenishmentSystem",+ li."unitOfMeasureCode",+ li."notes",+ li."revision",+ li."readableId",+ li."readableIdWithRevision",+ li."id",+ li."companyId",+ CASE+ WHEN li."thumbnailPath" IS NULL AND li."modelThumbnailPath" IS NOT NULL THEN li."modelThumbnailPath"+ ELSE li."thumbnailPath"+ END as "thumbnailPath",++ li."modelPath",+ li."modelName",+ li."modelSize",+ ps."supplierIds",+ uom.name as "unitOfMeasure",+ ir."revisions",+ p."customFields",+ p."tags",+ ic."itemPostingGroupId",+ (+ SELECT COALESCE(+ jsonb_object_agg(+ eim."integration",+ CASE+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"+ ELSE to_jsonb(eim."externalId")+ END+ ) FILTER (WHERE eim."externalId" IS NOT NULL OR eim."metadata" IS NOT NULL),+ '{}'::jsonb+ )+ FROM "externalIntegrationMapping" eim+ WHERE eim."entityType" = 'item' AND eim."entityId" = li.id+ ) AS "externalId",+ li."createdBy",+ li."createdAt",+ li."updatedBy",+ li."updatedAt",+ ss."supersessionMode",+ li."mpn"+FROM "part" p+INNER JOIN latest_items li ON li."readableId" = p."id" AND li."companyId" = p."companyId"+LEFT JOIN item_revisions ir ON ir."readableId" = p."id" AND ir."companyId" = p."companyId"+LEFT JOIN (+ SELECT+ "itemId",+ "companyId",+ string_agg(ps."supplierPartId", ',') AS "supplierIds"+ FROM "supplierPart" ps+ GROUP BY "itemId", "companyId"+) ps ON ps."itemId" = li."id" AND ps."companyId" = li."companyId"+LEFT JOIN "unitOfMeasure" uom ON uom.code = li."unitOfMeasureCode" AND uom."companyId" = li."companyId"+LEFT JOIN "itemCost" ic ON ic."itemId" = li.id+LEFT JOIN "itemSupersession" ss ON ss."itemId" = li.id AND ss."companyId" = li."companyId";+++CREATE OR REPLACE VIEW "tools" WITH (security_invoker = true) AS+ WITH latest_items AS (+ SELECT DISTINCT ON (i."readableId", i."companyId") i.id,+ i."readableId",+ i.name,+ i.description,+ i.type,+ i."replenishmentSystem",+ i."defaultMethodType",+ i."itemTrackingType",+ i."unitOfMeasureCode",+ i.active,+ i."companyId",+ i."createdBy",+ i."createdAt",+ i."updatedBy",+ i."updatedAt",+ i.assignee,+ i."modelUploadId",+ i."thumbnailPath",+ i.notes,+ i."trackingMethod",+ i.embedding,+ i.revision,+ i."readableIdWithRevision",+ i."requiresInspection",+ i."sourcingType",+ mu.id AS "modelUploadId",+ mu."modelPath",+ mu."thumbnailPath" AS "modelThumbnailPath",+ mu.name AS "modelName",+ mu.size AS "modelSize",+ i."mpn"+ FROM item i+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ WHERE i.type = 'Tool'::"itemType"+ ORDER BY i."readableId", i."companyId", i.active DESC, (+ CASE+ WHEN i.revision = '0'::text OR i.revision = ''::text OR i.revision IS NULL THEN 0+ ELSE 1+ END) DESC, i."createdAt" DESC NULLS LAST+ ), item_revisions AS (+ SELECT i."readableId",+ i."companyId",+ json_agg(json_build_object('id', i.id, 'revision', i.revision, 'methodType', i."defaultMethodType", 'type', i.type) ORDER BY (+ CASE+ WHEN i.revision = '0'::text OR i.revision = ''::text OR i.revision IS NULL THEN 0+ ELSE 1+ END), i."createdAt") AS revisions+ FROM item i+ WHERE i.type = 'Tool'::"itemType"+ GROUP BY i."readableId", i."companyId"+ )+ SELECT li.active,+ li.assignee,+ li."defaultMethodType",+ li."sourcingType",+ li.description,+ li."itemTrackingType",+ li.name,+ li."replenishmentSystem",+ li."unitOfMeasureCode",+ li.notes,+ li.revision,+ li."readableId",+ li."readableIdWithRevision",+ li.id,+ li."companyId",+ CASE+ WHEN li."thumbnailPath" IS NULL AND li."modelThumbnailPath" IS NOT NULL THEN li."modelThumbnailPath"+ ELSE li."thumbnailPath"+ END AS "thumbnailPath",+ li."modelPath",+ li."modelName",+ li."modelSize",+ ps."supplierIds",+ uom.name AS "unitOfMeasure",+ ir.revisions,+ t."customFields",+ t.tags,+ ic."itemPostingGroupId",+ ( SELECT COALESCE(jsonb_object_agg(eim.integration,+ CASE+ WHEN eim.metadata IS NOT NULL THEN eim.metadata+ ELSE to_jsonb(eim."externalId")+ END) FILTER (WHERE eim."externalId" IS NOT NULL OR eim.metadata IS NOT NULL), '{}'::jsonb) AS "coalesce"+ FROM "externalIntegrationMapping" eim+ WHERE eim."entityType" = 'item'::text AND eim."entityId" = li.id) AS "externalId",+ li."createdBy",+ li."createdAt",+ li."updatedBy",+ li."updatedAt",+ ss."supersessionMode",+ li."mpn"+ FROM tool t+ JOIN latest_items li(id, "readableId", name, description, type, "replenishmentSystem", "defaultMethodType", "itemTrackingType", "unitOfMeasureCode", active, "companyId", "createdBy", "createdAt", "updatedBy", "updatedAt", assignee, "modelUploadId", "thumbnailPath", notes, "trackingMethod", embedding, revision, "readableIdWithRevision", "requiresInspection", "sourcingType", "modelUploadId_1", "modelPath", "modelThumbnailPath", "modelName", "modelSize", "mpn") ON li."readableId" = t.id AND li."companyId" = t."companyId"+ LEFT JOIN item_revisions ir ON ir."readableId" = t.id AND ir."companyId" = li."companyId"+ LEFT JOIN ( SELECT ps_1."itemId",+ ps_1."companyId",+ string_agg(ps_1."supplierPartId", ','::text) AS "supplierIds"+ FROM "supplierPart" ps_1+ GROUP BY ps_1."itemId", ps_1."companyId") ps ON ps."itemId" = li.id AND ps."companyId" = li."companyId"+ LEFT JOIN "unitOfMeasure" uom ON uom.code = li."unitOfMeasureCode" AND uom."companyId" = li."companyId"+ LEFT JOIN "itemCost" ic ON ic."itemId" = li.id+ LEFT JOIN "itemSupersession" ss ON ss."itemId" = li.id AND ss."companyId" = li."companyId";+++CREATE OR REPLACE VIEW "materials" WITH (security_invoker = true) AS+ WITH latest_items AS (+ SELECT DISTINCT ON (i_1."readableId", i_1."companyId") i_1.id,+ i_1."readableId",+ i_1.name,+ i_1.description,+ i_1.type,+ i_1."replenishmentSystem",+ i_1."defaultMethodType",+ i_1."itemTrackingType",+ i_1."unitOfMeasureCode",+ i_1.active,+ i_1."companyId",+ i_1."createdBy",+ i_1."createdAt",+ i_1."updatedBy",+ i_1."updatedAt",+ i_1.assignee,+ i_1."modelUploadId",+ i_1."thumbnailPath",+ i_1.notes,+ i_1."trackingMethod",+ i_1.embedding,+ i_1.revision,+ i_1."readableIdWithRevision",+ i_1."requiresInspection",+ i_1.mpn,+ mu_1."modelPath",+ mu_1."thumbnailPath" AS "modelThumbnailPath",+ mu_1.name AS "modelName",+ mu_1.size AS "modelSize"+ FROM item i_1+ LEFT JOIN "modelUpload" mu_1 ON mu_1.id = i_1."modelUploadId"+ WHERE i_1.type = 'Material'::"itemType"+ ORDER BY i_1."readableId", i_1."companyId", i_1.active DESC, (+ CASE+ WHEN i_1.revision = '0'::text OR i_1.revision = ''::text OR i_1.revision IS NULL THEN 0+ ELSE 1+ END) DESC, i_1."createdAt" DESC NULLS LAST+ ), item_revisions AS (+ SELECT i_1."readableId",+ i_1."companyId",+ json_agg(json_build_object('id', i_1.id, 'revision', i_1.revision, 'methodType', i_1."defaultMethodType", 'type', i_1.type) ORDER BY (+ CASE+ WHEN i_1.revision = '0'::text OR i_1.revision = ''::text OR i_1.revision IS NULL THEN 0+ ELSE 1+ END), i_1."createdAt") AS revisions+ FROM item i_1+ WHERE i_1.type = 'Material'::"itemType"+ GROUP BY i_1."readableId", i_1."companyId"+ )+ SELECT i.active,+ i.assignee,+ i."defaultMethodType",+ i.description,+ i."itemTrackingType",+ i.name,+ i."replenishmentSystem",+ i."unitOfMeasureCode",+ i.notes,+ i.revision,+ i."readableId",+ i."readableIdWithRevision",+ i.id,+ i."companyId",+ CASE+ WHEN i."thumbnailPath" IS NULL AND i."modelThumbnailPath" IS NOT NULL THEN i."modelThumbnailPath"+ ELSE i."thumbnailPath"+ END AS "thumbnailPath",+ i."modelUploadId",+ i."modelPath",+ i."modelName",+ i."modelSize",+ ps."supplierIds",+ uom.name AS "unitOfMeasure",+ ir.revisions,+ mf.name AS "materialForm",+ ms.name AS "materialSubstance",+ md.name AS dimensions,+ mfin.name AS finish,+ mg.name AS grade,+ mt.name AS "materialType",+ m."materialSubstanceId",+ m."materialFormId",+ m."customFields",+ m.tags,+ ic."itemPostingGroupId",+ ( SELECT COALESCE(jsonb_object_agg(eim.integration,+ CASE+ WHEN eim.metadata IS NOT NULL THEN eim.metadata+ ELSE to_jsonb(eim."externalId")+ END) FILTER (WHERE eim."externalId" IS NOT NULL OR eim.metadata IS NOT NULL), '{}'::jsonb) AS "coalesce"+ FROM "externalIntegrationMapping" eim+ WHERE eim."entityType" = 'item'::text AND eim."entityId" = i.id) AS "externalId",+ i."createdBy",+ i."createdAt",+ i."updatedBy",+ i."updatedAt",+ ss."supersessionMode",+ i.mpn+ FROM material m+ JOIN latest_items i ON i."readableId" = m.id AND i."companyId" = m."companyId"+ LEFT JOIN item_revisions ir ON ir."readableId" = m.id AND ir."companyId" = i."companyId"+ LEFT JOIN ( SELECT ps_1."itemId",+ ps_1."companyId",+ string_agg(ps_1."supplierPartId", ','::text) AS "supplierIds"+ FROM "supplierPart" ps_1+ GROUP BY ps_1."itemId", ps_1."companyId") ps ON ps."itemId" = i.id AND ps."companyId" = i."companyId"+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ LEFT JOIN "unitOfMeasure" uom ON uom.code = i."unitOfMeasureCode" AND uom."companyId" = i."companyId"+ LEFT JOIN "materialForm" mf ON mf.id = m."materialFormId"+ LEFT JOIN "materialSubstance" ms ON ms.id = m."materialSubstanceId"+ LEFT JOIN "materialDimension" md ON m."dimensionId" = md.id+ LEFT JOIN "materialFinish" mfin ON m."finishId" = mfin.id+ LEFT JOIN "materialGrade" mg ON m."gradeId" = mg.id+ LEFT JOIN "materialType" mt ON m."materialTypeId" = mt.id+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id+ LEFT JOIN "itemSupersession" ss ON ss."itemId" = i.id AND ss."companyId" = i."companyId";+;+++CREATE OR REPLACE VIEW "consumables" WITH (security_invoker = true) AS+ WITH latest_items AS (+ SELECT DISTINCT ON (i."readableId", i."companyId") i.id,+ i."readableId",+ i.name,+ i.description,+ i.type,+ i."replenishmentSystem",+ i."defaultMethodType",+ i."itemTrackingType",+ i."unitOfMeasureCode",+ i.active,+ i."companyId",+ i."createdBy",+ i."createdAt",+ i."updatedBy",+ i."updatedAt",+ i.assignee,+ i."modelUploadId",+ i."thumbnailPath",+ i.notes,+ i."trackingMethod",+ i.embedding,+ i.revision,+ i."readableIdWithRevision",+ i."requiresInspection",+ i.mpn,+ mu."modelPath",+ mu."thumbnailPath" AS "modelThumbnailPath",+ mu.name AS "modelName",+ mu.size AS "modelSize"+ FROM item i+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ WHERE i.type = 'Consumable'::"itemType"+ ORDER BY i."readableId", i."companyId", i.active DESC, (+ CASE+ WHEN i.revision = '0'::text OR i.revision = ''::text OR i.revision IS NULL THEN 0+ ELSE 1+ END) DESC, i."createdAt" DESC NULLS LAST+ ), item_revisions AS (+ SELECT i."readableId",+ i."companyId",+ json_agg(json_build_object('id', i.id, 'revision', i.revision, 'methodType', i."defaultMethodType", 'type', i.type) ORDER BY (+ CASE+ WHEN i.revision = '0'::text OR i.revision = ''::text OR i.revision IS NULL THEN 0+ ELSE 1+ END), i."createdAt") AS revisions+ FROM item i+ WHERE i.type = 'Consumable'::"itemType"+ GROUP BY i."readableId", i."companyId"+ )+ SELECT li.active,+ li.assignee,+ li."defaultMethodType",+ li.description,+ li."itemTrackingType",+ li.name,+ li."replenishmentSystem",+ li."unitOfMeasureCode",+ li.notes,+ li.revision,+ li."readableId",+ li."readableIdWithRevision",+ li.id,+ li."companyId",+ CASE+ WHEN li."thumbnailPath" IS NULL AND li."modelThumbnailPath" IS NOT NULL THEN li."modelThumbnailPath"+ ELSE li."thumbnailPath"+ END AS "thumbnailPath",+ li."modelUploadId",+ li."modelPath",+ li."modelName",+ li."modelSize",+ ps."supplierIds",+ uom.name AS "unitOfMeasure",+ ir.revisions,+ c."customFields",+ c.tags,+ ic."itemPostingGroupId",+ ( SELECT COALESCE(jsonb_object_agg(eim.integration,+ CASE+ WHEN eim.metadata IS NOT NULL THEN eim.metadata+ ELSE to_jsonb(eim."externalId")+ END) FILTER (WHERE eim."externalId" IS NOT NULL OR eim.metadata IS NOT NULL), '{}'::jsonb) AS "coalesce"+ FROM "externalIntegrationMapping" eim+ WHERE eim."entityType" = 'item'::text AND eim."entityId" = li.id) AS "externalId",+ li."createdBy",+ li."createdAt",+ li."updatedBy",+ li."updatedAt",+ ss."supersessionMode",+ li.mpn+ FROM consumable c+ JOIN latest_items li ON li."readableId" = c.id AND li."companyId" = c."companyId"+ LEFT JOIN item_revisions ir ON ir."readableId" = c.id AND ir."companyId" = li."companyId"+ LEFT JOIN ( SELECT ps_1."itemId",+ ps_1."companyId",+ string_agg(ps_1."supplierPartId", ','::text) AS "supplierIds"+ FROM "supplierPart" ps_1+ GROUP BY ps_1."itemId", ps_1."companyId") ps ON ps."itemId" = li.id AND ps."companyId" = li."companyId"+ LEFT JOIN "unitOfMeasure" uom ON uom.code = li."unitOfMeasureCode" AND uom."companyId" = li."companyId"+ LEFT JOIN "itemCost" ic ON ic."itemId" = li.id+ LEFT JOIN "itemSupersession" ss ON ss."itemId" = li.id AND ss."companyId" = li."companyId";+;+++CREATE OR REPLACE VIEW "services" WITH (security_invoker = true) AS+ WITH latest_items AS (+ SELECT DISTINCT ON (i."readableId", i."companyId") i.id,+ i."readableId",+ i.name,+ i.description,+ i.type,+ i."replenishmentSystem",+ i."defaultMethodType",+ i."itemTrackingType",+ i."unitOfMeasureCode",+ i.active,+ i."companyId",+ i."createdBy",+ i."createdAt",+ i."updatedBy",+ i."updatedAt",+ i.assignee,+ i."modelUploadId",+ i."thumbnailPath",+ i.notes,+ i."trackingMethod",+ i.embedding,+ i.revision,+ i."readableIdWithRevision",+ i."requiresInspection"+ FROM item i+ WHERE i.type = 'Service'::"itemType"+ ORDER BY i."readableId", i."companyId", i.active DESC, (+ CASE+ WHEN i.revision = '0'::text OR i.revision = ''::text OR i.revision IS NULL THEN 0+ ELSE 1+ END) DESC, i."createdAt" DESC NULLS LAST+ ), item_revisions AS (+ SELECT i."readableId",+ i."companyId",+ json_agg(json_build_object('id', i.id, 'revision', i.revision, 'methodType', i."defaultMethodType", 'type', i.type) ORDER BY (+ CASE+ WHEN i.revision = '0'::text OR i.revision = ''::text OR i.revision IS NULL THEN 0+ ELSE 1+ END), i."createdAt") AS revisions+ FROM item i+ WHERE i.type = 'Service'::"itemType"+ GROUP BY i."readableId", i."companyId"+ )+ SELECT li.active,+ li.assignee,+ li."defaultMethodType",+ li.description,+ li."itemTrackingType",+ li.name,+ li."replenishmentSystem",+ li."unitOfMeasureCode",+ li.notes,+ li.revision,+ li."readableId",+ li."readableIdWithRevision",+ li.id,+ li."companyId",+ li."thumbnailPath",+ ps."supplierIds",+ uom.name AS "unitOfMeasure",+ ir.revisions,+ s."customFields",+ s.tags,+ ic."itemPostingGroupId",+ ( SELECT COALESCE(jsonb_object_agg(eim.integration,+ CASE+ WHEN eim.metadata IS NOT NULL THEN eim.metadata+ ELSE to_jsonb(eim."externalId")+ END) FILTER (WHERE eim."externalId" IS NOT NULL OR eim.metadata IS NOT NULL), '{}'::jsonb) AS "coalesce"+ FROM "externalIntegrationMapping" eim+ WHERE eim."entityType" = 'item'::text AND eim."entityId" = li.id) AS "externalId",+ li."createdBy",+ li."createdAt",+ li."updatedBy",+ li."updatedAt"+ FROM service s+ JOIN latest_items li ON li."readableId" = s.id AND li."companyId" = s."companyId"+ LEFT JOIN item_revisions ir ON ir."readableId" = s.id AND ir."companyId" = li."companyId"+ LEFT JOIN ( SELECT ps_1."itemId",+ ps_1."companyId",+ string_agg(ps_1."supplierPartId", ','::text) AS "supplierIds"+ FROM "supplierPart" ps_1+ GROUP BY ps_1."itemId", ps_1."companyId") ps ON ps."itemId" = li.id AND ps."companyId" = li."companyId"+ LEFT JOIN "unitOfMeasure" uom ON uom.code = li."unitOfMeasureCode" AND uom."companyId" = li."companyId"+ LEFT JOIN "itemCost" ic ON ic."itemId" = li.id;+;diff --git a/packages/database/supabase/migrations/20260719044345_co-replacement-part-change-type.sql b/packages/database/supabase/migrations/20260719044345_co-replacement-part-change-type.sqlnew file mode 100644index 0000000000..5eb7c35e7f--- /dev/null+++ b/packages/database/supabase/migrations/20260719044345_co-replacement-part-change-type.sql@@ -0,0 +1,22 @@+-- Rename the 1:1-supersession change type; existing changeOrderAffectedItem rows+-- carry over (they all already write an affected → new itemSupersession, so the+-- relabel is semantically exact). Then re-introduce 'New Part' as the net-new+-- (no-predecessor, no-supersession) type.+--+-- Idempotent / retry-safe: the DO-block guard renames only while 'New Part' still+-- exists and 'Replacement Part' does not; ADD VALUE IF NOT EXISTS re-adds the+-- net-new label on a retry.+DO $$+BEGIN+ IF EXISTS (+ SELECT 1 FROM pg_enum e JOIN pg_type t ON t.oid = e.enumtypid+ WHERE t.typname = 'changeOrderChangeType' AND e.enumlabel = 'New Part'+ ) AND NOT EXISTS (+ SELECT 1 FROM pg_enum e JOIN pg_type t ON t.oid = e.enumtypid+ WHERE t.typname = 'changeOrderChangeType' AND e.enumlabel = 'Replacement Part'+ ) THEN+ ALTER TYPE "changeOrderChangeType" RENAME VALUE 'New Part' TO 'Replacement Part';+ END IF;+END $$;++ALTER TYPE "changeOrderChangeType" ADD VALUE IF NOT EXISTS 'New Part';diff --git a/packages/dev/docker/docker-compose.dev.yml b/packages/dev/docker/docker-compose.dev.ymlindex d141bb4b54..1162f5b26e 100644--- a/packages/dev/docker/docker-compose.dev.yml+++ b/packages/dev/docker/docker-compose.dev.yml@@ -165,7 +165,7 @@ services:DB_USER: supabase_adminDB_PASSWORD: postgresDB_NAME: postgres- DB_AFTER_CONNECT_QUERY: 'SET search_path TO _realtime'+ DB_AFTER_CONNECT_QUERY: "SET search_path TO _realtime"DB_ENC_KEY: supabaserealtimeAPI_JWT_SECRET: ${SUPABASE_JWT_SECRET}METRICS_JWT_SECRET: ${SUPABASE_JWT_SECRET}diff --git a/packages/form/src/components/MultiSelect.tsx b/packages/form/src/components/MultiSelect.tsxindex 7cc48b35b8..8c752d55da 100644--- a/packages/form/src/components/MultiSelect.tsx+++ b/packages/form/src/components/MultiSelect.tsx@@ -51,11 +51,11 @@ const MultiSelectPreview = (const label = option ? option.label : val;return (<Badge- className="max-w-[160px] truncate border dark:border-none dark:shadow-button-base"+ className="max-w-[160px] border dark:border-none dark:shadow-button-base"key={val}variant="secondary">- {label}+ <span className="truncate">{label}</span></Badge>);})diff --git a/packages/glossary/src/terms.ts b/packages/glossary/src/terms.tsindex 36d9db287b..25e4832840 100644--- a/packages/glossary/src/terms.ts+++ b/packages/glossary/src/terms.ts@@ -69,6 +69,10 @@ export const terms = {definition: msg`Called a method in Carbon — the components plus operations that produce a part.`,href: "/docs/reference/methods"},+ "change-order": {+ term: msg`Change order`,+ definition: msg`An engineering change: the affected items whose methods are revised on a draft and released together, superseding the versions they replace.`+ },wip: {term: msg`Work in process (WIP)`,definition: msg`Not a table but a general-ledger balance: cost accumulates as job materials are issued and clears when the job is received to stock.`,@@ -1064,6 +1068,11 @@ export const terms = {definition: msg`Controls how planning handles a discontinued item: Consume First exhausts on-hand before switching to the successor, Prefer New redirects new demand to the successor immediately, Stock Only keeps only a minimum service reserve, and No Stock drops the item from planning entirely.`,aliases: ["phase-out", "spares-only", "obsolete"]},+ "change-order-change-type": {+ term: msg`Change Type`,+ definition: msg`What kind of change this is: Version updates how the part is made, Revision edits its details and documents, and New Part replaces it with a new part number.`,+ aliases: ["version", "revision", "new-part"]+ },// ── Items: Pick method / shelf life (PickMethodForm) ────────────────────"item-default-storage-unit": {diff --git a/packages/jobs/src/inngest/functions/notifications/content.ts b/packages/jobs/src/inngest/functions/notifications/content.tsindex b209897e9b..f5f14de507 100644--- a/packages/jobs/src/inngest/functions/notifications/content.ts+++ b/packages/jobs/src/inngest/functions/notifications/content.ts@@ -1052,6 +1052,40 @@ async function buildEventContent(};}+ case NotificationEvent.ChangeOrderSubmittedForReview:+ case NotificationEvent.ChangeOrderApproved:+ case NotificationEvent.ChangeOrderRejected:+ case NotificationEvent.ChangeOrderReleased: {+ const changeOrder = await client+ .from("changeOrder")+ .select("changeOrderId, status")+ .eq("id", documentId)+ .single();++ if (changeOrder.error || !changeOrder.data) {+ console.error("Failed to get changeOrder", changeOrder.error);+ throw changeOrder.error;+ }++ const readableId = changeOrder.data.changeOrderId;+ const description =+ type === NotificationEvent.ChangeOrderSubmittedForReview+ ? `Change order ${readableId} is ready for your review`+ : type === NotificationEvent.ChangeOrderApproved+ ? `Change order ${readableId} was approved`+ : type === NotificationEvent.ChangeOrderRejected+ ? `Change order ${readableId} was rejected`+ : `Change order ${readableId} was released`;++ return {+ description,+ reference: readableId ?? undefined,+ details: buildDetails([+ { label: "Status", value: changeOrder.data?.status }+ ])+ };+ }+default:return null;}diff --git a/packages/jobs/src/inngest/functions/notifications/notify.ts b/packages/jobs/src/inngest/functions/notifications/notify.tsindex e260c72dde..a9b859a66b 100644--- a/packages/jobs/src/inngest/functions/notifications/notify.ts+++ b/packages/jobs/src/inngest/functions/notifications/notify.ts@@ -62,6 +62,22 @@ const defaultDestinations: Partial<NotificationDestination.Email,NotificationDestination.Slack],+ [NotificationEvent.ChangeOrderApproved]: [+ NotificationDestination.Email,+ NotificationDestination.Slack+ ],+ [NotificationEvent.ChangeOrderRejected]: [+ NotificationDestination.Email,+ NotificationDestination.Slack+ ],+ [NotificationEvent.ChangeOrderReleased]: [+ NotificationDestination.Email,+ NotificationDestination.Slack+ ],+ [NotificationEvent.ChangeOrderSubmittedForReview]: [+ NotificationDestination.Email,+ NotificationDestination.Slack+ ],[NotificationEvent.DigitalQuoteResponse]: [NotificationDestination.Email,NotificationDestination.Slackdiff --git a/packages/kv/src/ratelimit/ratelimit.ts b/packages/kv/src/ratelimit/ratelimit.tsindex 1d80538dc4..bb0d465c17 100644--- a/packages/kv/src/ratelimit/ratelimit.ts+++ b/packages/kv/src/ratelimit/ratelimit.ts@@ -134,12 +134,21 @@ export class Ratelimit {throw new Error("Unexpected reset value of 0");}+ // Wait until the window resets (or the deadline), then retry. A window+ // boundary already having passed (wait <= 0) is a reason to retry+ // immediately, not to give up — only the deadline ends the loop. The+ // previous `wait <= 0` early-return made this flaky under real timers:+ // for the sliding window `reset` is the end of the current window, so if+ // time crossed that boundary between `limit()` and here, `wait` went+ // negative and we bailed with `success: false` after a single attempt.const wait = Math.min(res.reset, deadline) - Date.now();- if (wait <= 0 || Date.now() >= deadline) {- return res;+ if (wait > 0) {+ await new Promise((r) => setTimeout(r, wait));}- await new Promise((r) => setTimeout(r, wait));+ if (Date.now() >= deadline) {+ return res;+ }}}diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 45c3335b84..3568d5319d 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -38,6 +38,10 @@ msgstr "„{taskName}\" ist erledigt – alle {0} seiner Setup-Map-Elemente sindmsgid "(excluded for this customer)"msgstr "(für diesen Kunden ausgeschlossen)"+#. placeholder {0}: open.length+msgid "{0, plural, one {This part is on 1 open change order} other {This part is on # open change orders}}"+msgstr "{0, plural, one {Dieses Teil befindet sich in 1 offener Änderungsanweisung} other {Dieses Teil befindet sich in # offenen Änderungsanweisungen}}"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} Kunden mit einem Saldo"@@ -211,6 +215,9 @@ msgstr "90 Tage"msgid "A Carbon-run data migration — you load your own data"msgstr "Eine von Carbon durchgeführte Datenmigration – Sie laden Ihre eigenen Daten"+msgid "A change order tracks a controlled engineering or manufacturing change through review and implementation."+msgstr "Eine Änderungsanweisung verfolgt eine kontrollierte technische oder Fertigungsänderung durch Überprüfung und Umsetzung."+msgid "A clearing account holding the value of goods received but not yet billed; the supplier invoice clears it."msgstr "Ein Clearingkonto, das den Wert der erhaltenen, aber noch nicht in Rechnung gestellten Waren hält; die Lieferantenrechnung gleicht es aus."@@ -502,6 +509,9 @@ msgstr "Anschaffungskosten"msgid "Acquisition Date"msgstr "Anschaffungsdatum"+msgid "Action"+msgstr "Aktion"+msgid "Action Status"msgstr "Aktionsstatus"@@ -592,6 +602,9 @@ msgstr "Aktionen hinzufügen"msgid "Add Adjustment"msgstr "Anpassung hinzufügen"+msgid "Add Affected Item"+msgstr "Betroffenes Element hinzufügen"+msgid "Add any notes about your decision..."msgstr "Fügen Sie Notizen zu Ihrer Entscheidung hinzu..."@@ -670,9 +683,6 @@ msgstr "Frage hinzufügen"msgid "Add Receipt"msgstr "Beleg hinzufügen"-msgid "Add Required Actions"-msgstr "Erforderliche Aktionen hinzufügen"-msgid "Add Requirement"msgstr "Anforderung hinzufügen"@@ -719,6 +729,9 @@ msgstr "Add-On"msgid "Add-On Cost"msgstr "Add-On-Kosten"+msgid "Added"+msgstr "Hinzugefügt"+msgid "Added for this customer"msgstr "Für diesen Kunden hinzugefügt"@@ -737,9 +750,15 @@ msgstr "Adresszeile 2"msgid "Adjustment Type"msgstr "Anpassungstyp"+msgid "Advance to {nextStatus}"+msgstr "Zu {nextStatus} übergehen"+msgid "Advanced"msgstr "Erweitert"+msgid "Affected item not found."+msgstr "Betroffenes Element nicht gefunden."+msgid "After"msgstr "Nach"@@ -846,6 +865,9 @@ msgstr "Ein Buchhaltungsdatensatz für einen aktivierten Gegenstand, den Sie absmsgid "An asset's acquisition cost minus accumulated depreciation — what it's still worth on the books, and the figure it's disposed at."msgstr "Die Anschaffungskosten eines Vermögenswertes minus kumulierte Abschreibung — was es auf dem Bücher noch wert ist und der Betrag, zu dem es entsorgt wird."+msgid "An engineering change: the affected items whose methods are revised on a draft and released together, superseding the versions they replace."+msgstr "Eine technische Änderung: die betroffenen Elemente, deren Methoden in einem Entwurf überarbeitet und zusammen freigegeben werden, und dabei die Versionen ersetzen, die sie ersetzen."+msgid "An integration or a custom change — the small slice that's actually custom."msgstr "Eine Integration oder eine benutzerdefinierte Änderung — der kleine Teil, der tatsächlich benutzerdefiniert ist."@@ -1033,6 +1055,10 @@ msgstr "Sind Sie sicher, dass Sie den Prozess aktivieren möchten: {name}? Er wimsgid "Are you sure you want to activate this gauge?."msgstr "Sind Sie sicher, dass Sie dieses Messinstrument aktivieren möchten?."+#. placeholder {0}: routeData?.changeOrder?.changeOrderId ?? ""+msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."+msgstr "Sind Sie sicher, dass Sie {0} stornieren möchten? Es wird geschlossen und schreibgeschützt, bis Sie es erneut öffnen."+#. placeholder {0}: routeData?.rfqSummary ?.rfqId!msgid "Are you sure you want to cancel {0}? This will also cancel all related supplier quotes."msgstr "Sind Sie sicher, dass Sie {0} stornieren möchten? Dies storniert auch alle zugehörigen Lieferantenofferten."@@ -1123,6 +1149,14 @@ msgstr "Sind Sie sicher, dass Sie das Konto löschen möchten: {0}{1}? Dies kannmsgid "Are you sure you want to delete the API key: {0}? This cannot be undone."msgstr "Sind Sie sicher, dass Sie den API-Schlüssel: {0}? löschen möchten? Dies kann nicht rückgängig gemacht werden."+#. placeholder {0}: requiredAction.name+msgid "Are you sure you want to delete the change order action: {0}? This cannot be undone."+msgstr "Sind Sie sicher, dass Sie die Änderungsauftragsmaßnahme löschen möchten: {0}? Dies kann nicht rückgängig gemacht werden."++#. placeholder {0}: changeOrderType.name+msgid "Are you sure you want to delete the change order category: {0}? This cannot be undone."+msgstr "Möchten Sie die Änderungsanweisungskategorie wirklich löschen: {0}? Dies kann nicht rückgängig gemacht werden."+msgid "Are you sure you want to delete the contractor: {name}? This cannot be undone."msgstr "Sind Sie sicher, dass Sie den Auftragnehmer: {name} löschen möchten? Dies kann nicht rückgängig gemacht werden."@@ -1281,6 +1315,9 @@ msgstr "Sind Sie sicher, dass Sie den Webhook löschen möchten: {0}? Dies kannmsgid "Are you sure you want to delete this approval rule? This cannot be undone."msgstr "Sind Sie sicher, dass Sie diese Genehmigungsregel löschen möchten? Dies kann nicht rückgängig gemacht werden."+msgid "Are you sure you want to delete this change order?"+msgstr "Möchten Sie diese Änderungsanweisung wirklich löschen?"+msgid "Are you sure you want to delete this gauge?"msgstr "Sind Sie sicher, dass Sie dieses Messinstrument löschen möchten?"@@ -1893,6 +1930,12 @@ msgstr "Diese Datei kann nicht heruntergeladen werden"msgid "Cancel"msgstr "Abbrechen"+msgid "Cancel change order"+msgstr "Änderungsauftrag stornieren"++msgid "Cancel Change Order"+msgstr "Änderungsauftrag stornieren"+msgid "Cancel Job"msgstr "Auftrag abbrechen"@@ -2055,12 +2098,30 @@ msgstr "Fachleute"msgid "Change"msgstr "Ändern"+msgid "Change order"+msgstr "Änderungsauftrag"++msgid "Change Order"+msgstr "Änderungsanweisung"++msgid "Change Order Actions"+msgstr "Änderungsauftragsmaßnahmen"++msgid "Change Order Types"+msgstr "Änderungsanweisungstypen"++msgid "Change Orders"+msgstr "Änderungsanweisungen"+msgid "Change status"msgstr "Status ändern"msgid "Change the item type (e.g. Part, Material, Tool, etc.)"msgstr "Ändern Sie den Elementtyp (z. B. Teil, Material, Werkzeug usw.)"+msgid "Change type"+msgstr "Typ ändern"+msgid "Change Type"msgstr "Typ ändern"@@ -2076,6 +2137,9 @@ msgstr "Dies wird die vorhandene Methode überschreiben"msgid "Changing this will update the part ID"msgstr "Das Ändern aktualisiert die Teile-ID"+msgid "Changing type resets this item's draft edits."+msgstr "Das Ändern des Typs setzt die Entwurfsbearbeitungen dieses Elements zurück."+msgid "Chart of accounts"msgstr "Kontenplan"@@ -2411,6 +2475,9 @@ msgstr "Bestätigen"msgid "Confirm {0}"msgstr "Bestätigen {0}"+msgid "Confirm & release"+msgstr "Bestätigen & Freigeben"+msgid "Confirm and sign the scope"msgstr "Umfang bestätigen und unterzeichnen"@@ -2549,6 +2616,9 @@ msgstr "Controller, Buchhalter"msgid "Controls how planning handles a discontinued item: Consume First exhausts on-hand before switching to the successor, Prefer New redirects new demand to the successor immediately, Stock Only keeps only a minimum service reserve, and No Stock drops the item from planning entirely."msgstr "Steuert, wie die Planung ein eingestelltes Artikel handhabt: Consume First erschöpft den Bestand, bevor zur Nachfolgeposition gewechselt wird, Prefer New leitet neue Nachfrage sofort zur Nachfolgeposition um, Stock Only behält nur einen minimalen Servicebestand, und No Stock entfernt den Artikel vollständig aus der Planung."+msgid "Controls whether the bill of material and bill of process of a released (Production) revision can be edited outside a change order."+msgstr "Steuert, ob die Stückliste und die Prozeßliste einer freigegebenen (Produktions-)Version außerhalb einer Änderungsanweisung bearbeitet werden können."+msgid "Convention"msgstr "Konvention"@@ -2630,6 +2700,9 @@ msgstr "Job-Nummer kopieren"msgid "Copy link"msgstr "Link kopieren"+msgid "Copy link to change order"+msgstr "Link zur Änderungsanweisung kopieren"+msgid "Copy link to consumable"msgstr "Link zum Verbrauchsmaterial kopieren"@@ -2848,6 +2921,9 @@ msgstr "Erstelle {0} Werte"msgid "Create & Snapshot"msgstr "Erstellen & Snapshot"+msgid "Create a change order for the new revision and open it"+msgstr "Erstellen Sie einen Änderungsauftrag für die neue Überarbeitung und öffnen Sie ihn"+msgid "Create a new kanban card for scan-based replenishment."msgstr "Erstellen Sie eine neue Kanban-Karte für scan-basierte Nachschubversorgung."@@ -2875,6 +2951,9 @@ msgstr "Bestellungen erstellen und genehmigen"msgid "Create audit trail entries"msgstr "Audit-Trail-Einträge erstellen"+msgid "Create Change Order"+msgstr "Änderungsanweisung erstellen"+msgid "Create Issue"msgstr "Problem erstellen"@@ -2932,6 +3011,12 @@ msgstr "Erstellt am"msgid "Created By"msgstr "Erstellt von"+msgid "Created change order action"+msgstr "Änderungsauftragsmaßnahme erstellt"++msgid "Created change order type"+msgstr "Änderungsauftragstyp erstellt"+msgid "Created consumable"msgstr "Verbrauchsmaterial erstellt"@@ -3550,6 +3635,12 @@ msgstr "{periodLabel} löschen"msgid "Delete {storageUnitName}"msgstr "Löschen {storageUnitName}"+msgid "Delete action"+msgstr "Aktion löschen"++msgid "Delete Action"+msgstr "Aktion löschen"+msgid "Delete API Key"msgstr "API-Schlüssel löschen"@@ -3565,6 +3656,9 @@ msgstr "Attribut löschen"msgid "Delete Category"msgstr "Kategorie löschen"+msgid "Delete Change Order"+msgstr "Änderungsanweisung löschen"+msgid "Delete Consumable"msgstr "Verbrauchsmaterial löschen"@@ -3794,6 +3888,9 @@ msgstr "Übertragung löschen"msgid "Delete Transfer Line"msgstr "Transferzeile löschen"+msgid "Delete Type"+msgstr "Typ löschen"+msgid "Delete Unit of Measure"msgstr "Maßeinheit löschen"@@ -3884,6 +3981,9 @@ msgstr "Beschreibung"msgid "Description (optional)"msgstr "Beschreibung (optional)"+msgid "Description of Change"+msgstr "Änderungsbeschreibung"+msgid "Description of Issue"msgstr "Problembeschreibung"@@ -3929,6 +4029,9 @@ msgstr "Deaktiviert"msgid "Discard"msgstr "Verwerfen"+msgid "Discontinuation date"+msgstr "Einstellungsdatum"+msgid "Discontinuation Date"msgstr "Einstellungsdatum"@@ -4196,6 +4299,9 @@ msgstr "Bearbeiten <0>Problem</0> Workflow"msgid "Edit Account"msgstr "Konto bearbeiten"+msgid "Edit Action"+msgstr "Aktion bearbeiten"+msgid "Edit API Key"msgstr "API-Schlüssel bearbeiten"@@ -4217,6 +4323,15 @@ msgstr "Attributkategorie bearbeiten"msgid "Edit Category"msgstr "Kategorie bearbeiten"+msgid "Edit Change Order"+msgstr "Änderungsanweisung bearbeiten"++msgid "Edit Change Order Action"+msgstr "Änderungsauftragsmaßnahme bearbeiten"++msgid "Edit Change Order Type"+msgstr "Änderungsauftragstyp bearbeiten"+msgid "Edit column visibility"msgstr "Spaltensichtbarkeit bearbeiten"@@ -4466,6 +4581,9 @@ msgstr "Transfer bearbeiten"msgid "Edit Transfer Line"msgstr "Transferzeile bearbeiten"+msgid "Edit Type"+msgstr "Typ bearbeiten"+msgid "Edit Unit of Measure"msgstr "Maßeinheit bearbeiten"@@ -4583,6 +4701,9 @@ msgstr "Ende des letzten Quartals"msgid "End Time"msgstr "Endzeit"+msgid "Enforce — edits are blocked"+msgstr "Erzwingen — Bearbeitungen sind gesperrt"+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Erzwingen Sie eine Validierung und Richtlinien pro Artikel über Eingänge, Lieferungen, Transfers und Anpassungen hinweg."@@ -6004,6 +6125,9 @@ msgstr "II (normalstandard)"msgid "III (tightened)"msgstr "III (verschärft)"+msgid "Impact"+msgstr "Auswirkung"+msgid "Imperial"msgstr "Imperial"@@ -6551,6 +6675,9 @@ msgstr "Aktuell behalten"msgid "Keep existing pricing, only add new items"msgstr "Behalten Sie bestehende Preise, fügen Sie nur neue Artikel hinzu"+msgid "Keep Open"+msgstr "Offen halten"+msgid "Key"msgstr "Schlüssel"@@ -6655,6 +6782,9 @@ msgstr "Alle zugehörigen Belege unverändert lassen"msgid "Leave blank for built-in"msgstr "Leer lassen für integriert"+msgid "Leave blank to use the next revision automatically"+msgstr "Lassen Sie das Feld leer, um die nächste Revision automatisch zu verwenden"+msgid "Leave empty for exact match"msgstr "Leer lassen für exakte Übereinstimmung"@@ -6750,6 +6880,9 @@ msgstr "Linear-Problem verknüpfen"msgid "Linked entity quantity ({0}) does not match row quantity ({1})."msgstr "Verknüpfte Entitätsmenge ({0}) stimmt nicht mit der Zeilenmenge ({1}) überein."+msgid "Linked NCR"+msgstr "Verknüpfte Nichtkonformität"+msgid "Linked PO"msgstr "Verknüpfte Bestellung"@@ -7352,6 +7485,9 @@ msgstr "Modell aus Auftrag entfernt"msgid "Model removed from line"msgstr "Modell aus Zeile entfernt"+msgid "Modified"+msgstr "Geändert"+msgid "Module"msgstr "Modul"@@ -7501,6 +7637,15 @@ msgstr "Neues Attribut"msgid "New Attribute Category"msgstr "Neue Attributkategorie"+msgid "New Change Order"+msgstr "Neue Änderungsanweisung"++msgid "New Change Order Action"+msgstr "Neue Änderungsauftragsmaßnahme"++msgid "New Change Order Type"+msgstr "Neuer Änderungsauftragstyp"+msgid "New Consumable"msgstr "Neuer Verbrauchsstoff"@@ -7815,6 +7960,12 @@ msgstr "Keine aktiven Angebote"msgid "No addresses found"msgstr "Keine Adressen gefunden"+msgid "No affected items to assess."+msgstr "Keine betroffenen Elemente zu bewerten."++msgid "No affected items."+msgstr "Keine betroffenen Elemente."+msgid "No applications. Payment will be on-account."msgstr "Keine Anwendungen. Zahlung erfolgt auf Kontostand."@@ -7840,6 +7991,9 @@ msgstr "Keine Kalibrierungsdatensätze gefunden"msgid "No changes recorded"msgstr "Keine Änderungen aufgezeichnet"+msgid "No changes yet."+msgstr "Noch keine Änderungen."+msgid "No comments yet. Be the first to add a comment."msgstr "Noch keine Kommentare. Seien Sie der Erste, der einen Kommentar hinzufügt."@@ -7867,12 +8021,18 @@ msgstr "Keine Tage frei geplant"msgid "No default attachments yet."msgstr "Noch keine Standardanhänge vorhanden."+msgid "No draft make method for this item yet."+msgstr "Noch keine Entwurfsmethode für dieses Element."+msgid "No draft versions available"msgstr "Keine Entwurfsversionen verfügbar"msgid "No due date"msgstr "Kein Fälligkeitsdatum"+msgid "No editable properties for this item."+msgstr "Keine bearbeitbaren Eigenschaften für dieses Element."+msgid "No employees assigned yet. Add groups to see status."msgstr "Noch keine Mitarbeiter zugewiesen. Fügen Sie Gruppen hinzu, um den Status anzuzeigen."@@ -7897,6 +8057,9 @@ msgstr "Keine Felder gefunden."msgid "No files"msgstr "Keine Dateien"+msgid "No files for this item."+msgstr "Keine Dateien für dieses Element."+msgid "No files uploaded"msgstr "Keine Dateien hochgeladen"@@ -7933,6 +8096,9 @@ msgstr "Keine Übereinstimmungen"msgid "No matches for \"{query}\". Try a different search term."msgstr "Keine Übereinstimmungen für \"{query}\". Versuchen Sie einen anderen Suchbegriff."+msgid "No matches. Type to create one."+msgstr "Keine Übereinstimmungen. Geben Sie ein, um eine zu erstellen."+msgid "No new notifications"msgstr "Keine neuen Benachrichtigungen"@@ -8098,6 +8264,9 @@ msgstr "Nicht eine Tabelle, sondern ein Hauptbuch-Saldo: Kosten sammeln sich, wemsgid "Not enough jobs to cover quantity"msgstr "Nicht genug Aufträge zur Deckung der Menge"+msgid "Not referenced anywhere yet."+msgstr "Noch nirgendwo referenziert."+msgid "Not Required"msgstr "Nicht erforderlich"@@ -8149,6 +8318,9 @@ msgstr "OEM (Original Equipment Manufacturer)"msgid "of"msgstr "von"+msgid "Off — released revisions stay editable"+msgstr "Aus — veröffentlichte Versionen bleiben bearbeitbar"+msgid "OK"msgstr "OK"@@ -8236,6 +8408,9 @@ msgstr "Oops! Der Link, auf den Sie zugreifen möchten, ist ungültig."msgid "Open"msgstr "Öffnen"+msgid "Open a change order"+msgstr "Öffnen Sie einen Änderungsauftrag"+msgid "Open Actions"msgstr "Offene Maßnahmen"@@ -8251,6 +8426,9 @@ msgstr "Offene Forderungen"msgid "Open Audit Log"msgstr "Audit-Protokoll öffnen"+msgid "Open change orders affecting this part"+msgstr "Offene Änderungsanweisungen, die diesen Teil betreffen"+msgid "Open Date"msgstr "Öffnungsdatum"@@ -8504,6 +8682,9 @@ msgstr "Überschreiben Sie die Angebotsmethode mit der Quellmethode"msgid "Overwrite the target manufacturing method with the quote method"msgstr "Überschreiben Sie die Zielfertigungsmethode mit der Angebotsmethode"+msgid "Owner"+msgstr "Besitzer"+msgid "Owner (cost center)"msgstr "Übergeordnete Kostenstelle"@@ -8568,6 +8749,12 @@ msgstr "Teile-ID"msgid "Part is configured for manufacturing"msgstr "Teil ist für die Herstellung konfiguriert"+msgid "Part Number"+msgstr "Teilenummer"++msgid "Part Supersession"+msgstr "Teilersatz"+msgid "Partial"msgstr "Teilweise"@@ -9531,6 +9718,9 @@ msgstr "Grund"msgid "Reason Account"msgstr "Grund-Konto"+msgid "Reason for Change"+msgstr "Grund für Änderung"+msgid "Reason for declining (Optional)"msgstr "Grund für Ablehnung (Optional)"@@ -9733,12 +9923,27 @@ msgstr "Relative Zeitleiste · Daten müssen noch bestätigt werden"msgid "Release"msgstr "Freigabe"+msgid "Release change order"+msgstr "Änderungsauftrag freigeben"++msgid "Release control"+msgstr "Freigabekontrolle"++msgid "Release Control"+msgstr "Freigabekontrolle"+msgid "Release Job"msgstr "Auftrag freigeben"msgid "Released"msgstr "Freigegeben"+msgid "Released revision"+msgstr "Freigegebene Version"++msgid "Released revision is locked"+msgstr "Freigegebene Version ist gesperrt"+msgid "Remaining"msgstr "Verbleibend"@@ -9785,6 +9990,9 @@ msgstr "Sortierung nach Spalte entfernen"msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."msgstr "Entfernen Sie diesen Speichertyp aus allen referenzierenden Speichereinheiten und löschen Sie ihn. Dies kann nicht rückgängig gemacht werden."+msgid "Removed"+msgstr "Entfernt"+msgid "Rendering label preview..."msgstr "Label-Vorschau wird gerendert..."@@ -10006,6 +10214,9 @@ msgstr "Umkehrbuchung Umsatzsteuer (Standard)"msgid "Reverse the related journal entries"msgstr "Kehren Sie die zugehörigen Journaleinträge um"+msgid "Review each item's changes, then confirm — releasing can't be undone."+msgstr "Überprüfen Sie die Änderungen jedes Elements, und bestätigen Sie dann – die Freigabe kann nicht rückgängig gemacht werden."+msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Überprüfen Sie die Bilanz und die Gewinn- und Verlustrechnung der Periode und bestätigen Sie, dass die Zahlen korrekt aussehen. Dies ist eine manuelle Genehmigung – markieren Sie sie als erledigt, sobald Sie diese überprüft haben."@@ -10019,6 +10230,9 @@ msgstr "Revision"msgid "Revision {0}"msgstr "Revision {0}"+msgid "Revisions"+msgstr "Versionen"+msgid "Revoke"msgstr "Widerrufen"@@ -11361,6 +11575,9 @@ msgstr "Angebot erfolgreich kopiert"msgid "Successfully created a new revision"msgstr "Neue Revision erfolgreich erstellt"+msgid "Successor effectivity"+msgstr "Nachfolger-Effektivität"+msgid "Successor Effectivity Date"msgstr "Nachfolger-Effektivitätsdatum"@@ -12432,6 +12649,9 @@ msgstr "Diese Informationen werden in Dokumentkopfzeilen verwendet"msgid "This information will be visible to all users, so be careful what you share."msgstr "Diese Informationen sind für alle Benutzer sichtbar, daher seien Sie vorsichtig, was Sie teilen."+msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."+msgstr "Dies ist ein gekauftes Element – es hat keine Stückliste/Arbeitspläne; nur seine Attribute und Dokumente können sich ändern."+msgid "This is a unique identifier for the webhook"msgstr "Dies ist eine eindeutige Kennung für den Webhook"@@ -12489,6 +12709,12 @@ msgstr "Diese Periode hat keine Journaleinträge und kann dauerhaft gelöscht wemsgid "This Quarter"msgstr "Dieses Quartal"+msgid "This revision is released (Production). Changes should normally flow through a change order."+msgstr "Diese Überarbeitung ist freigegeben (Produktion). Änderungen sollten normalerweise durch eine Änderungsanforderung fließen."++msgid "This revision is released (Production). Open a change order to modify it."+msgstr "Diese Überarbeitung ist freigegeben (Produktion). Öffnen Sie eine Änderungsanforderung, um sie zu ändern."+msgid "This sales order has associated jobs. Choose what to do with them."msgstr "Diese Bestellung hat zugeordnete Aufträge. Wählen Sie, was damit geschehen soll."@@ -12531,6 +12757,9 @@ msgstr "Dies ersetzt alle Methodenmaterialien anderer Revisionen durch diese Revmsgid "This will replace all method materials of other sizes with this size."msgstr "Dies ersetzt alle Methodenmaterialien anderer Größen durch diese Größe."+msgid "This will set the current version of the make method to Active, making it read-only."+msgstr "Dadurch wird die aktuelle Version der Herstellungsmethode auf Aktiv gesetzt und schreibgeschützt."+msgid "This will write off the remaining book value of the asset."msgstr "Dies schreibt den verbleibenden Buchwert des Vermögenswerts ab."@@ -13493,6 +13722,9 @@ msgstr "Lager, Betrieb"msgid "Warn"msgstr "Warnung"+msgid "Warn — edits succeed with a warning"+msgstr "Warnung — Änderungen werden mit einer Warnung erfolgreich durchgeführt"+msgid "Warn but allow"msgstr "Warnen, aber zulassen"@@ -13624,6 +13856,9 @@ msgstr "{translatedTerm} ist was?"msgid "What it is"msgstr "Was es ist"+msgid "What kind of change this is: Version updates how the part is made, Revision edits its details and documents, and New Part replaces it with a new part number."+msgstr "Was für eine Änderung dies ist: Versionen aktualisieren, wie das Teil hergestellt wird, Revisionen bearbeiten seine Details und Dokumente, und ein neues Teil ersetzt es durch eine neue Teilenummer."+msgid "What kind of output this entry records — Production (good units), Scrap (unrecoverable), or Rework (sent back for correction); reveals Scrap Reason when Scrap."msgstr "Welche Art von Ausgabe dieser Eintrag aufzeichnet — Produktion (gute Einheiten), Ausschuss (nicht behebbar) oder Nacharbeiten (zur Korrektur zurückgesendet); zeigt Ausschussgrund an, wenn Ausschuss."@@ -13783,6 +14018,9 @@ msgstr "Wo neuer Bestand dieses Artikels standardmäßig beim Empfang landet; Prmsgid "Where stock lives and how it ships."msgstr "Wo Bestände lagern und wie sie versendet werden."+msgid "Where the affected items are used across the system. Informational — nothing here blocks releasing."+msgstr "Wo die betroffenen Elemente im System verwendet werden. Informativ – nichts hier blockiert die Freigabe."+msgid "Where this entry originated (manual entry, posting from sales/purchasing, recurring template, etc.)."msgstr "Woher dieser Eintrag stammt (manueller Eintrag, Buchung aus Verkauf/Einkauf, wiederkehrende Vorlage usw.)."@@ -14067,6 +14305,9 @@ msgstr "Du bist seit {hoursElapsed} Stunden angemeldet. Hast du vergessen, dichmsgid "Your books and how money flows."msgstr "Ihre Bücher und wie Geld fließt."+msgid "Your changes go into a new draft version released with this change order."+msgstr "Ihre Änderungen werden in eine neue Entwurfsversion aufgenommen, die mit dieser Änderungsorder freigegeben wird."+msgid "Your Console PIN"msgstr "Ihre Konsolen-PIN"diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.poindex a4061c87f0..3954ebd806 100644--- a/packages/locale/locales/de/mes.po+++ b/packages/locale/locales/de/mes.po@@ -610,6 +610,9 @@ msgstr "Keine Auswirkung"msgid "No maintenance scheduled for today"msgstr "Keine Instandhaltung für heute geplant"+msgid "No matches. Type to create one."+msgstr "Keine Übereinstimmungen. Geben Sie etwas ein, um einen zu erstellen."+msgid "No materials"msgstr "Keine Materialien"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 681fca465a..fc8065cc0c 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -38,6 +38,10 @@ msgstr "\"{taskName}\" is done — all {0} of its Setup Map items are configuredmsgid "(excluded for this customer)"msgstr "(excluded for this customer)"+#. placeholder {0}: open.length+msgid "{0, plural, one {This part is on 1 open change order} other {This part is on # open change orders}}"+msgstr "{0, plural, one {This part is on 1 open change order} other {This part is on # open change orders}}"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} customers with a balance"@@ -211,6 +215,9 @@ msgstr "90D"msgid "A Carbon-run data migration — you load your own data"msgstr "A Carbon-run data migration — you load your own data"+msgid "A change order tracks a controlled engineering or manufacturing change through review and implementation."+msgstr "A change order tracks a controlled engineering or manufacturing change through review and implementation."+msgid "A clearing account holding the value of goods received but not yet billed; the supplier invoice clears it."msgstr "A clearing account holding the value of goods received but not yet billed; the supplier invoice clears it."@@ -502,6 +509,9 @@ msgstr "Acquisition Cost"msgid "Acquisition Date"msgstr "Acquisition Date"+msgid "Action"+msgstr "Action"+msgid "Action Status"msgstr "Action Status"@@ -592,6 +602,9 @@ msgstr "Add Actions"msgid "Add Adjustment"msgstr "Add Adjustment"+msgid "Add Affected Item"+msgstr "Add Affected Item"+msgid "Add any notes about your decision..."msgstr "Add any notes about your decision..."@@ -670,9 +683,6 @@ msgstr "Add Question"msgid "Add Receipt"msgstr "Add Receipt"-msgid "Add Required Actions"-msgstr "Add Required Actions"-msgid "Add Requirement"msgstr "Add Requirement"@@ -719,6 +729,9 @@ msgstr "Add-On"msgid "Add-On Cost"msgstr "Add-On Cost"+msgid "Added"+msgstr "Added"+msgid "Added for this customer"msgstr "Added for this customer"@@ -737,9 +750,15 @@ msgstr "Address Line 2"msgid "Adjustment Type"msgstr "Adjustment Type"+msgid "Advance to {nextStatus}"+msgstr "Advance to {nextStatus}"+msgid "Advanced"msgstr "Advanced"+msgid "Affected item not found."+msgstr "Affected item not found."+msgid "After"msgstr "After"@@ -846,6 +865,9 @@ msgstr "An accounting record for a capitalized item you depreciate rather than emsgid "An asset's acquisition cost minus accumulated depreciation — what it's still worth on the books, and the figure it's disposed at."msgstr "An asset's acquisition cost minus accumulated depreciation — what it's still worth on the books, and the figure it's disposed at."+msgid "An engineering change: the affected items whose methods are revised on a draft and released together, superseding the versions they replace."+msgstr "An engineering change: the affected items whose methods are revised on a draft and released together, superseding the versions they replace."+msgid "An integration or a custom change — the small slice that's actually custom."msgstr "An integration or a custom change — the small slice that's actually custom."@@ -1033,6 +1055,10 @@ msgstr "Are you sure you want to activate the process: {name}? It will appear inmsgid "Are you sure you want to activate this gauge?."msgstr "Are you sure you want to activate this gauge?."+#. placeholder {0}: routeData?.changeOrder?.changeOrderId ?? ""+msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."+msgstr "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."+#. placeholder {0}: routeData?.rfqSummary ?.rfqId!msgid "Are you sure you want to cancel {0}? This will also cancel all related supplier quotes."msgstr "Are you sure you want to cancel {0}? This will also cancel all related supplier quotes."@@ -1123,6 +1149,14 @@ msgstr "Are you sure you want to delete the account: {0}{1}? This cannot be undomsgid "Are you sure you want to delete the API key: {0}? This cannot be undone."msgstr "Are you sure you want to delete the API key: {0}? This cannot be undone."+#. placeholder {0}: requiredAction.name+msgid "Are you sure you want to delete the change order action: {0}? This cannot be undone."+msgstr "Are you sure you want to delete the change order action: {0}? This cannot be undone."++#. placeholder {0}: changeOrderType.name+msgid "Are you sure you want to delete the change order category: {0}? This cannot be undone."+msgstr "Are you sure you want to delete the change order category: {0}? This cannot be undone."+msgid "Are you sure you want to delete the contractor: {name}? This cannot be undone."msgstr "Are you sure you want to delete the contractor: {name}? This cannot be undone."@@ -1281,6 +1315,9 @@ msgstr "Are you sure you want to delete the webhook: {0}? This cannot be undone.msgid "Are you sure you want to delete this approval rule? This cannot be undone."msgstr "Are you sure you want to delete this approval rule? This cannot be undone."+msgid "Are you sure you want to delete this change order?"+msgstr "Are you sure you want to delete this change order?"+msgid "Are you sure you want to delete this gauge?"msgstr "Are you sure you want to delete this gauge?"@@ -1893,6 +1930,12 @@ msgstr "Can't download this file"msgid "Cancel"msgstr "Cancel"+msgid "Cancel change order"+msgstr "Cancel change order"++msgid "Cancel Change Order"+msgstr "Cancel Change Order"+msgid "Cancel Job"msgstr "Cancel Job"@@ -2055,12 +2098,30 @@ msgstr "Champions"msgid "Change"msgstr "Change"+msgid "Change order"+msgstr "Change order"++msgid "Change Order"+msgstr "Change Order"++msgid "Change Order Actions"+msgstr "Change Order Actions"++msgid "Change Order Types"+msgstr "Change Order Types"++msgid "Change Orders"+msgstr "Change Orders"+msgid "Change status"msgstr "Change status"msgid "Change the item type (e.g. Part, Material, Tool, etc.)"msgstr "Change the item type (e.g. Part, Material, Tool, etc.)"+msgid "Change type"+msgstr "Change type"+msgid "Change Type"msgstr "Change Type"@@ -2076,6 +2137,9 @@ msgstr "Changing this will overwrite the existing method"msgid "Changing this will update the part ID"msgstr "Changing this will update the part ID"+msgid "Changing type resets this item's draft edits."+msgstr "Changing type resets this item's draft edits."+msgid "Chart of accounts"msgstr "Chart of accounts"@@ -2411,6 +2475,9 @@ msgstr "Confirm"msgid "Confirm {0}"msgstr "Confirm {0}"+msgid "Confirm & release"+msgstr "Confirm & release"+msgid "Confirm and sign the scope"msgstr "Confirm and sign the scope"@@ -2549,6 +2616,9 @@ msgstr "Controller, Accountant"msgid "Controls how planning handles a discontinued item: Consume First exhausts on-hand before switching to the successor, Prefer New redirects new demand to the successor immediately, Stock Only keeps only a minimum service reserve, and No Stock drops the item from planning entirely."msgstr "Controls how planning handles a discontinued item: Consume First exhausts on-hand before switching to the successor, Prefer New redirects new demand to the successor immediately, Stock Only keeps only a minimum service reserve, and No Stock drops the item from planning entirely."+msgid "Controls whether the bill of material and bill of process of a released (Production) revision can be edited outside a change order."+msgstr "Controls whether the bill of material and bill of process of a released (Production) revision can be edited outside a change order."+msgid "Convention"msgstr "Convention"@@ -2630,6 +2700,9 @@ msgstr "Copy Job number"msgid "Copy link"msgstr "Copy link"+msgid "Copy link to change order"+msgstr "Copy link to change order"+msgid "Copy link to consumable"msgstr "Copy link to consumable"@@ -2848,6 +2921,9 @@ msgstr "Create {0} values"msgid "Create & Snapshot"msgstr "Create & Snapshot"+msgid "Create a change order for the new revision and open it"+msgstr "Create a change order for the new revision and open it"+msgid "Create a new kanban card for scan-based replenishment."msgstr "Create a new kanban card for scan-based replenishment."@@ -2875,6 +2951,9 @@ msgstr "Create and approve purchase orders"msgid "Create audit trail entries"msgstr "Create audit trail entries"+msgid "Create Change Order"+msgstr "Create Change Order"+msgid "Create Issue"msgstr "Create Issue"@@ -2932,6 +3011,12 @@ msgstr "Created At"msgid "Created By"msgstr "Created By"+msgid "Created change order action"+msgstr "Created change order action"++msgid "Created change order type"+msgstr "Created change order type"+msgid "Created consumable"msgstr "Created consumable"@@ -3550,6 +3635,12 @@ msgstr "Delete {periodLabel}"msgid "Delete {storageUnitName}"msgstr "Delete {storageUnitName}"+msgid "Delete action"+msgstr "Delete action"++msgid "Delete Action"+msgstr "Delete Action"+msgid "Delete API Key"msgstr "Delete API Key"@@ -3565,6 +3656,9 @@ msgstr "Delete Attribute"msgid "Delete Category"msgstr "Delete Category"+msgid "Delete Change Order"+msgstr "Delete Change Order"+msgid "Delete Consumable"msgstr "Delete Consumable"@@ -3794,6 +3888,9 @@ msgstr "Delete Transfer"msgid "Delete Transfer Line"msgstr "Delete Transfer Line"+msgid "Delete Type"+msgstr "Delete Type"+msgid "Delete Unit of Measure"msgstr "Delete Unit of Measure"@@ -3884,6 +3981,9 @@ msgstr "Description"msgid "Description (optional)"msgstr "Description (optional)"+msgid "Description of Change"+msgstr "Description of Change"+msgid "Description of Issue"msgstr "Description of Issue"@@ -3929,6 +4029,9 @@ msgstr "Disabled"msgid "Discard"msgstr "Discard"+msgid "Discontinuation date"+msgstr "Discontinuation date"+msgid "Discontinuation Date"msgstr "Discontinuation Date"@@ -4196,6 +4299,9 @@ msgstr "Edit <0>Issue</0> Workflow"msgid "Edit Account"msgstr "Edit Account"+msgid "Edit Action"+msgstr "Edit Action"+msgid "Edit API Key"msgstr "Edit API Key"@@ -4217,6 +4323,15 @@ msgstr "Edit Attribute Category"msgid "Edit Category"msgstr "Edit Category"+msgid "Edit Change Order"+msgstr "Edit Change Order"++msgid "Edit Change Order Action"+msgstr "Edit Change Order Action"++msgid "Edit Change Order Type"+msgstr "Edit Change Order Type"+msgid "Edit column visibility"msgstr "Edit column visibility"@@ -4466,6 +4581,9 @@ msgstr "Edit Transfer"msgid "Edit Transfer Line"msgstr "Edit Transfer Line"+msgid "Edit Type"+msgstr "Edit Type"+msgid "Edit Unit of Measure"msgstr "Edit Unit of Measure"@@ -4583,6 +4701,9 @@ msgstr "End of Last Quarter"msgid "End Time"msgstr "End Time"+msgid "Enforce — edits are blocked"+msgstr "Enforce — edits are blocked"+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."@@ -6004,6 +6125,9 @@ msgstr "II (normal default)"msgid "III (tightened)"msgstr "III (tightened)"+msgid "Impact"+msgstr "Impact"+msgid "Imperial"msgstr "Imperial"@@ -6551,6 +6675,9 @@ msgstr "Keep Current"msgid "Keep existing pricing, only add new items"msgstr "Keep existing pricing, only add new items"+msgid "Keep Open"+msgstr "Keep Open"+msgid "Key"msgstr "Key"@@ -6655,6 +6782,9 @@ msgstr "Leave any related receipts untouched"msgid "Leave blank for built-in"msgstr "Leave blank for built-in"+msgid "Leave blank to use the next revision automatically"+msgstr "Leave blank to use the next revision automatically"+msgid "Leave empty for exact match"msgstr "Leave empty for exact match"@@ -6750,6 +6880,9 @@ msgstr "Link Linear Issue"msgid "Linked entity quantity ({0}) does not match row quantity ({1})."msgstr "Linked entity quantity ({0}) does not match row quantity ({1})."+msgid "Linked NCR"+msgstr "Linked NCR"+msgid "Linked PO"msgstr "Linked PO"@@ -7352,6 +7485,9 @@ msgstr "Model removed from job"msgid "Model removed from line"msgstr "Model removed from line"+msgid "Modified"+msgstr "Modified"+msgid "Module"msgstr "Module"@@ -7501,6 +7637,15 @@ msgstr "New Attribute"msgid "New Attribute Category"msgstr "New Attribute Category"+msgid "New Change Order"+msgstr "New Change Order"++msgid "New Change Order Action"+msgstr "New Change Order Action"++msgid "New Change Order Type"+msgstr "New Change Order Type"+msgid "New Consumable"msgstr "New Consumable"@@ -7815,6 +7960,12 @@ msgstr "No Active Quotes"msgid "No addresses found"msgstr "No addresses found"+msgid "No affected items to assess."+msgstr "No affected items to assess."++msgid "No affected items."+msgstr "No affected items."+msgid "No applications. Payment will be on-account."msgstr "No applications. Payment will be on-account."@@ -7840,6 +7991,9 @@ msgstr "No calibration records found"msgid "No changes recorded"msgstr "No changes recorded"+msgid "No changes yet."+msgstr "No changes yet."+msgid "No comments yet. Be the first to add a comment."msgstr "No comments yet. Be the first to add a comment."@@ -7867,12 +8021,18 @@ msgstr "No days off scheduled"msgid "No default attachments yet."msgstr "No default attachments yet."+msgid "No draft make method for this item yet."+msgstr "No draft make method for this item yet."+msgid "No draft versions available"msgstr "No draft versions available"msgid "No due date"msgstr "No due date"+msgid "No editable properties for this item."+msgstr "No editable properties for this item."+msgid "No employees assigned yet. Add groups to see status."msgstr "No employees assigned yet. Add groups to see status."@@ -7897,6 +8057,9 @@ msgstr "No fields found."msgid "No files"msgstr "No files"+msgid "No files for this item."+msgstr "No files for this item."+msgid "No files uploaded"msgstr "No files uploaded"@@ -7933,6 +8096,9 @@ msgstr "No matches"msgid "No matches for \"{query}\". Try a different search term."msgstr "No matches for \"{query}\". Try a different search term."+msgid "No matches. Type to create one."+msgstr "No matches. Type to create one."+msgid "No new notifications"msgstr "No new notifications"@@ -8098,6 +8264,9 @@ msgstr "Not a table but a general-ledger balance: cost accumulates as job materimsgid "Not enough jobs to cover quantity"msgstr "Not enough jobs to cover quantity"+msgid "Not referenced anywhere yet."+msgstr "Not referenced anywhere yet."+msgid "Not Required"msgstr "Not Required"@@ -8149,6 +8318,9 @@ msgstr "OEM (original equipment manufacturer)"msgid "of"msgstr "of"+msgid "Off — released revisions stay editable"+msgstr "Off — released revisions stay editable"+msgid "OK"msgstr "OK"@@ -8236,6 +8408,9 @@ msgstr "Oops! The link you're trying to access is not valid."msgid "Open"msgstr "Open"+msgid "Open a change order"+msgstr "Open a change order"+msgid "Open Actions"msgstr "Open Actions"@@ -8251,6 +8426,9 @@ msgstr "Open AR"msgid "Open Audit Log"msgstr "Open Audit Log"+msgid "Open change orders affecting this part"+msgstr "Open change orders affecting this part"+msgid "Open Date"msgstr "Open Date"@@ -8504,6 +8682,9 @@ msgstr "Overwrite the quote method with the source method"msgid "Overwrite the target manufacturing method with the quote method"msgstr "Overwrite the target manufacturing method with the quote method"+msgid "Owner"+msgstr "Owner"+msgid "Owner (cost center)"msgstr "Owner (cost center)"@@ -8568,6 +8749,12 @@ msgstr "Part ID"msgid "Part is configured for manufacturing"msgstr "Part is configured for manufacturing"+msgid "Part Number"+msgstr "Part Number"++msgid "Part Supersession"+msgstr "Part Supersession"+msgid "Partial"msgstr "Partial"@@ -9531,6 +9718,9 @@ msgstr "Reason"msgid "Reason Account"msgstr "Reason Account"+msgid "Reason for Change"+msgstr "Reason for Change"+msgid "Reason for declining (Optional)"msgstr "Reason for declining (Optional)"@@ -9733,12 +9923,27 @@ msgstr "Relative timeline · dates to be confirmed"msgid "Release"msgstr "Release"+msgid "Release change order"+msgstr "Release change order"++msgid "Release control"+msgstr "Release control"++msgid "Release Control"+msgstr "Release Control"+msgid "Release Job"msgstr "Release Job"msgid "Released"msgstr "Released"+msgid "Released revision"+msgstr "Released revision"++msgid "Released revision is locked"+msgstr "Released revision is locked"+msgid "Remaining"msgstr "Remaining"@@ -9785,6 +9990,9 @@ msgstr "Remove sort by column"msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."msgstr "Remove this storage type from all referencing storage units and delete it. This cannot be undone."+msgid "Removed"+msgstr "Removed"+msgid "Rendering label preview..."msgstr "Rendering label preview..."@@ -10006,6 +10214,9 @@ msgstr "Reverse Charge Sales Tax (default)"msgid "Reverse the related journal entries"msgstr "Reverse the related journal entries"+msgid "Review each item's changes, then confirm — releasing can't be undone."+msgstr "Review each item's changes, then confirm — releasing can't be undone."+msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."@@ -10019,6 +10230,9 @@ msgstr "Revision"msgid "Revision {0}"msgstr "Revision {0}"+msgid "Revisions"+msgstr "Revisions"+msgid "Revoke"msgstr "Revoke"@@ -11361,6 +11575,9 @@ msgstr "Successfully copied quote"msgid "Successfully created a new revision"msgstr "Successfully created a new revision"+msgid "Successor effectivity"+msgstr "Successor effectivity"+msgid "Successor Effectivity Date"msgstr "Successor Effectivity Date"@@ -12432,6 +12649,9 @@ msgstr "This information will be used on document headers"msgid "This information will be visible to all users, so be careful what you share."msgstr "This information will be visible to all users, so be careful what you share."+msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."+msgstr "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."+msgid "This is a unique identifier for the webhook"msgstr "This is a unique identifier for the webhook"@@ -12489,6 +12709,12 @@ msgstr "This period has no journal entries posted to it and can be permanently dmsgid "This Quarter"msgstr "This Quarter"+msgid "This revision is released (Production). Changes should normally flow through a change order."+msgstr "This revision is released (Production). Changes should normally flow through a change order."++msgid "This revision is released (Production). Open a change order to modify it."+msgstr "This revision is released (Production). Open a change order to modify it."+msgid "This sales order has associated jobs. Choose what to do with them."msgstr "This sales order has associated jobs. Choose what to do with them."@@ -12531,6 +12757,9 @@ msgstr "This will replace all method materials of other revisions with this revimsgid "This will replace all method materials of other sizes with this size."msgstr "This will replace all method materials of other sizes with this size."+msgid "This will set the current version of the make method to Active, making it read-only."+msgstr "This will set the current version of the make method to Active, making it read-only."+msgid "This will write off the remaining book value of the asset."msgstr "This will write off the remaining book value of the asset."@@ -13493,6 +13722,9 @@ msgstr "Warehouse, Ops"msgid "Warn"msgstr "Warn"+msgid "Warn — edits succeed with a warning"+msgstr "Warn — edits succeed with a warning"+msgid "Warn but allow"msgstr "Warn but allow"@@ -13624,6 +13856,9 @@ msgstr "What is {translatedTerm}?"msgid "What it is"msgstr "What it is"+msgid "What kind of change this is: Version updates how the part is made, Revision edits its details and documents, and New Part replaces it with a new part number."+msgstr "What kind of change this is: Version updates how the part is made, Revision edits its details and documents, and New Part replaces it with a new part number."+msgid "What kind of output this entry records — Production (good units), Scrap (unrecoverable), or Rework (sent back for correction); reveals Scrap Reason when Scrap."msgstr "What kind of output this entry records — Production (good units), Scrap (unrecoverable), or Rework (sent back for correction); reveals Scrap Reason when Scrap."@@ -13783,6 +14018,9 @@ msgstr "Where new stock of this item lands by default on receipt; per-line storamsgid "Where stock lives and how it ships."msgstr "Where stock lives and how it ships."+msgid "Where the affected items are used across the system. Informational — nothing here blocks releasing."+msgstr "Where the affected items are used across the system. Informational — nothing here blocks releasing."+msgid "Where this entry originated (manual entry, posting from sales/purchasing, recurring template, etc.)."msgstr "Where this entry originated (manual entry, posting from sales/purchasing, recurring template, etc.)."@@ -14071,6 +14309,9 @@ msgstr "You've been clocked in for {hoursElapsed} hours. Did you forget to clockmsgid "Your books and how money flows."msgstr "Your books and how money flows."+msgid "Your changes go into a new draft version released with this change order."+msgstr "Your changes go into a new draft version released with this change order."+msgid "Your Console PIN"msgstr "Your Console PIN"diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.poindex e9a04b46c4..ed796b1dd7 100644--- a/packages/locale/locales/en/mes.po+++ b/packages/locale/locales/en/mes.po@@ -610,6 +610,9 @@ msgstr "No Impact"msgid "No maintenance scheduled for today"msgstr "No maintenance scheduled for today"+msgid "No matches. Type to create one."+msgstr "No matches. Type to create one."+msgid "No materials"msgstr "No materials"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex cf25d3f01e..c94df1fd58 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -38,6 +38,10 @@ msgstr "\"{taskName}\" está hecho — todos los {0} elementos de su Mapa de Conmsgid "(excluded for this customer)"msgstr "(excluido para este cliente)"+#. placeholder {0}: open.length+msgid "{0, plural, one {This part is on 1 open change order} other {This part is on # open change orders}}"+msgstr "{0, plural, one {Esta parte está en 1 orden de cambio abierta} other {Esta parte está en # órdenes de cambio abiertas}}"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} clientes con saldo"@@ -211,6 +215,9 @@ msgstr "90 días"msgid "A Carbon-run data migration — you load your own data"msgstr "Una migración de datos ejecutada por Carbon — usted carga sus propios datos"+msgid "A change order tracks a controlled engineering or manufacturing change through review and implementation."+msgstr "Una orden de cambio rastrea un cambio de ingeniería o fabricación controlado a través de revisión e implementación."+msgid "A clearing account holding the value of goods received but not yet billed; the supplier invoice clears it."msgstr "Una cuenta de compensación que mantiene el valor de bienes recibidos pero aún no facturados; la factura del proveedor la cancela."@@ -502,6 +509,9 @@ msgstr "Costo de adquisición"msgid "Acquisition Date"msgstr "Fecha de adquisición"+msgid "Action"+msgstr "Acción"+msgid "Action Status"msgstr "Estado de la Acción"@@ -592,6 +602,9 @@ msgstr "Agregar Acciones"msgid "Add Adjustment"msgstr "Agregar ajuste"+msgid "Add Affected Item"+msgstr "Añadir elemento afectado"+msgid "Add any notes about your decision..."msgstr "Añade cualquier nota sobre tu decisión..."@@ -670,9 +683,6 @@ msgstr "Agregar pregunta"msgid "Add Receipt"msgstr "Agregar Recepción"-msgid "Add Required Actions"-msgstr "Agregar Acciones Requeridas"-msgid "Add Requirement"msgstr "Agregar Requisito"@@ -719,6 +729,9 @@ msgstr "Complemento"msgid "Add-On Cost"msgstr "Costo Adicional"+msgid "Added"+msgstr "Añadido"+msgid "Added for this customer"msgstr "Añadido para este cliente"@@ -737,9 +750,15 @@ msgstr "Línea de Dirección 2"msgid "Adjustment Type"msgstr "Tipo de Ajuste"+msgid "Advance to {nextStatus}"+msgstr "Avanzar a {nextStatus}"+msgid "Advanced"msgstr "Avanzado"+msgid "Affected item not found."+msgstr "Elemento afectado no encontrado."+msgid "After"msgstr "Después"@@ -846,6 +865,9 @@ msgstr "Un registro contable de un elemento capitalizado que deprecia en lugar dmsgid "An asset's acquisition cost minus accumulated depreciation — what it's still worth on the books, and the figure it's disposed at."msgstr "El costo de adquisición de un activo menos la depreciación acumulada — lo que aún vale en los libros y la cantidad en que se dispone."+msgid "An engineering change: the affected items whose methods are revised on a draft and released together, superseding the versions they replace."+msgstr "Un cambio de ingeniería: los elementos afectados cuyos métodos se revisan en un borrador y se lanzan juntos, reemplazando las versiones que sustituyen."+msgid "An integration or a custom change — the small slice that's actually custom."msgstr "Una integración o un cambio personalizado — la pequeña parte que es realmente personalizada."@@ -1033,6 +1055,10 @@ msgstr "¿Estás seguro de que deseas activar el proceso: {name}? Volverá a apamsgid "Are you sure you want to activate this gauge?."msgstr "¿Está seguro de que desea activar este calibrador?."+#. placeholder {0}: routeData?.changeOrder?.changeOrderId ?? ""+msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."+msgstr "¿Estás seguro de que deseas cancelar {0}? Se cerrará y será de solo lectura hasta que lo vuelvas a abrir."+#. placeholder {0}: routeData?.rfqSummary ?.rfqId!msgid "Are you sure you want to cancel {0}? This will also cancel all related supplier quotes."msgstr "¿Estás seguro de que deseas cancelar {0}? Esto también cancelará todas las cotizaciones de proveedores relacionadas."@@ -1123,6 +1149,14 @@ msgstr "¿Estás seguro de que deseas eliminar la cuenta: {0}{1}? Esta acción nmsgid "Are you sure you want to delete the API key: {0}? This cannot be undone."msgstr "¿Estás seguro de que deseas eliminar la clave API: {0}? Esto no se puede deshacer."+#. placeholder {0}: requiredAction.name+msgid "Are you sure you want to delete the change order action: {0}? This cannot be undone."+msgstr "¿Estás seguro de que deseas eliminar la acción de la orden de cambio: {0}? Esto no se puede deshacer."++#. placeholder {0}: changeOrderType.name+msgid "Are you sure you want to delete the change order category: {0}? This cannot be undone."+msgstr "¿Está seguro de que desea eliminar la categoría de orden de cambio: {0}? Esto no se puede deshacer."+msgid "Are you sure you want to delete the contractor: {name}? This cannot be undone."msgstr "¿Estás seguro de que deseas eliminar el contratista: {name}? Esto no se puede deshacer."@@ -1281,6 +1315,9 @@ msgstr "¿Estás seguro de que deseas eliminar el webhook: {0}? Esto no se puedemsgid "Are you sure you want to delete this approval rule? This cannot be undone."msgstr "¿Está seguro de que desea eliminar esta regla de aprobación? Esto no se puede deshacer."+msgid "Are you sure you want to delete this change order?"+msgstr "¿Está seguro de que desea eliminar esta orden de cambio?"+msgid "Are you sure you want to delete this gauge?"msgstr "¿Estás seguro de que deseas eliminar este calibrador?"@@ -1893,6 +1930,12 @@ msgstr "No se puede descargar este archivo"msgid "Cancel"msgstr "Cancelar"+msgid "Cancel change order"+msgstr "Cancelar orden de cambio"++msgid "Cancel Change Order"+msgstr "Cancelar Orden de Cambio"+msgid "Cancel Job"msgstr "Cancelar Trabajo"@@ -2055,12 +2098,30 @@ msgstr "Campeones"msgid "Change"msgstr "Cambiar"+msgid "Change order"+msgstr "Orden de cambio"++msgid "Change Order"+msgstr "Orden de Cambio"++msgid "Change Order Actions"+msgstr "Acciones de orden de cambio"++msgid "Change Order Types"+msgstr "Tipos de Orden de Cambio"++msgid "Change Orders"+msgstr "Órdenes de Cambio"+msgid "Change status"msgstr "Cambiar estado"msgid "Change the item type (e.g. Part, Material, Tool, etc.)"msgstr "Cambiar el tipo de artículo (p. ej., Pieza, Material, Herramienta, etc.)"+msgid "Change type"+msgstr "Tipo de cambio"+msgid "Change Type"msgstr "Cambiar Tipo"@@ -2076,6 +2137,9 @@ msgstr "Cambiar esto sobrescribirá el método existente"msgid "Changing this will update the part ID"msgstr "Cambiar esto actualizará el ID de la pieza"+msgid "Changing type resets this item's draft edits."+msgstr "Cambiar el tipo restablece los borradores editados de este elemento."+msgid "Chart of accounts"msgstr "Plan de cuentas"@@ -2411,6 +2475,9 @@ msgstr "Confirmar"msgid "Confirm {0}"msgstr "Confirmar {0}"+msgid "Confirm & release"+msgstr "Confirmar y liberar"+msgid "Confirm and sign the scope"msgstr "Confirmar y firmar el alcance"@@ -2549,6 +2616,9 @@ msgstr "Controlador, Contador"msgid "Controls how planning handles a discontinued item: Consume First exhausts on-hand before switching to the successor, Prefer New redirects new demand to the successor immediately, Stock Only keeps only a minimum service reserve, and No Stock drops the item from planning entirely."msgstr "Controla cómo la planificación maneja un artículo descontinuado: Consumir Primero agota el inventario disponible antes de cambiar al sucesor, Preferir Nuevo redirige la nueva demanda al sucesor inmediatamente, Solo Stock mantiene solo una reserva de servicio mínima, y Sin Stock elimina el artículo de la planificación por completo."+msgid "Controls whether the bill of material and bill of process of a released (Production) revision can be edited outside a change order."+msgstr "Controla si la lista de materiales y lista de procesos de una revisión liberada (Producción) pueden ser editadas fuera de una orden de cambio."+msgid "Convention"msgstr "Convención"@@ -2630,6 +2700,9 @@ msgstr "Copiar número de trabajo"msgid "Copy link"msgstr "Copiar enlace"+msgid "Copy link to change order"+msgstr "Copiar enlace a orden de cambio"+msgid "Copy link to consumable"msgstr "Copiar enlace al consumible"@@ -2848,6 +2921,9 @@ msgstr "Crear {0} valores"msgid "Create & Snapshot"msgstr "Crear y Capturar"+msgid "Create a change order for the new revision and open it"+msgstr "Crear una orden de cambio para la nueva revisión y abrirla"+msgid "Create a new kanban card for scan-based replenishment."msgstr "Crea una nueva tarjeta kanban para reabastecimiento basado en escaneo."@@ -2875,6 +2951,9 @@ msgstr "Crear y aprobar órdenes de compra"msgid "Create audit trail entries"msgstr "Crear entradas de pista de auditoría"+msgid "Create Change Order"+msgstr "Crear Orden de Cambio"+msgid "Create Issue"msgstr "Crear Problema"@@ -2932,6 +3011,12 @@ msgstr "Creado el"msgid "Created By"msgstr "Creado por"+msgid "Created change order action"+msgstr "Acción de orden de cambio creada"++msgid "Created change order type"+msgstr "Tipo de orden de cambio creado"+msgid "Created consumable"msgstr "Consumible creado"@@ -3550,6 +3635,12 @@ msgstr "Eliminar {periodLabel}"msgid "Delete {storageUnitName}"msgstr "Eliminar {storageUnitName}"+msgid "Delete action"+msgstr "Eliminar acción"++msgid "Delete Action"+msgstr "Eliminar acción"+msgid "Delete API Key"msgstr "Eliminar clave API"@@ -3565,6 +3656,9 @@ msgstr "Eliminar Atributo"msgid "Delete Category"msgstr "Eliminar Categoría"+msgid "Delete Change Order"+msgstr "Eliminar Orden de Cambio"+msgid "Delete Consumable"msgstr "Eliminar Consumible"@@ -3794,6 +3888,9 @@ msgstr "Eliminar Transferencia"msgid "Delete Transfer Line"msgstr "Eliminar Línea de Transferencia"+msgid "Delete Type"+msgstr "Eliminar Tipo"+msgid "Delete Unit of Measure"msgstr "Eliminar unidad de medida"@@ -3884,6 +3981,9 @@ msgstr "Descripción"msgid "Description (optional)"msgstr "Descripción (opcional)"+msgid "Description of Change"+msgstr "Descripción del Cambio"+msgid "Description of Issue"msgstr "Descripción del Problema"@@ -3929,6 +4029,9 @@ msgstr "Deshabilitado"msgid "Discard"msgstr "Descartar"+msgid "Discontinuation date"+msgstr "Fecha de descontinuación"+msgid "Discontinuation Date"msgstr "Fecha de Discontinuación"@@ -4196,6 +4299,9 @@ msgstr "Editar Flujo de Trabajo <0>Problema</0>"msgid "Edit Account"msgstr "Editar Cuenta"+msgid "Edit Action"+msgstr "Editar acción"+msgid "Edit API Key"msgstr "Editar Clave API"@@ -4217,6 +4323,15 @@ msgstr "Editar Categoría de Atributo"msgid "Edit Category"msgstr "Editar Categoría"+msgid "Edit Change Order"+msgstr "Editar Orden de Cambio"++msgid "Edit Change Order Action"+msgstr "Editar acción de orden de cambio"++msgid "Edit Change Order Type"+msgstr "Editar Tipo de Orden de Cambio"+msgid "Edit column visibility"msgstr "Editar visibilidad de columnas"@@ -4466,6 +4581,9 @@ msgstr "Editar Transferencia"msgid "Edit Transfer Line"msgstr "Editar Línea de Transferencia"+msgid "Edit Type"+msgstr "Editar Tipo"+msgid "Edit Unit of Measure"msgstr "Editar Unidad de Medida"@@ -4583,6 +4701,9 @@ msgstr "Fin del Trimestre Anterior"msgid "End Time"msgstr "Hora de Finalización"+msgid "Enforce — edits are blocked"+msgstr "Aplicar — las ediciones están bloqueadas"+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Aplicar validación y directrices por artículo en recibos, envíos, transferencias y ajustes."@@ -6004,6 +6125,9 @@ msgstr "II (normal predeterminado)"msgid "III (tightened)"msgstr "III (apretado)"+msgid "Impact"+msgstr "Impacto"+msgid "Imperial"msgstr "Imperial"@@ -6551,6 +6675,9 @@ msgstr "Mantener Actual"msgid "Keep existing pricing, only add new items"msgstr "Mantener precios existentes, solo agregar elementos nuevos"+msgid "Keep Open"+msgstr "Mantener Abierto"+msgid "Key"msgstr "Clave"@@ -6655,6 +6782,9 @@ msgstr "Dejar los recibos relacionados sin tocar"msgid "Leave blank for built-in"msgstr "Dejar en blanco para usar el integrado"+msgid "Leave blank to use the next revision automatically"+msgstr "Dejar en blanco para usar la siguiente revisión automáticamente"+msgid "Leave empty for exact match"msgstr "Dejar vacío para coincidencia exacta"@@ -6750,6 +6880,9 @@ msgstr "Vincular problema de Linear"msgid "Linked entity quantity ({0}) does not match row quantity ({1})."msgstr "La cantidad de entidad vinculada ({0}) no coincide con la cantidad de fila ({1})."+msgid "Linked NCR"+msgstr "NCR vinculado"+msgid "Linked PO"msgstr "PO vinculada"@@ -7352,6 +7485,9 @@ msgstr "Modelo eliminado del trabajo"msgid "Model removed from line"msgstr "Modelo eliminado de la línea"+msgid "Modified"+msgstr "Modificado"+msgid "Module"msgstr "Módulo"@@ -7501,6 +7637,15 @@ msgstr "Nuevo Atributo"msgid "New Attribute Category"msgstr "Nueva Categoría de Atributo"+msgid "New Change Order"+msgstr "Nueva orden de cambio"++msgid "New Change Order Action"+msgstr "Nueva acción de orden de cambio"++msgid "New Change Order Type"+msgstr "Nuevo Tipo de Orden de Cambio"+msgid "New Consumable"msgstr "Nuevo Consumible"@@ -7815,6 +7960,12 @@ msgstr "Sin presupuestos activos"msgid "No addresses found"msgstr "No se encontraron direcciones"+msgid "No affected items to assess."+msgstr "No hay elementos afectados para evaluar."++msgid "No affected items."+msgstr "Sin elementos afectados."+msgid "No applications. Payment will be on-account."msgstr "Sin aplicaciones. El pago será a cuenta."@@ -7840,6 +7991,9 @@ msgstr "No se encontraron registros de calibración"msgid "No changes recorded"msgstr "Sin cambios registrados"+msgid "No changes yet."+msgstr "Sin cambios aún."+msgid "No comments yet. Be the first to add a comment."msgstr "No hay comentarios aún. Sé el primero en agregar un comentario."@@ -7867,12 +8021,18 @@ msgstr "Sin días libres programados"msgid "No default attachments yet."msgstr "Sin adjuntos predeterminados aún."+msgid "No draft make method for this item yet."+msgstr "Sin método de fabricación en borrador para este elemento aún."+msgid "No draft versions available"msgstr "No hay versiones en borrador disponibles"msgid "No due date"msgstr "Sin fecha de vencimiento"+msgid "No editable properties for this item."+msgstr "Sin propiedades editables para este elemento."+msgid "No employees assigned yet. Add groups to see status."msgstr "No hay empleados asignados aún. Agregue grupos para ver el estado."@@ -7897,6 +8057,9 @@ msgstr "No se encontraron campos."msgid "No files"msgstr "Sin archivos"+msgid "No files for this item."+msgstr "Sin archivos para este elemento."+msgid "No files uploaded"msgstr "No hay archivos cargados"@@ -7933,6 +8096,9 @@ msgstr "Sin coincidencias"msgid "No matches for \"{query}\". Try a different search term."msgstr "No hay coincidencias para \"{query}\". Intenta un término de búsqueda diferente."+msgid "No matches. Type to create one."+msgstr "Sin coincidencias. Escribe para crear una."+msgid "No new notifications"msgstr "Sin notificaciones nuevas"@@ -8098,6 +8264,9 @@ msgstr "No es una tabla sino un saldo del libro mayor: el costo se acumula cuandmsgid "Not enough jobs to cover quantity"msgstr "No hay suficientes trabajos para cubrir la cantidad"+msgid "Not referenced anywhere yet."+msgstr "Sin referencias aún."+msgid "Not Required"msgstr "No requerido"@@ -8149,6 +8318,9 @@ msgstr "OEM (fabricante de equipos originales)"msgid "of"msgstr "de"+msgid "Off — released revisions stay editable"+msgstr "Desactivado — las revisiones lanzadas permanecen editables"+msgid "OK"msgstr "Aceptar"@@ -8236,6 +8408,9 @@ msgstr "¡Oops! El enlace que intentas acceder no es válido."msgid "Open"msgstr "Abrir"+msgid "Open a change order"+msgstr "Abrir una orden de cambio"+msgid "Open Actions"msgstr "Acciones Abiertas"@@ -8251,6 +8426,9 @@ msgstr "AR abierto"msgid "Open Audit Log"msgstr "Abrir Registro de Auditoría"+msgid "Open change orders affecting this part"+msgstr "Órdenes de cambio abiertas que afectan esta parte"+msgid "Open Date"msgstr "Fecha de Apertura"@@ -8504,6 +8682,9 @@ msgstr "Sobrescribir el método de cotización con el método de origen"msgid "Overwrite the target manufacturing method with the quote method"msgstr "Sobrescribir el método de fabricación objetivo con el método de cotización"+msgid "Owner"+msgstr "Propietario"+msgid "Owner (cost center)"msgstr "Centro de costos principal"@@ -8568,6 +8749,12 @@ msgstr "ID de Pieza"msgid "Part is configured for manufacturing"msgstr "La pieza está configurada para fabricación"+msgid "Part Number"+msgstr "Número de pieza"++msgid "Part Supersession"+msgstr "Sustitución de Pieza"+msgid "Partial"msgstr "Parcial"@@ -9531,6 +9718,9 @@ msgstr "Razón"msgid "Reason Account"msgstr "Cuenta de Razón"+msgid "Reason for Change"+msgstr "Razón del cambio"+msgid "Reason for declining (Optional)"msgstr "Motivo de rechazo (Opcional)"@@ -9733,12 +9923,27 @@ msgstr "Cronograma relativo · fechas por confirmar"msgid "Release"msgstr "Liberar"+msgid "Release change order"+msgstr "Liberar orden de cambio"++msgid "Release control"+msgstr "Control de lanzamiento"++msgid "Release Control"+msgstr "Control de lanzamiento"+msgid "Release Job"msgstr "Liberar Trabajo"msgid "Released"msgstr "Liberado"+msgid "Released revision"+msgstr "Revisión lanzada"++msgid "Released revision is locked"+msgstr "La revisión lanzada está bloqueada"+msgid "Remaining"msgstr "Restante"@@ -9785,6 +9990,9 @@ msgstr "Eliminar ordenamiento por columna"msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."msgstr "Elimina este tipo de almacenamiento de todas las unidades de almacenamiento que lo referencian y elimínalo. Esto no se puede deshacer."+msgid "Removed"+msgstr "Eliminado"+msgid "Rendering label preview..."msgstr "Renderizando vista previa de etiqueta..."@@ -10006,6 +10214,9 @@ msgstr "Impuesto a las ventas de cargo inverso (predeterminado)"msgid "Reverse the related journal entries"msgstr "Revertir los asientos de diario relacionados"+msgid "Review each item's changes, then confirm — releasing can't be undone."+msgstr "Revisa los cambios de cada elemento y confirma — liberar no se puede deshacer."+msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Revise el balance general y el estado de resultados del período y confirme que las cifras se ven correctas. Este es un visto bueno manual — marque como hecho una vez que los haya revisado."@@ -10019,6 +10230,9 @@ msgstr "Revisión"msgid "Revision {0}"msgstr "Revisión {0}"+msgid "Revisions"+msgstr "Revisiones"+msgid "Revoke"msgstr "Revocar"@@ -11361,6 +11575,9 @@ msgstr "Presupuesto copiado exitosamente"msgid "Successfully created a new revision"msgstr "Se creó exitosamente una nueva revisión"+msgid "Successor effectivity"+msgstr "Efectividad del sucesor"+msgid "Successor Effectivity Date"msgstr "Fecha de Efectividad del Sucesor"@@ -12432,6 +12649,9 @@ msgstr "Esta información se utilizará en los encabezados de documentos"msgid "This information will be visible to all users, so be careful what you share."msgstr "Esta información será visible para todos los usuarios, así que ten cuidado con lo que compartes."+msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."+msgstr "Este es un artículo comprado — no tiene BoM/BoP; solo sus atributos y documentos pueden cambiar."+msgid "This is a unique identifier for the webhook"msgstr "Este es un identificador único para el webhook"@@ -12489,6 +12709,12 @@ msgstr "Este período no tiene asientos de diario registrados en él y puede elimsgid "This Quarter"msgstr "Este Trimestre"+msgid "This revision is released (Production). Changes should normally flow through a change order."+msgstr "Esta revisión está liberada (Producción). Los cambios normalmente deben fluir a través de una orden de cambio."++msgid "This revision is released (Production). Open a change order to modify it."+msgstr "Esta revisión está liberada (Producción). Abra una orden de cambio para modificarla."+msgid "This sales order has associated jobs. Choose what to do with them."msgstr "Este pedido de venta tiene trabajos asociados. Elige qué hacer con ellos."@@ -12531,6 +12757,9 @@ msgstr "Esto reemplazará todos los materiales de método de otras revisiones comsgid "This will replace all method materials of other sizes with this size."msgstr "Esto reemplazará todos los materiales de método de otros tamaños con este tamaño."+msgid "This will set the current version of the make method to Active, making it read-only."+msgstr "Esto establecerá la versión actual del método de fabricación como Activa, haciéndola de solo lectura."+msgid "This will write off the remaining book value of the asset."msgstr "Esto liquidará el valor en libros restante del activo."@@ -13493,6 +13722,9 @@ msgstr "Almacén, Ops"msgid "Warn"msgstr "Advertencia"+msgid "Warn — edits succeed with a warning"+msgstr "Advertencia — las ediciones se realizan con una advertencia"+msgid "Warn but allow"msgstr "Advertir pero permitir"@@ -13624,6 +13856,9 @@ msgstr "¿Qué es {translatedTerm}?"msgid "What it is"msgstr "Qué es"+msgid "What kind of change this is: Version updates how the part is made, Revision edits its details and documents, and New Part replaces it with a new part number."+msgstr "Qué tipo de cambio es: Versión actualiza cómo se fabrica la pieza, Revisión edita sus detalles y documentos, y Nueva Pieza la reemplaza con un nuevo número de parte."+msgid "What kind of output this entry records — Production (good units), Scrap (unrecoverable), or Rework (sent back for correction); reveals Scrap Reason when Scrap."msgstr "Qué tipo de salida registra esta entrada — Producción (unidades buenas), Scrap (irrecuperable) o Rework (enviado de vuelta para corrección); revela Scrap Reason cuando Scrap."@@ -13783,6 +14018,9 @@ msgstr "Dónde aterriza el nuevo stock de este artículo por defecto al recibirlmsgid "Where stock lives and how it ships."msgstr "Dónde vive el stock y cómo se envía."+msgid "Where the affected items are used across the system. Informational — nothing here blocks releasing."+msgstr "Dónde se utilizan los elementos afectados en todo el sistema. Informativo — nada aquí bloquea la liberación."+msgid "Where this entry originated (manual entry, posting from sales/purchasing, recurring template, etc.)."msgstr "De dónde se originó esta entrada (entrada manual, contabilización de ventas/compras, plantilla recurrente, etc.)."@@ -14067,6 +14305,9 @@ msgstr "Has estado marcado durante {hoursElapsed} horas. ¿Olvidaste marcar la smsgid "Your books and how money flows."msgstr "Tus libros y cómo fluye el dinero."+msgid "Your changes go into a new draft version released with this change order."+msgstr "Sus cambios van a una nueva versión borrador lanzada con esta orden de cambio."+msgid "Your Console PIN"msgstr "Tu PIN de Consola"diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.poindex 3faf4b09f3..16ce0e6ba3 100644--- a/packages/locale/locales/es/mes.po+++ b/packages/locale/locales/es/mes.po@@ -610,6 +610,9 @@ msgstr "Sin impacto"msgid "No maintenance scheduled for today"msgstr "No hay mantenimiento programado para hoy"+msgid "No matches. Type to create one."+msgstr "Sin coincidencias. Escribe para crear una."+msgid "No materials"msgstr "Sin materiales"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 79fd5e9c27..4fbcd3f9d4 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -38,6 +38,10 @@ msgstr "« {taskName} » est terminé — tous les {0} éléments de sa Carte demsgid "(excluded for this customer)"msgstr "(exclu pour ce client)"+#. placeholder {0}: open.length+msgid "{0, plural, one {This part is on 1 open change order} other {This part is on # open change orders}}"+msgstr "{0, plural, one {Cette pièce est sur 1 ordre de modification ouvert} other {Cette pièce est sur # ordres de modification ouverts}}"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} clients avec un solde"@@ -211,6 +215,9 @@ msgstr "90 jours"msgid "A Carbon-run data migration — you load your own data"msgstr "Une migration de données gérée par Carbon — vous chargez vos propres données"+msgid "A change order tracks a controlled engineering or manufacturing change through review and implementation."+msgstr "Un ordre de modification suit une modification technique ou manufacturière contrôlée tout au long de l'examen et de la mise en œuvre."+msgid "A clearing account holding the value of goods received but not yet billed; the supplier invoice clears it."msgstr "Un compte de compensation tenant la valeur des marchandises reçues mais non encore facturées ; la facture du fournisseur l'apure."@@ -502,6 +509,9 @@ msgstr "Coût d'acquisition"msgid "Acquisition Date"msgstr "Date d'acquisition"+msgid "Action"+msgstr "Action"+msgid "Action Status"msgstr "Statut de l'action"@@ -592,6 +602,9 @@ msgstr "Ajouter des actions"msgid "Add Adjustment"msgstr "Ajouter un ajustement"+msgid "Add Affected Item"+msgstr "Ajouter un article affecté"+msgid "Add any notes about your decision..."msgstr "Ajoutez des notes sur votre décision..."@@ -670,9 +683,6 @@ msgstr "Ajouter une question"msgid "Add Receipt"msgstr "Ajouter un reçu"-msgid "Add Required Actions"-msgstr "Ajouter les actions requises"-msgid "Add Requirement"msgstr "Ajouter une exigence"@@ -719,6 +729,9 @@ msgstr "Supplément"msgid "Add-On Cost"msgstr "Coût supplémentaire"+msgid "Added"+msgstr "Ajouté"+msgid "Added for this customer"msgstr "Ajouté pour ce client"@@ -737,9 +750,15 @@ msgstr "Ligne d'adresse 2"msgid "Adjustment Type"msgstr "Type d'ajustement"+msgid "Advance to {nextStatus}"+msgstr "Avancer vers {nextStatus}"+msgid "Advanced"msgstr "Avancé"+msgid "Affected item not found."+msgstr "Article affecté non trouvé."+msgid "After"msgstr "Après"@@ -846,6 +865,9 @@ msgstr "Un enregistrement comptable pour un élément capitalisé que vous amortmsgid "An asset's acquisition cost minus accumulated depreciation — what it's still worth on the books, and the figure it's disposed at."msgstr "Le coût d'acquisition d'un actif moins l'amortissement cumulé — ce qu'il vaut encore sur les livres et le montant auquel il est cédé."+msgid "An engineering change: the affected items whose methods are revised on a draft and released together, superseding the versions they replace."+msgstr "Un ordre de modification d'ingénierie : les articles affectés dont les méthodes sont révisées sur un brouillon et publiées ensemble, remplaçant les versions qu'elles remplacent."+msgid "An integration or a custom change — the small slice that's actually custom."msgstr "Une intégration ou une modification personnalisée — la petite partie qui est réellement personnalisée."@@ -1033,6 +1055,10 @@ msgstr "Êtes-vous sûr de vouloir activer le processus : {name} ? Il réapparamsgid "Are you sure you want to activate this gauge?."msgstr "Êtes-vous sûr de vouloir activer cette jauge ?."+#. placeholder {0}: routeData?.changeOrder?.changeOrderId ?? ""+msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."+msgstr "Êtes-vous sûr de vouloir annuler {0} ? Il sera fermé et en lecture seule jusqu'à ce que vous le rouvriez."+#. placeholder {0}: routeData?.rfqSummary ?.rfqId!msgid "Are you sure you want to cancel {0}? This will also cancel all related supplier quotes."msgstr "Êtes-vous sûr de vouloir annuler {0} ? Cela annulera également tous les devis fournisseurs associés."@@ -1123,6 +1149,14 @@ msgstr "Êtes-vous sûr de vouloir supprimer le compte : {0}{1} ? Cette action nmsgid "Are you sure you want to delete the API key: {0}? This cannot be undone."msgstr "Êtes-vous sûr de vouloir supprimer la clé API : {0}? Cette action ne peut pas être annulée."+#. placeholder {0}: requiredAction.name+msgid "Are you sure you want to delete the change order action: {0}? This cannot be undone."+msgstr "Êtes-vous sûr de vouloir supprimer l'action d'ordre de modification : {0} ? Cela ne peut pas être annulé."++#. placeholder {0}: changeOrderType.name+msgid "Are you sure you want to delete the change order category: {0}? This cannot be undone."+msgstr "Êtes-vous sûr de vouloir supprimer la catégorie d'ordre de modification : {0} ? Cette action ne peut pas être annulée."+msgid "Are you sure you want to delete the contractor: {name}? This cannot be undone."msgstr "Êtes-vous sûr de vouloir supprimer l'entrepreneur : {name} ? Cette action ne peut pas être annulée."@@ -1281,6 +1315,9 @@ msgstr "Êtes-vous sûr de vouloir supprimer le webhook : {0} ? Cette action nemsgid "Are you sure you want to delete this approval rule? This cannot be undone."msgstr "Êtes-vous sûr de vouloir supprimer cette règle d'approbation ? Cette action ne peut pas être annulée."+msgid "Are you sure you want to delete this change order?"+msgstr "Êtes-vous sûr de vouloir supprimer cet ordre de modification ?"+msgid "Are you sure you want to delete this gauge?"msgstr "Êtes-vous sûr de vouloir supprimer ce jauge ?"@@ -1893,6 +1930,12 @@ msgstr "Impossible de télécharger ce fichier"msgid "Cancel"msgstr "Annuler"+msgid "Cancel change order"+msgstr "Annuler le bon de modification"++msgid "Cancel Change Order"+msgstr "Annuler le bon de modification"+msgid "Cancel Job"msgstr "Annuler le travail"@@ -2055,12 +2098,30 @@ msgstr "Champions"msgid "Change"msgstr "Modifier"+msgid "Change order"+msgstr "Ordre de modification"++msgid "Change Order"+msgstr "Ordre de modification"++msgid "Change Order Actions"+msgstr "Actions d'ordre de modification"++msgid "Change Order Types"+msgstr "Types d'ordres de modification"++msgid "Change Orders"+msgstr "Ordres de modification"+msgid "Change status"msgstr "Modifier le statut"msgid "Change the item type (e.g. Part, Material, Tool, etc.)"msgstr "Modifier le type d'article (p. ex. Pièce, Matériau, Outil, etc.)"+msgid "Change type"+msgstr "Modifier le type"+msgid "Change Type"msgstr "Changer le type"@@ -2076,6 +2137,9 @@ msgstr "Modifier ceci remplacera la méthode existante"msgid "Changing this will update the part ID"msgstr "Cela modifiera l'ID de la pièce"+msgid "Changing type resets this item's draft edits."+msgstr "Modifier le type réinitialise les brouillons de cet article."+msgid "Chart of accounts"msgstr "Plan comptable"@@ -2411,6 +2475,9 @@ msgstr "Confirmer"msgid "Confirm {0}"msgstr "Confirmer {0}"+msgid "Confirm & release"+msgstr "Confirmer et publier"+msgid "Confirm and sign the scope"msgstr "Confirmer et signer l'étendue"@@ -2549,6 +2616,9 @@ msgstr "Contrôleur, Comptable"msgid "Controls how planning handles a discontinued item: Consume First exhausts on-hand before switching to the successor, Prefer New redirects new demand to the successor immediately, Stock Only keeps only a minimum service reserve, and No Stock drops the item from planning entirely."msgstr "Contrôle la façon dont la planification gère un article discontinué : Consommer d'abord épuise le stock existant avant de basculer vers le successeur, Préférer le nouveau redirige immédiatement la nouvelle demande vers le successeur, Stock uniquement conserve uniquement une réserve de service minimale, et Pas de stock supprime l'article de la planification entièrement."+msgid "Controls whether the bill of material and bill of process of a released (Production) revision can be edited outside a change order."+msgstr "Contrôle si la nomenclature et le processus de fabrication d'une révision publiée (Production) peuvent être modifiés en dehors d'un ordre de modification."+msgid "Convention"msgstr "Convention"@@ -2630,6 +2700,9 @@ msgstr "Copier le numéro de travail"msgid "Copy link"msgstr "Copier le lien"+msgid "Copy link to change order"+msgstr "Copier le lien vers l'ordre de modification"+msgid "Copy link to consumable"msgstr "Copier le lien vers le consommable"@@ -2848,6 +2921,9 @@ msgstr "Créer {0} valeurs"msgid "Create & Snapshot"msgstr "Créer et capturer"+msgid "Create a change order for the new revision and open it"+msgstr "Créer un ordre de modification pour la nouvelle révision et l'ouvrir"+msgid "Create a new kanban card for scan-based replenishment."msgstr "Créer une nouvelle carte kanban pour le réapprovisionnement basé sur la numérisation."@@ -2875,6 +2951,9 @@ msgstr "Créer et approuver les commandes d'achat"msgid "Create audit trail entries"msgstr "Créer des entrées de piste d'audit"+msgid "Create Change Order"+msgstr "Créer un ordre de modification"+msgid "Create Issue"msgstr "Créer un problème"@@ -2932,6 +3011,12 @@ msgstr "Créé le"msgid "Created By"msgstr "Créé par"+msgid "Created change order action"+msgstr "Action d'ordre de modification créée"++msgid "Created change order type"+msgstr "Type de bon de modification créé"+msgid "Created consumable"msgstr "Consommable créé"@@ -3550,6 +3635,12 @@ msgstr "Supprimer {periodLabel}"msgid "Delete {storageUnitName}"msgstr "Supprimer {storageUnitName}"+msgid "Delete action"+msgstr "Supprimer l'action"++msgid "Delete Action"+msgstr "Supprimer l'action"+msgid "Delete API Key"msgstr "Supprimer la clé API"@@ -3565,6 +3656,9 @@ msgstr "Supprimer l'attribut"msgid "Delete Category"msgstr "Supprimer la catégorie"+msgid "Delete Change Order"+msgstr "Supprimer l'ordre de modification"+msgid "Delete Consumable"msgstr "Supprimer la consommable"@@ -3794,6 +3888,9 @@ msgstr "Supprimer le transfert"msgid "Delete Transfer Line"msgstr "Supprimer la ligne de transfert"+msgid "Delete Type"+msgstr "Supprimer le type"+msgid "Delete Unit of Measure"msgstr "Supprimer l'unité de mesure"@@ -3884,6 +3981,9 @@ msgstr "Description"msgid "Description (optional)"msgstr "Description (facultatif)"+msgid "Description of Change"+msgstr "Description du changement"+msgid "Description of Issue"msgstr "Description du problème"@@ -3929,6 +4029,9 @@ msgstr "Désactivé"msgid "Discard"msgstr "Rejeter"+msgid "Discontinuation date"+msgstr "Date d'arrêt"+msgid "Discontinuation Date"msgstr "Date d'arrêt"@@ -4196,6 +4299,9 @@ msgstr "Modifier le Flux de Travail <0>Problème</0>"msgid "Edit Account"msgstr "Modifier le compte"+msgid "Edit Action"+msgstr "Modifier l'action"+msgid "Edit API Key"msgstr "Modifier la clé API"@@ -4217,6 +4323,15 @@ msgstr "Modifier la catégorie d'attribut"msgid "Edit Category"msgstr "Modifier la catégorie"+msgid "Edit Change Order"+msgstr "Modifier l'ordre de modification"++msgid "Edit Change Order Action"+msgstr "Modifier l'action d'ordre de modification"++msgid "Edit Change Order Type"+msgstr "Modifier le type de bon de modification"+msgid "Edit column visibility"msgstr "Modifier la visibilité des colonnes"@@ -4466,6 +4581,9 @@ msgstr "Modifier le transfert"msgid "Edit Transfer Line"msgstr "Modifier la ligne de transfert"+msgid "Edit Type"+msgstr "Modifier le type"+msgid "Edit Unit of Measure"msgstr "Modifier l'unité de mesure"@@ -4583,6 +4701,9 @@ msgstr "Fin du dernier trimestre"msgid "End Time"msgstr "Heure de fin"+msgid "Enforce — edits are blocked"+msgstr "Appliquer — les modifications sont bloquées"+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Appliquer la validation et les directives par article dans les reçus, les expéditions, les transferts et les ajustements."@@ -6004,6 +6125,9 @@ msgstr "II (normal par défaut)"msgid "III (tightened)"msgstr "III (renforcé)"+msgid "Impact"+msgstr "Impact"+msgid "Imperial"msgstr "Impérial"@@ -6551,6 +6675,9 @@ msgstr "Conserver les paramètres actuels"msgid "Keep existing pricing, only add new items"msgstr "Conserver la tarification existante, ajouter uniquement les nouveaux articles"+msgid "Keep Open"+msgstr "Garder ouvert"+msgid "Key"msgstr "Clé"@@ -6655,6 +6782,9 @@ msgstr "Laisser les reçus connexes intacts"msgid "Leave blank for built-in"msgstr "Laisser vide pour utiliser le modèle intégré"+msgid "Leave blank to use the next revision automatically"+msgstr "Laisser vide pour utiliser automatiquement la prochaine révision"+msgid "Leave empty for exact match"msgstr "Laisser vide pour une correspondance exacte"@@ -6750,6 +6880,9 @@ msgstr "Lier un problème Linear"msgid "Linked entity quantity ({0}) does not match row quantity ({1})."msgstr "La quantité d'entité liée ({0}) ne correspond pas à la quantité de ligne ({1})."+msgid "Linked NCR"+msgstr "RNC lié"+msgid "Linked PO"msgstr "Bon de commande lié"@@ -7352,6 +7485,9 @@ msgstr "Modèle supprimé du projet"msgid "Model removed from line"msgstr "Modèle supprimé de la ligne"+msgid "Modified"+msgstr "Modifié"+msgid "Module"msgstr "Module"@@ -7501,6 +7637,15 @@ msgstr "Nouvel Attribut"msgid "New Attribute Category"msgstr "Nouvelle Catégorie d'Attribut"+msgid "New Change Order"+msgstr "Nouvelle demande de modification"++msgid "New Change Order Action"+msgstr "Nouvelle action d'ordre de modification"++msgid "New Change Order Type"+msgstr "Nouveau type de bon de modification"+msgid "New Consumable"msgstr "Nouveau consommable"@@ -7815,6 +7960,12 @@ msgstr "Aucun devis actif"msgid "No addresses found"msgstr "Aucune adresse trouvée"+msgid "No affected items to assess."+msgstr "Aucun article affecté à évaluer."++msgid "No affected items."+msgstr "Aucun article affecté."+msgid "No applications. Payment will be on-account."msgstr "Aucune application. Le paiement sera sur compte."@@ -7840,6 +7991,9 @@ msgstr "Aucun enregistrement d'étalonnage trouvé"msgid "No changes recorded"msgstr "Aucune modification enregistrée"+msgid "No changes yet."+msgstr "Aucune modification pour le moment."+msgid "No comments yet. Be the first to add a comment."msgstr "Aucun commentaire pour le moment. Soyez le premier à ajouter un commentaire."@@ -7867,12 +8021,18 @@ msgstr "Aucun jour de congé prévu"msgid "No default attachments yet."msgstr "Aucune pièce jointe par défaut pour le moment."+msgid "No draft make method for this item yet."+msgstr "Aucune méthode de fabrication de brouillon pour cet article pour le moment."+msgid "No draft versions available"msgstr "Aucune version brouillon disponible"msgid "No due date"msgstr "Pas de date d'échéance"+msgid "No editable properties for this item."+msgstr "Aucune propriété modifiable pour cet article."+msgid "No employees assigned yet. Add groups to see status."msgstr "Aucun employé assigné pour le moment. Ajoutez des groupes pour voir le statut."@@ -7897,6 +8057,9 @@ msgstr "Aucun champ trouvé."msgid "No files"msgstr "Aucun fichier"+msgid "No files for this item."+msgstr "Aucun fichier pour cet article."+msgid "No files uploaded"msgstr "Aucun fichier téléchargé"@@ -7933,6 +8096,9 @@ msgstr "Aucune correspondance"msgid "No matches for \"{query}\". Try a different search term."msgstr "Aucune correspondance pour « {query} ». Essayez un terme de recherche différent."+msgid "No matches. Type to create one."+msgstr "Aucune correspondance. Tapez pour en créer une."+msgid "No new notifications"msgstr "Aucune nouvelle notification"@@ -8098,6 +8264,9 @@ msgstr "Pas un tableau mais un solde du grand livre : le coût s'accumule au furmsgid "Not enough jobs to cover quantity"msgstr "Pas assez de tâches pour couvrir la quantité"+msgid "Not referenced anywhere yet."+msgstr "Non référencé nulle part pour le moment."+msgid "Not Required"msgstr "Non requis"@@ -8149,6 +8318,9 @@ msgstr "OEM (fabricant d'équipement d'origine)"msgid "of"msgstr "de"+msgid "Off — released revisions stay editable"+msgstr "Désactivé — les révisions publiées restent modifiables"+msgid "OK"msgstr "OK"@@ -8236,6 +8408,9 @@ msgstr "Oups ! Le lien auquel vous essayez d'accéder n'est pas valide."msgid "Open"msgstr "Ouvrir"+msgid "Open a change order"+msgstr "Ouvrir un ordre de modification"+msgid "Open Actions"msgstr "Actions ouvertes"@@ -8251,6 +8426,9 @@ msgstr "AR ouvert"msgid "Open Audit Log"msgstr "Ouvrir le journal d'audit"+msgid "Open change orders affecting this part"+msgstr "Demandes de modification ouvertes affectant cette pièce"+msgid "Open Date"msgstr "Date d'ouverture"@@ -8504,6 +8682,9 @@ msgstr "Remplacer la méthode de devis par la méthode source"msgid "Overwrite the target manufacturing method with the quote method"msgstr "Remplacer la méthode de fabrication cible par la méthode de devis"+msgid "Owner"+msgstr "Propriétaire"+msgid "Owner (cost center)"msgstr "Centre de coûts parent"@@ -8568,6 +8749,12 @@ msgstr "ID de pièce"msgid "Part is configured for manufacturing"msgstr "La pièce est configurée pour la fabrication"+msgid "Part Number"+msgstr "Numéro de pièce"++msgid "Part Supersession"+msgstr "Remplacement de pièce"+msgid "Partial"msgstr "Partiel"@@ -9531,6 +9718,9 @@ msgstr "Raison"msgid "Reason Account"msgstr "Compte de raison"+msgid "Reason for Change"+msgstr "Raison du changement"+msgid "Reason for declining (Optional)"msgstr "Raison du refus (Facultatif)"@@ -9733,12 +9923,27 @@ msgstr "Chronologie relative · dates à confirmer"msgid "Release"msgstr "Libération"+msgid "Release change order"+msgstr "Publier l'ordre de changement"++msgid "Release control"+msgstr "Contrôle de la version"++msgid "Release Control"+msgstr "Contrôle de la version"+msgid "Release Job"msgstr "Lancer le travail"msgid "Released"msgstr "Libéré"+msgid "Released revision"+msgstr "Révision publiée"++msgid "Released revision is locked"+msgstr "La révision publiée est verrouillée"+msgid "Remaining"msgstr "Restant"@@ -9785,6 +9990,9 @@ msgstr "Supprimer le tri par colonne"msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."msgstr "Supprimez ce type de stockage de toutes les unités de stockage qui le référencent et supprimez-le. Cette action ne peut pas être annulée."+msgid "Removed"+msgstr "Supprimé"+msgid "Rendering label preview..."msgstr "Rendu de l'aperçu de l'étiquette..."@@ -10006,6 +10214,9 @@ msgstr "Taxe de vente d'autoliquidation (défaut)"msgid "Reverse the related journal entries"msgstr "Inverser les écritures comptables associées"+msgid "Review each item's changes, then confirm — releasing can't be undone."+msgstr "Examinez les changements de chaque article, puis confirmez — la publication ne peut pas être annulée."+msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Examinez le bilan et le compte de résultat de la période et confirmez que les chiffres semblent corrects. Ceci est une approbation manuelle — marquez-la comme terminée une fois que vous les avez examinés."@@ -10019,6 +10230,9 @@ msgstr "Révision"msgid "Revision {0}"msgstr "Révision {0}"+msgid "Revisions"+msgstr "Révisions"+msgid "Revoke"msgstr "Révoquer"@@ -11361,6 +11575,9 @@ msgstr "Devis copié avec succès"msgid "Successfully created a new revision"msgstr "Révision créée avec succès"+msgid "Successor effectivity"+msgstr "Effectivité du successeur"+msgid "Successor Effectivity Date"msgstr "Date d'effectivité du successeur"@@ -12432,6 +12649,9 @@ msgstr "Ces informations seront utilisées dans les en-têtes de document"msgid "This information will be visible to all users, so be careful what you share."msgstr "Ces informations seront visibles par tous les utilisateurs, soyez donc prudent dans ce que vous partagez."+msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."+msgstr "Ceci est un article acheté — il n'a pas de BoM/BoP ; seuls ses attributs et documents peuvent changer."+msgid "This is a unique identifier for the webhook"msgstr "Ceci est un identifiant unique pour le webhook"@@ -12489,6 +12709,12 @@ msgstr "Cette période n'a aucune écriture de journal comptabilisée et peut êmsgid "This Quarter"msgstr "Ce trimestre"+msgid "This revision is released (Production). Changes should normally flow through a change order."+msgstr "Cette révision est libérée (Production). Les modifications doivent normalement transiter par un ordre de changement."++msgid "This revision is released (Production). Open a change order to modify it."+msgstr "Cette révision est libérée (Production). Ouvrez un ordre de changement pour la modifier."+msgid "This sales order has associated jobs. Choose what to do with them."msgstr "Cette commande client a des tâches associées. Choisissez ce que vous souhaitez en faire."@@ -12531,6 +12757,9 @@ msgstr "Cela remplacera tous les matériaux de méthode des autres révisions pamsgid "This will replace all method materials of other sizes with this size."msgstr "Cela remplacera tous les matériaux de méthode d'autres tailles par cette taille."+msgid "This will set the current version of the make method to Active, making it read-only."+msgstr "Cela définira la version actuelle de la méthode de fabrication sur Active, la rendant en lecture seule."+msgid "This will write off the remaining book value of the asset."msgstr "Ceci annulera la valeur nette comptable restante de l'actif."@@ -13493,6 +13722,9 @@ msgstr "Entrepôt, Ops"msgid "Warn"msgstr "Avertissement"+msgid "Warn — edits succeed with a warning"+msgstr "Avertissement — les modifications réussissent avec un avertissement"+msgid "Warn but allow"msgstr "Avertir mais autoriser"@@ -13624,6 +13856,9 @@ msgstr "Qu'est-ce que {translatedTerm} ?"msgid "What it is"msgstr "Ce que c'est"+msgid "What kind of change this is: Version updates how the part is made, Revision edits its details and documents, and New Part replaces it with a new part number."+msgstr "Quel type de changement c'est : Version met à jour la façon dont la pièce est fabriquée, Révision édite ses détails et documents, et Nouvelle Pièce la remplace par un nouveau numéro de pièce."+msgid "What kind of output this entry records — Production (good units), Scrap (unrecoverable), or Rework (sent back for correction); reveals Scrap Reason when Scrap."msgstr "Quel type de sortie cette entrée enregistre — Production (bonnes unités), Rebut (irrécupérable) ou Retravail (renvoyé pour correction) ; révèle Scrap Reason quand Rebut."@@ -13783,6 +14018,9 @@ msgstr "Où le nouveau stock de cet article se pose par défaut à la réceptionmsgid "Where stock lives and how it ships."msgstr "Où le stock se trouve et comment il est expédié."+msgid "Where the affected items are used across the system. Informational — nothing here blocks releasing."+msgstr "Où les articles affectés sont utilisés dans le système. Informatif — rien ici ne bloque la publication."+msgid "Where this entry originated (manual entry, posting from sales/purchasing, recurring template, etc.)."msgstr "D'où provient cette entrée (entrée manuelle, comptabilisation de ventes/achats, modèle récurrent, etc.)."@@ -14067,6 +14305,9 @@ msgstr "Vous êtes connecté depuis {hoursElapsed} heures. Avez-vous oublié demsgid "Your books and how money flows."msgstr "Vos livres et la circulation de l'argent."+msgid "Your changes go into a new draft version released with this change order."+msgstr "Vos modifications s'ajoutent à une nouvelle version brouillon livrée avec ce bon de modification."+msgid "Your Console PIN"msgstr "Votre PIN Console"diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.poindex ab1cc3c398..d5be8e63b8 100644--- a/packages/locale/locales/fr/mes.po+++ b/packages/locale/locales/fr/mes.po@@ -610,6 +610,9 @@ msgstr "Aucun impact"msgid "No maintenance scheduled for today"msgstr "Aucune maintenance planifiée pour aujourd'hui"+msgid "No matches. Type to create one."+msgstr "Aucune correspondance. Tapez pour en créer une."+msgid "No materials"msgstr "Aucun matériau"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex ac6858b7e5..687d80a0aa 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -38,6 +38,10 @@ msgstr "\"{taskName}\" पूरा हो गया — इसके सभीmsgid "(excluded for this customer)"msgstr "(इस ग्राहक के लिए बाहर रखा गया)"+#. placeholder {0}: open.length+msgid "{0, plural, one {This part is on 1 open change order} other {This part is on # open change orders}}"+msgstr "{0, plural, one {यह भाग 1 खुले परिवर्तन आदेश पर है} other {यह भाग # खुले परिवर्तन आदेशों पर है}}"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} ग्राहकों के साथ शेष"@@ -211,6 +215,9 @@ msgstr "90 दिन"msgid "A Carbon-run data migration — you load your own data"msgstr "एक कार्बन-चलाया गया डेटा माइग्रेशन — आप अपना डेटा लोड करते हैं"+msgid "A change order tracks a controlled engineering or manufacturing change through review and implementation."+msgstr "एक परिवर्तन आदेश समीक्षा और कार्यान्वयन के माध्यम से नियंत्रित इंजीनियरिंग या विनिर्माण परिवर्तन को ट्रैक करता है।"+msgid "A clearing account holding the value of goods received but not yet billed; the supplier invoice clears it."msgstr "एक क्लीयरिंग खाता जो प्राप्त किए गए लेकिन अभी तक चालान नहीं किए गए सामान का मूल्य रखता है; आपूर्तिकर्ता चालान इसे साफ करता है।"@@ -502,6 +509,9 @@ msgstr "अधिग्रहण लागत"msgid "Acquisition Date"msgstr "अधिग्रहण तारीख"+msgid "Action"+msgstr "कार्रवाई"+msgid "Action Status"msgstr "कार्रवाई स्थिति"@@ -592,6 +602,9 @@ msgstr "कार्य जोड़ें"msgid "Add Adjustment"msgstr "समायोजन जोड़ें"+msgid "Add Affected Item"+msgstr "प्रभावित आइटम जोड़ें"+msgid "Add any notes about your decision..."msgstr "अपने निर्णय के बारे में कोई भी नोट्स जोड़ें..."@@ -670,9 +683,6 @@ msgstr "प्रश्न जोड़ें"msgid "Add Receipt"msgstr "रसीद जोड़ें"-msgid "Add Required Actions"-msgstr "आवश्यक कार्य जोड़ें"-msgid "Add Requirement"msgstr "आवश्यकता जोड़ें"@@ -719,6 +729,9 @@ msgstr "ऐड-ऑन"msgid "Add-On Cost"msgstr "ऐड-ऑन लागत"+msgid "Added"+msgstr "जोड़ा गया"+msgid "Added for this customer"msgstr "इस ग्राहक के लिए जोड़ा गया"@@ -737,9 +750,15 @@ msgstr "पता लाइन 2"msgid "Adjustment Type"msgstr "समायोजन प्रकार"+msgid "Advance to {nextStatus}"+msgstr "{nextStatus} को आगे बढ़ाएं"+msgid "Advanced"msgstr "उन्नत"+msgid "Affected item not found."+msgstr "प्रभावित आइटम नहीं मिला।"+msgid "After"msgstr "के बाद"@@ -846,6 +865,9 @@ msgstr "एक पूंजीकृत वस्तु के लिए एकmsgid "An asset's acquisition cost minus accumulated depreciation — what it's still worth on the books, and the figure it's disposed at."msgstr "एक संपत्ति की अधिग्रहण लागत माइनस संचयी मूल्यह्रास — यह किताबों पर अभी भी क्या मूल्य है और राशि जिस पर इसे निपटाया जाता है।"+msgid "An engineering change: the affected items whose methods are revised on a draft and released together, superseding the versions they replace."+msgstr "एक इंजीनियरिंग परिवर्तन: प्रभावित आइटम जिनकी विधियों को ड्राफ्ट पर संशोधित किया गया है और एक साथ जारी किया गया है, जो वे संस्करणों को प्रतिस्थापित करते हैं।"+msgid "An integration or a custom change — the small slice that's actually custom."msgstr "एक एकीकरण या एक कस्टम परिवर्तन — वह छोटा हिस्सा जो वास्तव में कस्टम है।"@@ -1033,6 +1055,10 @@ msgstr "क्या आप सुनिश्चित हैं कि आपmsgid "Are you sure you want to activate this gauge?."msgstr "क्या आप सुनिश्चित हैं कि आप इस गेज को सक्रिय करना चाहते हैं?"+#. placeholder {0}: routeData?.changeOrder?.changeOrderId ?? ""+msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."+msgstr "क्या आप सुनिश्चित हैं कि आप {0} को रद्द करना चाहते हैं? यह बंद हो जाएगा और जब तक आप इसे फिर से नहीं खोलते तब तक यह केवल पढ़ने के लिए होगा।"+#. placeholder {0}: routeData?.rfqSummary ?.rfqId!msgid "Are you sure you want to cancel {0}? This will also cancel all related supplier quotes."msgstr "क्या आप सुनिश्चित हैं कि आप {0} को रद्द करना चाहते हैं? यह सभी संबंधित आपूर्तिकर्ता उद्धरणों को भी रद्द कर देगा।"@@ -1123,6 +1149,14 @@ msgstr "क्या आप सुनिश्चित हैं कि आपmsgid "Are you sure you want to delete the API key: {0}? This cannot be undone."msgstr "क्या आप सुनिश्चित हैं कि आप API कुंजी को हटाना चाहते हैं: {0}? यह पूर्ववत नहीं किया जा सकता।"+#. placeholder {0}: requiredAction.name+msgid "Are you sure you want to delete the change order action: {0}? This cannot be undone."+msgstr "क्या आप वाकई परिवर्तन आदेश कार्रवाई को हटाना चाहते हैं: {0}? यह पूर्ववत नहीं किया जा सकता।"++#. placeholder {0}: changeOrderType.name+msgid "Are you sure you want to delete the change order category: {0}? This cannot be undone."+msgstr "क्या आप परिवर्तन आदेश श्रेणी को हटाना चाहते हैं: {0}? यह पूर्ववत नहीं किया जा सकता।"+msgid "Are you sure you want to delete the contractor: {name}? This cannot be undone."msgstr "क्या आप सुनिश्चित हैं कि आप ठेकेदार को हटाना चाहते हैं: {name}? यह पूर्ववत नहीं किया जा सकता।"@@ -1281,6 +1315,9 @@ msgstr "क्या आप सुनिश्चित हैं कि आपmsgid "Are you sure you want to delete this approval rule? This cannot be undone."msgstr "क्या आप सुनिश्चित हैं कि आप इस अनुमोदन नियम को हटाना चाहते हैं? यह पूर्ववत नहीं किया जा सकता।"+msgid "Are you sure you want to delete this change order?"+msgstr "क्या आप इस परिवर्तन आदेश को हटाना चाहते हैं?"+msgid "Are you sure you want to delete this gauge?"msgstr "क्या आप सुनिश्चित हैं कि आप इस गेज को हटाना चाहते हैं?"@@ -1893,6 +1930,12 @@ msgstr "इस फ़ाइल को डाउनलोड नहीं करmsgid "Cancel"msgstr "रद्द करें"+msgid "Cancel change order"+msgstr "परिवर्तन आदेश रद्द करें"++msgid "Cancel Change Order"+msgstr "परिवर्तन आदेश रद्द करें"+msgid "Cancel Job"msgstr "नौकरी रद्द करें"@@ -2055,12 +2098,30 @@ msgstr "चैंपियन"msgid "Change"msgstr "बदलें"+msgid "Change order"+msgstr "परिवर्तन आदेश"++msgid "Change Order"+msgstr "परिवर्तन आदेश"++msgid "Change Order Actions"+msgstr "परिवर्तन आदेश कार्रवाई"++msgid "Change Order Types"+msgstr "परिवर्तन आदेश प्रकार"++msgid "Change Orders"+msgstr "परिवर्तन आदेश"+msgid "Change status"msgstr "स्थिति बदलें"msgid "Change the item type (e.g. Part, Material, Tool, etc.)"msgstr "आइटम प्रकार बदलें (जैसे भाग, सामग्री, उपकरण, आदि)"+msgid "Change type"+msgstr "प्रकार परिवर्तित करें"+msgid "Change Type"msgstr "प्रकार बदलें"@@ -2076,6 +2137,9 @@ msgstr "इसे बदलने से मौजूदा विधि अधmsgid "Changing this will update the part ID"msgstr "इसे बदलने से पार्ट ID अपडेट हो जाएगा"+msgid "Changing type resets this item's draft edits."+msgstr "प्रकार बदलने से इस आइटम के ड्राफ्ट संपादन रीसेट हो जाते हैं।"+msgid "Chart of accounts"msgstr "खातों की चार्ट"@@ -2411,6 +2475,9 @@ msgstr "पुष्टि करें"msgid "Confirm {0}"msgstr "की पुष्टि करें {0}"+msgid "Confirm & release"+msgstr "पुष्टि करें और जारी करें"+msgid "Confirm and sign the scope"msgstr "स्कोप की पुष्टि करें और हस्ताक्षर करें"@@ -2549,6 +2616,9 @@ msgstr "नियंत्रक, लेखाकार"msgid "Controls how planning handles a discontinued item: Consume First exhausts on-hand before switching to the successor, Prefer New redirects new demand to the successor immediately, Stock Only keeps only a minimum service reserve, and No Stock drops the item from planning entirely."msgstr "नियंत्रित करता है कि योजना एक बंद की गई वस्तु को कैसे संभालती है: पहले उपभोग करें हाथ पर स्टॉक को समाप्त करता है फिर उत्तराधिकारी पर स्विच करता है, नई को प्राथमिकता दें नई मांग को तुरंत उत्तराधिकारी को पुनर्निर्देशित करता है, केवल स्टॉक केवल न्यूनतम सेवा रिजर्व रखता है, और कोई स्टॉक नहीं वस्तु को योजना से पूरी तरह हटा देता है।"+msgid "Controls whether the bill of material and bill of process of a released (Production) revision can be edited outside a change order."+msgstr "नियंत्रित करता है कि क्या जारी (उत्पादन) संशोधन के सामग्री बिल और प्रक्रिया बिल को परिवर्तन आदेश के बाहर संपादित किया जा सकता है।"+msgid "Convention"msgstr "अभिसम्मति"@@ -2630,6 +2700,9 @@ msgstr "जॉब नंबर कॉपी करें"msgid "Copy link"msgstr "लिंक कॉपी करें"+msgid "Copy link to change order"+msgstr "परिवर्तन आदेश के लिए लिंक कॉपी करें"+msgid "Copy link to consumable"msgstr "उपभोग्य के लिए लिंक कॉपी करें"@@ -2848,6 +2921,9 @@ msgstr "{0} मान बनाएं"msgid "Create & Snapshot"msgstr "बनाएं और स्नैपशॉट लें"+msgid "Create a change order for the new revision and open it"+msgstr "नए संशोधन के लिए एक परिवर्तन आदेश बनाएं और इसे खोलें"+msgid "Create a new kanban card for scan-based replenishment."msgstr "स्कैन-आधारित पुनःपूर्ति के लिए एक नया कानबन कार्ड बनाएं।"@@ -2875,6 +2951,9 @@ msgstr "क्रय आदेश बनाएं और मंजूरी दmsgid "Create audit trail entries"msgstr "ऑडिट ट्रेल प्रविष्टियां बनाएं"+msgid "Create Change Order"+msgstr "परिवर्तन आदेश बनाएं"+msgid "Create Issue"msgstr "समस्या बनाएं"@@ -2932,6 +3011,12 @@ msgstr "बनाया गया"msgid "Created By"msgstr "द्वारा बनाया गया"+msgid "Created change order action"+msgstr "बनाई गई परिवर्तन आदेश कार्रवाई"++msgid "Created change order type"+msgstr "बनाया गया परिवर्तन आदेश प्रकार"+msgid "Created consumable"msgstr "उपभोग्य बनाया गया"@@ -3550,6 +3635,12 @@ msgstr "{periodLabel} हटाएँ"msgid "Delete {storageUnitName}"msgstr "Delete {storageUnitName} को हटाएं"+msgid "Delete action"+msgstr "क्रिया हटाएं"++msgid "Delete Action"+msgstr "कार्रवाई हटाएं"+msgid "Delete API Key"msgstr "API Key हटाएं"@@ -3565,6 +3656,9 @@ msgstr "विशेषता हटाएं"msgid "Delete Category"msgstr "श्रेणी हटाएं"+msgid "Delete Change Order"+msgstr "परिवर्तन आदेश हटाएं"+msgid "Delete Consumable"msgstr "उपभोग्य हटाएं"@@ -3794,6 +3888,9 @@ msgstr "स्थानांतरण हटाएं"msgid "Delete Transfer Line"msgstr "स्थानांतरण लाइन हटाएं"+msgid "Delete Type"+msgstr "प्रकार हटाएं"+msgid "Delete Unit of Measure"msgstr "माप की इकाई हटाएं"@@ -3884,6 +3981,9 @@ msgstr "विवरण"msgid "Description (optional)"msgstr "विवरण (वैकल्पिक)"+msgid "Description of Change"+msgstr "परिवर्तन का विवरण"+msgid "Description of Issue"msgstr "समस्या का विवरण"@@ -3929,6 +4029,9 @@ msgstr "अक्षम"msgid "Discard"msgstr "त्यागें"+msgid "Discontinuation date"+msgstr "बंद करने की तारीख"+msgid "Discontinuation Date"msgstr "बंद करने की तारीख"@@ -4196,6 +4299,9 @@ msgstr "<0>समस्या</0> वर्कफ़्लो संपादिmsgid "Edit Account"msgstr "खाता संपादित करें"+msgid "Edit Action"+msgstr "कार्रवाई संपादित करें"+msgid "Edit API Key"msgstr "API Key संपादित करें"@@ -4217,6 +4323,15 @@ msgstr "विशेषता श्रेणी संपादित करेmsgid "Edit Category"msgstr "श्रेणी संपादित करें"+msgid "Edit Change Order"+msgstr "परिवर्तन आदेश संपादित करें"++msgid "Edit Change Order Action"+msgstr "परिवर्तन आदेश कार्रवाई संपादित करें"++msgid "Edit Change Order Type"+msgstr "परिवर्तन आदेश प्रकार संपादित करें"+msgid "Edit column visibility"msgstr "कॉलम दृश्यता संपादित करें"@@ -4466,6 +4581,9 @@ msgstr "ट्रांसफर संपादित करें"msgid "Edit Transfer Line"msgstr "स्थानांतरण लाइन संपादित करें"+msgid "Edit Type"+msgstr "प्रकार संपादित करें"+msgid "Edit Unit of Measure"msgstr "माप की इकाई संपादित करें"@@ -4583,6 +4701,9 @@ msgstr "पिछली तिमाही का अंत"msgid "End Time"msgstr "समाप्ति समय"+msgid "Enforce — edits are blocked"+msgstr "लागू करें — संपादन अवरुद्ध हैं"+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "रसीदों, शिपमेंट, ट्रांसफर और समायोजन में प्रति-आइटम सत्यापन और दिशानिर्देश लागू करें।"@@ -6004,6 +6125,9 @@ msgstr "II (सामान्य डिफ़ॉल्ट)"msgid "III (tightened)"msgstr "III (कसा हुआ)"+msgid "Impact"+msgstr "प्रभाव"+msgid "Imperial"msgstr "इंपीरियल"@@ -6551,6 +6675,9 @@ msgstr "वर्तमान रखें"msgid "Keep existing pricing, only add new items"msgstr "मौजूदा मूल्य निर्धारण रखें, केवल नई वस्तुएं जोड़ें"+msgid "Keep Open"+msgstr "खुला रखें"+msgid "Key"msgstr "कुंजी"@@ -6655,6 +6782,9 @@ msgstr "किसी भी संबंधित रसीदों को अmsgid "Leave blank for built-in"msgstr "बिल्ट-इन के लिए खाली छोड़ें"+msgid "Leave blank to use the next revision automatically"+msgstr "अगले संशोधन को स्वचालित रूप से उपयोग करने के लिए खाली छोड़ें"+msgid "Leave empty for exact match"msgstr "सटीक मिलान के लिए खाली छोड़ें"@@ -6750,6 +6880,9 @@ msgstr "Linear समस्या को लिंक करें"msgid "Linked entity quantity ({0}) does not match row quantity ({1})."msgstr "लिंक किया गया इकाई मात्रा ({0}) पंक्ति मात्रा ({1}) से मेल नहीं खाती।"+msgid "Linked NCR"+msgstr "जुड़ा हुआ NCR"+msgid "Linked PO"msgstr "लिंक्ड PO"@@ -7352,6 +7485,9 @@ msgstr "जॉब से मॉडल हटाया गया"msgid "Model removed from line"msgstr "मॉडल लाइन से हटाया गया"+msgid "Modified"+msgstr "संशोधित"+msgid "Module"msgstr "मॉड्यूल"@@ -7501,6 +7637,15 @@ msgstr "नई विशेषता"msgid "New Attribute Category"msgstr "नई विशेषता श्रेणी"+msgid "New Change Order"+msgstr "नया परिवर्तन आदेश"++msgid "New Change Order Action"+msgstr "नई परिवर्तन आदेश कार्रवाई"++msgid "New Change Order Type"+msgstr "नया परिवर्तन आदेश प्रकार"+msgid "New Consumable"msgstr "नया उपभोग्य"@@ -7815,6 +7960,12 @@ msgstr "कोई सक्रिय उद्धरण नहीं"msgid "No addresses found"msgstr "कोई पता नहीं मिला"+msgid "No affected items to assess."+msgstr "मूल्यांकन के लिए कोई प्रभावित आइटम नहीं।"++msgid "No affected items."+msgstr "कोई प्रभावित आइटम नहीं।"+msgid "No applications. Payment will be on-account."msgstr "कोई आवेदन नहीं। भुगतान खाते पर होगा।"@@ -7840,6 +7991,9 @@ msgstr "कोई अंशांकन रिकॉर्ड नहीं मmsgid "No changes recorded"msgstr "कोई परिवर्तन दर्ज नहीं किया गया"+msgid "No changes yet."+msgstr "अभी तक कोई परिवर्तन नहीं।"+msgid "No comments yet. Be the first to add a comment."msgstr "अभी तक कोई टिप्पणी नहीं है। टिप्पणी जोड़ने वाले पहले व्यक्ति बनें।"@@ -7867,12 +8021,18 @@ msgstr "कोई दिन बंद निर्धारित नहींmsgid "No default attachments yet."msgstr "अभी तक कोई डिफ़ॉल्ट अटैचमेंट नहीं है।"+msgid "No draft make method for this item yet."+msgstr "इस आइटम के लिए अभी तक कोई ड्राफ्ट विधि नहीं।"+msgid "No draft versions available"msgstr "कोई ड्राफ्ट संस्करण उपलब्ध नहीं है"msgid "No due date"msgstr "कोई नियत तारीख नहीं"+msgid "No editable properties for this item."+msgstr "इस आइटम के लिए कोई संपादन योग्य गुण नहीं।"+msgid "No employees assigned yet. Add groups to see status."msgstr "अभी तक कोई कर्मचारी असाइन नहीं किया गया है। स्थिति देखने के लिए समूह जोड़ें।"@@ -7897,6 +8057,9 @@ msgstr "कोई फ़ील्ड नहीं मिला।"msgid "No files"msgstr "कोई फ़ाइलें नहीं"+msgid "No files for this item."+msgstr "इस आइटम के लिए कोई फ़ाइल नहीं।"+msgid "No files uploaded"msgstr "कोई फ़ाइल अपलोड नहीं की गई"@@ -7933,6 +8096,9 @@ msgstr "कोई मेल नहीं"msgid "No matches for \"{query}\". Try a different search term."msgstr "\"{query}\" के लिए कोई मिलान नहीं। एक अलग खोज शब्द आजमाएं।"+msgid "No matches. Type to create one."+msgstr "कोई मेल नहीं। एक बनाने के लिए टाइप करें।"+msgid "No new notifications"msgstr "कोई नई सूचनाएं नहीं"@@ -8098,6 +8264,9 @@ msgstr "एक तालिका नहीं बल्कि एक सामmsgid "Not enough jobs to cover quantity"msgstr "पर्याप्त नौकरियां नहीं हैं मात्रा को कवर करने के लिए"+msgid "Not referenced anywhere yet."+msgstr "अभी तक कहीं भी संदर्भित नहीं।"+msgid "Not Required"msgstr "आवश्यक नहीं"@@ -8149,6 +8318,9 @@ msgstr "OEM (मूल उपकरण निर्माता)"msgid "of"msgstr "का"+msgid "Off — released revisions stay editable"+msgstr "बंद — जारी किए गए संशोधन संपादन योग्य रहते हैं"+msgid "OK"msgstr "ठीक है"@@ -8236,6 +8408,9 @@ msgstr "अरे! आप जिस लिंक को एक्सेस कmsgid "Open"msgstr "खोलें"+msgid "Open a change order"+msgstr "एक परिवर्तन आदेश खोलें"+msgid "Open Actions"msgstr "खुली कार्रवाइयाँ"@@ -8251,6 +8426,9 @@ msgstr "खुला AR"msgid "Open Audit Log"msgstr "ऑडिट लॉग खोलें"+msgid "Open change orders affecting this part"+msgstr "इस हिस्से को प्रभावित करने वाले खुले परिवर्तन आदेश"+msgid "Open Date"msgstr "खुली तारीख"@@ -8504,6 +8682,9 @@ msgstr "उद्धरण विधि को स्रोत विधि सmsgid "Overwrite the target manufacturing method with the quote method"msgstr "उद्धरण विधि के साथ लक्ष्य विनिर्माण विधि को अधिलेखित करें"+msgid "Owner"+msgstr "मालिक"+msgid "Owner (cost center)"msgstr "मूल लागत केंद्र"@@ -8568,6 +8749,12 @@ msgstr "पार्ट आईडी"msgid "Part is configured for manufacturing"msgstr "भाग विनिर्माण के लिए कॉन्फ़िगर किया गया है"+msgid "Part Number"+msgstr "भाग संख्या"++msgid "Part Supersession"+msgstr "भाग प्रतिस्थापन"+msgid "Partial"msgstr "आंशिक"@@ -9531,6 +9718,9 @@ msgstr "कारण"msgid "Reason Account"msgstr "कारण खाता"+msgid "Reason for Change"+msgstr "परिवर्तन का कारण"+msgid "Reason for declining (Optional)"msgstr "अस्वीकार करने का कारण (वैकल्पिक)"@@ -9733,12 +9923,27 @@ msgstr "सापेक्ष समयरेखा · तारीखें पmsgid "Release"msgstr "रिलीज़"+msgid "Release change order"+msgstr "परिवर्तन आदेश जारी करें"++msgid "Release control"+msgstr "जारी करने का नियंत्रण"++msgid "Release Control"+msgstr "जारी करने का नियंत्रण"+msgid "Release Job"msgstr "जॉब रिलीज़ करें"msgid "Released"msgstr "जारी किया गया"+msgid "Released revision"+msgstr "जारी किया गया संशोधन"++msgid "Released revision is locked"+msgstr "जारी किया गया संशोधन लॉक किया गया है"+msgid "Remaining"msgstr "शेष"@@ -9785,6 +9990,9 @@ msgstr "कॉलम द्वारा सॉर्ट हटाएं"msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."msgstr "इस स्टोरेज प्रकार को सभी संदर्भित स्टोरेज इकाइयों से हटाएं और इसे हटाएं। यह पूर्ववत नहीं किया जा सकता।"+msgid "Removed"+msgstr "हटाया गया"+msgid "Rendering label preview..."msgstr "लेबल पूर्वावलोकन प्रस्तुत किया जा रहा है..."@@ -10006,6 +10214,9 @@ msgstr "रिवर्स चार्ज बिक्रय कर (डिफmsgid "Reverse the related journal entries"msgstr "संबंधित जर्नल प्रविष्टियों को उलट दें"+msgid "Review each item's changes, then confirm — releasing can't be undone."+msgstr "प्रत्येक आइटम के परिवर्तनों की समीक्षा करें, फिर पुष्टि करें — जारी करना वापस नहीं किया जा सकता।"+msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "अवधि की बैलेंस शीट और आय विवरण की समीक्षा करें और पुष्टि करें कि आंकड़े सही लगते हैं। यह एक मैनुअल साइन-ऑफ है — एक बार समीक्षा करने के बाद इसे पूर्ण चिह्नित करें।"@@ -10019,6 +10230,9 @@ msgstr "संस्करण"msgid "Revision {0}"msgstr "संस्करण {0}"+msgid "Revisions"+msgstr "संशोधन"+msgid "Revoke"msgstr "रद्द करें"@@ -11361,6 +11575,9 @@ msgstr "सफलतापूर्वक उद्धरण की प्रतmsgid "Successfully created a new revision"msgstr "सफलतापूर्वक एक नया संशोधन बनाया गया"+msgid "Successor effectivity"+msgstr "उत्तराधिकारी प्रभावशीलता"+msgid "Successor Effectivity Date"msgstr "उत्तराधिकारी प्रभावी तारीख"@@ -12432,6 +12649,9 @@ msgstr "यह जानकारी दस्तावेज़ शीर्षmsgid "This information will be visible to all users, so be careful what you share."msgstr "यह जानकारी सभी उपयोगकर्ताओं को दिखाई देगी, इसलिए सावधान रहें कि आप क्या साझा करते हैं।"+msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."+msgstr "यह एक खरीदा गया आइटम है — इसके पास कोई BoM/BoP नहीं है; केवल इसकी विशेषताओं और दस्तावेजों को बदला जा सकता है।"+msgid "This is a unique identifier for the webhook"msgstr "यह वेबहुक के लिए एक अद्वितीय पहचानकर्ता है"@@ -12489,6 +12709,12 @@ msgstr "इस अवधि में कोई जर्नल प्रविmsgid "This Quarter"msgstr "इस त्रैमासिक"+msgid "This revision is released (Production). Changes should normally flow through a change order."+msgstr "यह संशोधन जारी है (Production)। परिवर्तन सामान्यतः एक चेंज ऑर्डर के माध्यम से होने चाहिए।"++msgid "This revision is released (Production). Open a change order to modify it."+msgstr "यह संशोधन जारी है (Production)। इसे संशोधित करने के लिए एक चेंज ऑर्डर खोलें।"+msgid "This sales order has associated jobs. Choose what to do with them."msgstr "इस बिक्रय आदेश के संबंधित कार्य हैं। उनके साथ क्या करना है यह चुनें।"@@ -12531,6 +12757,9 @@ msgstr "यह अन्य संशोधनों की सभी विधmsgid "This will replace all method materials of other sizes with this size."msgstr "यह अन्य आकारों की सभी विधि सामग्रियों को इस आकार से बदल देगा।"+msgid "This will set the current version of the make method to Active, making it read-only."+msgstr "यह make विधि के वर्तमान संस्करण को सक्रिय के रूप में सेट करेगा, जिससे यह केवल-पढ़ने योग्य हो जाएगा।"+msgid "This will write off the remaining book value of the asset."msgstr "यह संपत्ति के शेष बही मूल्य को लिख देगा।"@@ -13493,6 +13722,9 @@ msgstr "गोदाम, संचालन"msgid "Warn"msgstr "चेतावनी"+msgid "Warn — edits succeed with a warning"+msgstr "चेतावनी — संपादन एक चेतावनी के साथ सफल होता है"+msgid "Warn but allow"msgstr "चेतावनी दें लेकिन अनुमति दें"@@ -13624,6 +13856,9 @@ msgstr "{translatedTerm} क्या है?"msgid "What it is"msgstr "यह क्या है"+msgid "What kind of change this is: Version updates how the part is made, Revision edits its details and documents, and New Part replaces it with a new part number."+msgstr "यह किस प्रकार का परिवर्तन है: संस्करण अपडेट करता है कि भाग कैसे बनाया जाता है, संशोधन इसके विवरण और दस्तावेज़ों को संपादित करता है, और नया भाग इसे एक नए भाग संख्या से बदल देता है।"+msgid "What kind of output this entry records — Production (good units), Scrap (unrecoverable), or Rework (sent back for correction); reveals Scrap Reason when Scrap."msgstr "यह प्रविष्टि किस प्रकार का आउटपुट रिकॉर्ड करती है — उत्पादन (अच्छी इकाइयाँ), स्क्रैप (अपूरणीय) या पुनः कार्य (सुधार के लिए वापस भेजा गया); जब स्क्रैप हो तो स्क्रैप कारण प्रकट करता है।"@@ -13783,6 +14018,9 @@ msgstr "जहां इस आइटम की नई स्टॉक डिफmsgid "Where stock lives and how it ships."msgstr "स्टॉक कहाँ रहता है और यह कैसे भेजा जाता है।"+msgid "Where the affected items are used across the system. Informational — nothing here blocks releasing."+msgstr "जहां प्रभावित आइटम पूरे सिस्टम में उपयोग किए जाते हैं। सूचनात्मक — यहां कुछ भी जारी करने में बाधा नहीं डालता।"+msgid "Where this entry originated (manual entry, posting from sales/purchasing, recurring template, etc.)."msgstr "यह प्रविष्टि कहाँ से उत्पन्न हुई (मैनुअल प्रविष्टि, बिक्रय/खरीद से पोस्टिंग, पुनरावर्ती टेम्पलेट, आदि)।"@@ -14067,6 +14305,9 @@ msgstr "आप {hoursElapsed} घंटे के लिए क्लॉक इmsgid "Your books and how money flows."msgstr "आपकी किताबें और पैसा कैसे बहता है।"+msgid "Your changes go into a new draft version released with this change order."+msgstr "आपके परिवर्तन इस परिवर्तन आदेश के साथ जारी एक नए ड्राफ्ट संस्करण में जाते हैं।"+msgid "Your Console PIN"msgstr "आपका कंसोल PIN"diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.poindex ff34545641..4e60890600 100644--- a/packages/locale/locales/hi/mes.po+++ b/packages/locale/locales/hi/mes.po@@ -610,6 +610,9 @@ msgstr "कोई प्रभाव नहीं"msgid "No maintenance scheduled for today"msgstr "आज के लिए कोई रखरखाव निर्धारित नहीं है"+msgid "No matches. Type to create one."+msgstr "कोई मेल नहीं। एक बनाने के लिए टाइप करें।"+msgid "No materials"msgstr "कोई सामग्री नहीं"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex b50c9b2bb3..4b1e8e3e34 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -38,6 +38,10 @@ msgstr "\"{taskName}\" è completato — tutti i {0} elementi della Setup Map somsgid "(excluded for this customer)"msgstr "(escluso per questo cliente)"+#. placeholder {0}: open.length+msgid "{0, plural, one {This part is on 1 open change order} other {This part is on # open change orders}}"+msgstr "{0, plural, one {Questa parte è in 1 ordine di modifica aperto} other {Questa parte è in # ordini di modifica aperti}}"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} clienti con saldo"@@ -211,6 +215,9 @@ msgstr "90 giorni"msgid "A Carbon-run data migration — you load your own data"msgstr "Una migrazione dati gestita da Carbon — tu carichi i tuoi dati"+msgid "A change order tracks a controlled engineering or manufacturing change through review and implementation."+msgstr "Un ordine di modifica traccia una modifica ingegneristica o manifatturiera controllata attraverso la revisione e l'implementazione."+msgid "A clearing account holding the value of goods received but not yet billed; the supplier invoice clears it."msgstr "Un conto di compensazione che tiene il valore della merce ricevuta ma non ancora fatturata; la fattura del fornitore la compensa."@@ -502,6 +509,9 @@ msgstr "Costo di acquisizione"msgid "Acquisition Date"msgstr "Data di acquisizione"+msgid "Action"+msgstr "Azione"+msgid "Action Status"msgstr "Stato Azione"@@ -592,6 +602,9 @@ msgstr "Aggiungi Azioni"msgid "Add Adjustment"msgstr "Aggiungi rettifica"+msgid "Add Affected Item"+msgstr "Aggiungi elemento interessato"+msgid "Add any notes about your decision..."msgstr "Aggiungi eventuali note sulla tua decisione..."@@ -670,9 +683,6 @@ msgstr "Aggiungi Domanda"msgid "Add Receipt"msgstr "Aggiungi Ricevuta"-msgid "Add Required Actions"-msgstr "Aggiungi Azioni Richieste"-msgid "Add Requirement"msgstr "Aggiungi Requisito"@@ -719,6 +729,9 @@ msgstr "Componente aggiuntivo"msgid "Add-On Cost"msgstr "Costo Aggiuntivo"+msgid "Added"+msgstr "Aggiunto"+msgid "Added for this customer"msgstr "Aggiunto per questo cliente"@@ -737,9 +750,15 @@ msgstr "Indirizzo Linea 2"msgid "Adjustment Type"msgstr "Tipo di Rettifica"+msgid "Advance to {nextStatus}"+msgstr "Procedi a {nextStatus}"+msgid "Advanced"msgstr "Avanzate"+msgid "Affected item not found."+msgstr "Elemento interessato non trovato."+msgid "After"msgstr "Dopo"@@ -846,6 +865,9 @@ msgstr "Un record contabile per un elemento capitalizzato che ammortizzi anzichmsgid "An asset's acquisition cost minus accumulated depreciation — what it's still worth on the books, and the figure it's disposed at."msgstr "Il costo di acquisizione di un asset meno l'ammortamento cumulato — quello che vale ancora sui libri e l'importo a cui viene ceduto."+msgid "An engineering change: the affected items whose methods are revised on a draft and released together, superseding the versions they replace."+msgstr "Una modifica ingegneristica: gli elementi interessati i cui metodi vengono rivisti in una bozza e rilasciati insieme, sostituendo le versioni che sostituiscono."+msgid "An integration or a custom change — the small slice that's actually custom."msgstr "Un'integrazione o una modifica personalizzata — la piccola parte che è effettivamente personalizzata."@@ -1033,6 +1055,10 @@ msgstr "Sei sicuro di voler attivare il processo: {name}? Apparirà di nuovo neimsgid "Are you sure you want to activate this gauge?."msgstr "Sei sicuro di voler attivare questo calibro?."+#. placeholder {0}: routeData?.changeOrder?.changeOrderId ?? ""+msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."+msgstr "Sei sicuro di voler cancellare {0}? Sarà chiuso e in sola lettura fino a quando non lo riapri."+#. placeholder {0}: routeData?.rfqSummary ?.rfqId!msgid "Are you sure you want to cancel {0}? This will also cancel all related supplier quotes."msgstr "Sei sicuro di voler annullare {0}? Questo annullerà anche tutte le quotazioni dei fornitori correlate."@@ -1123,6 +1149,14 @@ msgstr "Sei sicuro di voler eliminare l'account: {0}{1}? Questa azione non puòmsgid "Are you sure you want to delete the API key: {0}? This cannot be undone."msgstr "Sei sicuro di voler eliminare la chiave API: {0}? Questa azione non può essere annullata."+#. placeholder {0}: requiredAction.name+msgid "Are you sure you want to delete the change order action: {0}? This cannot be undone."+msgstr "Sei sicuro di voler eliminare l'azione dell'ordine di modifica: {0}? Non è possibile annullare."++#. placeholder {0}: changeOrderType.name+msgid "Are you sure you want to delete the change order category: {0}? This cannot be undone."+msgstr "Sei sicuro di voler eliminare la categoria di ordine di modifica: {0}? Questa azione non può essere annullata."+msgid "Are you sure you want to delete the contractor: {name}? This cannot be undone."msgstr "Sei sicuro di voler eliminare l'appaltatore: {name}? Questa azione non può essere annullata."@@ -1281,6 +1315,9 @@ msgstr "Sei sicuro di voler eliminare il webhook: {0}? Questa azione non può esmsgid "Are you sure you want to delete this approval rule? This cannot be undone."msgstr "Sei sicuro di voler eliminare questa regola di approvazione? Questa azione non può essere annullata."+msgid "Are you sure you want to delete this change order?"+msgstr "Sei sicuro di voler eliminare questo ordine di modifica?"+msgid "Are you sure you want to delete this gauge?"msgstr "Sei sicuro di voler eliminare questo calibro?"@@ -1893,6 +1930,12 @@ msgstr "Impossibile scaricare questo file"msgid "Cancel"msgstr "Annulla"+msgid "Cancel change order"+msgstr "Annulla ordine di modifica"++msgid "Cancel Change Order"+msgstr "Annulla Ordine di Modifica"+msgid "Cancel Job"msgstr "Annulla Lavoro"@@ -2055,12 +2098,30 @@ msgstr "Campioni"msgid "Change"msgstr "Cambia"+msgid "Change order"+msgstr "Ordine di modifica"++msgid "Change Order"+msgstr "Ordine di Modifica"++msgid "Change Order Actions"+msgstr "Azioni dell'ordine di modifica"++msgid "Change Order Types"+msgstr "Tipi di Ordini di Modifica"++msgid "Change Orders"+msgstr "Ordini di Modifica"+msgid "Change status"msgstr "Cambia stato"msgid "Change the item type (e.g. Part, Material, Tool, etc.)"msgstr "Cambia il tipo di articolo (ad es. Parte, Materiale, Strumento, ecc.)"+msgid "Change type"+msgstr "Tipo di modifica"+msgid "Change Type"msgstr "Cambia Tipo"@@ -2076,6 +2137,9 @@ msgstr "Modificare questo sovrascriverà il metodo esistente"msgid "Changing this will update the part ID"msgstr "Modificare questo aggiornerà l'ID della parte"+msgid "Changing type resets this item's draft edits."+msgstr "Cambiare il tipo ripristina le modifiche in bozza di questo elemento."+msgid "Chart of accounts"msgstr "Piano dei conti"@@ -2411,6 +2475,9 @@ msgstr "Conferma"msgid "Confirm {0}"msgstr "Conferma {0}"+msgid "Confirm & release"+msgstr "Conferma e rilascia"+msgid "Confirm and sign the scope"msgstr "Conferma e firma l'ambito"@@ -2549,6 +2616,9 @@ msgstr "Controllore, Contabile"msgid "Controls how planning handles a discontinued item: Consume First exhausts on-hand before switching to the successor, Prefer New redirects new demand to the successor immediately, Stock Only keeps only a minimum service reserve, and No Stock drops the item from planning entirely."msgstr "Controlla come la pianificazione gestisce un articolo discontinuo: Consuma Prima esaurisce le scorte disponibili prima di passare al successore, Preferisci Nuovo reindirizza immediatamente la nuova domanda al successore, Solo Stock mantiene solo una riserva di servizio minima e Nessuno Stock rimuove completamente l'articolo dalla pianificazione."+msgid "Controls whether the bill of material and bill of process of a released (Production) revision can be edited outside a change order."+msgstr "Controlla se la distinta base e il foglio di lavoro di una revisione rilasciata (Produzione) possono essere modificati al di fuori di un ordine di modifica."+msgid "Convention"msgstr "Convenzione"@@ -2630,6 +2700,9 @@ msgstr "Copia numero lavoro"msgid "Copy link"msgstr "Copia link"+msgid "Copy link to change order"+msgstr "Copia link all'ordine di modifica"+msgid "Copy link to consumable"msgstr "Copia il collegamento al consumabile"@@ -2848,6 +2921,9 @@ msgstr "Crea {0} valori"msgid "Create & Snapshot"msgstr "Crea e Snapshot"+msgid "Create a change order for the new revision and open it"+msgstr "Crea un ordine di modifica per la nuova revisione e aprilo"+msgid "Create a new kanban card for scan-based replenishment."msgstr "Crea una nuova scheda kanban per il rifornimento basato su scansione."@@ -2875,6 +2951,9 @@ msgstr "Creare e approvare ordini di acquisto"msgid "Create audit trail entries"msgstr "Crea voci di audit trail"+msgid "Create Change Order"+msgstr "Crea Ordine di Modifica"+msgid "Create Issue"msgstr "Crea Problema"@@ -2932,6 +3011,12 @@ msgstr "Creato il"msgid "Created By"msgstr "Creato da"+msgid "Created change order action"+msgstr "Azione dell'ordine di modifica creata"++msgid "Created change order type"+msgstr "Tipo di ordine di modifica creato"+msgid "Created consumable"msgstr "Consumabile creato"@@ -3550,6 +3635,12 @@ msgstr "Elimina {periodLabel}"msgid "Delete {storageUnitName}"msgstr "Elimina {storageUnitName}"+msgid "Delete action"+msgstr "Elimina azione"++msgid "Delete Action"+msgstr "Elimina azione"+msgid "Delete API Key"msgstr "Elimina Chiave API"@@ -3565,6 +3656,9 @@ msgstr "Elimina Attributo"msgid "Delete Category"msgstr "Elimina Categoria"+msgid "Delete Change Order"+msgstr "Elimina Ordine di Modifica"+msgid "Delete Consumable"msgstr "Elimina Consumabile"@@ -3794,6 +3888,9 @@ msgstr "Elimina Trasferimento"msgid "Delete Transfer Line"msgstr "Elimina Riga di Trasferimento"+msgid "Delete Type"+msgstr "Elimina Tipo"+msgid "Delete Unit of Measure"msgstr "Elimina unità di misura"@@ -3884,6 +3981,9 @@ msgstr "Descrizione"msgid "Description (optional)"msgstr "Descrizione (facoltativa)"+msgid "Description of Change"+msgstr "Descrizione della Modifica"+msgid "Description of Issue"msgstr "Descrizione del Problema"@@ -3929,6 +4029,9 @@ msgstr "Disabilitato"msgid "Discard"msgstr "Scarta"+msgid "Discontinuation date"+msgstr "Data di interruzione"+msgid "Discontinuation Date"msgstr "Data di interruzione"@@ -4196,6 +4299,9 @@ msgstr "Modifica Flusso di Lavoro <0>Problema</0>"msgid "Edit Account"msgstr "Modifica Account"+msgid "Edit Action"+msgstr "Modifica azione"+msgid "Edit API Key"msgstr "Modifica Chiave API"@@ -4217,6 +4323,15 @@ msgstr "Modifica Categoria Attributo"msgid "Edit Category"msgstr "Modifica Categoria"+msgid "Edit Change Order"+msgstr "Modifica Ordine di Modifica"++msgid "Edit Change Order Action"+msgstr "Modifica azione dell'ordine di modifica"++msgid "Edit Change Order Type"+msgstr "Modifica Tipo di Ordine di Modifica"+msgid "Edit column visibility"msgstr "Modifica visibilità colonna"@@ -4466,6 +4581,9 @@ msgstr "Modifica Trasferimento"msgid "Edit Transfer Line"msgstr "Modifica Riga Trasferimento"+msgid "Edit Type"+msgstr "Modifica Tipo"+msgid "Edit Unit of Measure"msgstr "Modifica Unità di Misura"@@ -4583,6 +4701,9 @@ msgstr "Fine dell'ultimo trimestre"msgid "End Time"msgstr "Ora di fine"+msgid "Enforce — edits are blocked"+msgstr "Applica — le modifiche sono bloccate"+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Applica la convalida per articolo e le linee guida su ricevute, spedizioni, trasferimenti e rettifiche."@@ -6004,6 +6125,9 @@ msgstr "II (normale predefinito)"msgid "III (tightened)"msgstr "III (stretto)"+msgid "Impact"+msgstr "Impatto"+msgid "Imperial"msgstr "Imperiale"@@ -6551,6 +6675,9 @@ msgstr "Mantieni Attuale"msgid "Keep existing pricing, only add new items"msgstr "Mantieni i prezzi esistenti, aggiungi solo i nuovi articoli"+msgid "Keep Open"+msgstr "Mantieni Aperto"+msgid "Key"msgstr "Chiave"@@ -6655,6 +6782,9 @@ msgstr "Lasciare le ricevute correlate intatte"msgid "Leave blank for built-in"msgstr "Lascia vuoto per built-in"+msgid "Leave blank to use the next revision automatically"+msgstr "Lascia vuoto per usare la prossima revisione automaticamente"+msgid "Leave empty for exact match"msgstr "Lascia vuoto per una corrispondenza esatta"@@ -6750,6 +6880,9 @@ msgstr "Collega problema Linear"msgid "Linked entity quantity ({0}) does not match row quantity ({1})."msgstr "La quantità dell'entità collegata ({0}) non corrisponde alla quantità della riga ({1})."+msgid "Linked NCR"+msgstr "NCR collegato"+msgid "Linked PO"msgstr "PO collegato"@@ -7352,6 +7485,9 @@ msgstr "Modello rimosso dal lavoro"msgid "Model removed from line"msgstr "Modello rimosso dalla riga"+msgid "Modified"+msgstr "Modificato"+msgid "Module"msgstr "Modulo"@@ -7501,6 +7637,15 @@ msgstr "Nuovo Attributo"msgid "New Attribute Category"msgstr "Nuova Categoria Attributo"+msgid "New Change Order"+msgstr "Nuovo Ordine di Modifica"++msgid "New Change Order Action"+msgstr "Nuova azione dell'ordine di modifica"++msgid "New Change Order Type"+msgstr "Nuovo Tipo di Ordine di Modifica"+msgid "New Consumable"msgstr "Nuovo Consumabile"@@ -7815,6 +7960,12 @@ msgstr "Nessuna Quotazione Attiva"msgid "No addresses found"msgstr "Nessun indirizzo trovato"+msgid "No affected items to assess."+msgstr "Nessun elemento interessato da valutare."++msgid "No affected items."+msgstr "Nessun elemento interessato."+msgid "No applications. Payment will be on-account."msgstr "Nessuna applicazione. Il pagamento sarà a conto."@@ -7840,6 +7991,9 @@ msgstr "Nessun record di calibrazione trovato"msgid "No changes recorded"msgstr "Nessuna modifica registrata"+msgid "No changes yet."+msgstr "Nessuna modifica ancora."+msgid "No comments yet. Be the first to add a comment."msgstr "Nessun commento ancora. Sii il primo ad aggiungere un commento."@@ -7867,12 +8021,18 @@ msgstr "Nessun giorno libero programmato"msgid "No default attachments yet."msgstr "Nessun allegato predefinito ancora."+msgid "No draft make method for this item yet."+msgstr "Nessun metodo di creazione della bozza per questo elemento ancora."+msgid "No draft versions available"msgstr "Nessuna versione bozza disponibile"msgid "No due date"msgstr "Nessuna data di scadenza"+msgid "No editable properties for this item."+msgstr "Nessuna proprietà modificabile per questo elemento."+msgid "No employees assigned yet. Add groups to see status."msgstr "Nessun dipendente assegnato ancora. Aggiungi gruppi per visualizzare lo stato."@@ -7897,6 +8057,9 @@ msgstr "Nessun campo trovato."msgid "No files"msgstr "Nessun file"+msgid "No files for this item."+msgstr "Nessun file per questo elemento."+msgid "No files uploaded"msgstr "Nessun file caricato"@@ -7933,6 +8096,9 @@ msgstr "Nessuna corrispondenza"msgid "No matches for \"{query}\". Try a different search term."msgstr "Nessuna corrispondenza per \"{query}\". Prova un termine di ricerca diverso."+msgid "No matches. Type to create one."+msgstr "Nessuna corrispondenza. Digita per crearne uno."+msgid "No new notifications"msgstr "Nessuna nuova notifica"@@ -8098,6 +8264,9 @@ msgstr "Non una tabella ma un saldo del libro mastro: il costo si accumula quandmsgid "Not enough jobs to cover quantity"msgstr "Non ci sono abbastanza lavori per coprire la quantità"+msgid "Not referenced anywhere yet."+msgstr "Non referenziato da nessuna parte ancora."+msgid "Not Required"msgstr "Non richiesto"@@ -8149,6 +8318,9 @@ msgstr "OEM (Original Equipment Manufacturer)"msgid "of"msgstr "di"+msgid "Off — released revisions stay editable"+msgstr "Disattivato — le revisioni rilasciate rimangono modificabili"+msgid "OK"msgstr "OK"@@ -8236,6 +8408,9 @@ msgstr "Oops! Il link che stai cercando di accedere non è valido."msgid "Open"msgstr "Apri"+msgid "Open a change order"+msgstr "Apri un ordine di modifica"+msgid "Open Actions"msgstr "Azioni Aperte"@@ -8251,6 +8426,9 @@ msgstr "AR aperto"msgid "Open Audit Log"msgstr "Apri Registro di Audit"+msgid "Open change orders affecting this part"+msgstr "Ordini di modifica aperti che interessano questa parte"+msgid "Open Date"msgstr "Data di apertura"@@ -8504,6 +8682,9 @@ msgstr "Sovrascrivi il metodo di preventivo con il metodo di origine"msgid "Overwrite the target manufacturing method with the quote method"msgstr "Sovrascrivi il metodo di produzione target con il metodo di quotazione"+msgid "Owner"+msgstr "Proprietario"+msgid "Owner (cost center)"msgstr "Centro di costo principale"@@ -8568,6 +8749,12 @@ msgstr "ID Parte"msgid "Part is configured for manufacturing"msgstr "La parte è configurata per la produzione"+msgid "Part Number"+msgstr "Numero componente"++msgid "Part Supersession"+msgstr "Sostituzione Pezzo"+msgid "Partial"msgstr "Parziale"@@ -9531,6 +9718,9 @@ msgstr "Motivo"msgid "Reason Account"msgstr "Conto Motivo"+msgid "Reason for Change"+msgstr "Motivo della Modifica"+msgid "Reason for declining (Optional)"msgstr "Motivo del rifiuto (Facoltativo)"@@ -9733,12 +9923,27 @@ msgstr "Cronologia relativa · date da confermare"msgid "Release"msgstr "Rilascio"+msgid "Release change order"+msgstr "Rilascia ordine di modifica"++msgid "Release control"+msgstr "Controllo rilascio"++msgid "Release Control"+msgstr "Controllo Rilascio"+msgid "Release Job"msgstr "Rilascia Commessa"msgid "Released"msgstr "Rilasciato"+msgid "Released revision"+msgstr "Revisione rilasciata"++msgid "Released revision is locked"+msgstr "La revisione rilasciata è bloccata"+msgid "Remaining"msgstr "Rimanente"@@ -9785,6 +9990,9 @@ msgstr "Rimuovi ordinamento per colonna"msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."msgstr "Rimuovi questo tipo di archiviazione da tutte le unità di archiviazione che lo referenziano ed eliminalo. Questa azione non può essere annullata."+msgid "Removed"+msgstr "Rimosso"+msgid "Rendering label preview..."msgstr "Rendering dell'anteprima dell'etichetta..."@@ -10006,6 +10214,9 @@ msgstr "Imposta di vendita con inversione contabile (predefinito)"msgid "Reverse the related journal entries"msgstr "Storna le relative registrazioni contabili"+msgid "Review each item's changes, then confirm — releasing can't be undone."+msgstr "Rivedi i cambiamenti di ogni elemento, poi conferma — il rilascio non può essere annullato."+msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Rivedi il bilancio e il conto economico del periodo e conferma che i dati sembrino corretti. Questo è un completamento manuale — contrassegnalo come eseguito una volta revisionati."@@ -10019,6 +10230,9 @@ msgstr "Revisione"msgid "Revision {0}"msgstr "Revisione {0}"+msgid "Revisions"+msgstr "Revisioni"+msgid "Revoke"msgstr "Revoca"@@ -11361,6 +11575,9 @@ msgstr "Preventivo copiato con successo"msgid "Successfully created a new revision"msgstr "Revisione creata con successo"+msgid "Successor effectivity"+msgstr "Data di efficacia del successore"+msgid "Successor Effectivity Date"msgstr "Data di Efficacia del Successore"@@ -12432,6 +12649,9 @@ msgstr "Queste informazioni verranno utilizzate nelle intestazioni dei documentimsgid "This information will be visible to all users, so be careful what you share."msgstr "Queste informazioni saranno visibili a tutti gli utenti, quindi fai attenzione a ciò che condividi."+msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."+msgstr "Questo è un elemento acquistato — non ha BoM/BoP; solo i suoi attributi e documenti possono cambiare."+msgid "This is a unique identifier for the webhook"msgstr "Questo è un identificatore univoco per il webhook"@@ -12489,6 +12709,12 @@ msgstr "Questo periodo non ha movimenti di diario registrati e può essere elimimsgid "This Quarter"msgstr "Questo Trimestre"+msgid "This revision is released (Production). Changes should normally flow through a change order."+msgstr "Questa revisione è rilasciata (Produzione). Le modifiche dovrebbero normalmente fluire attraverso un ordine di modifica."++msgid "This revision is released (Production). Open a change order to modify it."+msgstr "Questa revisione è rilasciata (Produzione). Aprire un ordine di modifica per modificarla."+msgid "This sales order has associated jobs. Choose what to do with them."msgstr "Questo ordine di vendita ha processi associati. Scegli cosa fare con loro."@@ -12531,6 +12757,9 @@ msgstr "Questo sostituirà tutti i materiali del metodo di altre revisioni con qmsgid "This will replace all method materials of other sizes with this size."msgstr "Questo sostituirà tutti i materiali del metodo di altre dimensioni con questa dimensione."+msgid "This will set the current version of the make method to Active, making it read-only."+msgstr "Questo imposterà la versione corrente del metodo di produzione su Attivo, rendendola di sola lettura."+msgid "This will write off the remaining book value of the asset."msgstr "Questo cancellerà il valore netto contabile rimanente dell'asset."@@ -13493,6 +13722,9 @@ msgstr "Magazzino, Ops"msgid "Warn"msgstr "Avviso"+msgid "Warn — edits succeed with a warning"+msgstr "Avviso — le modifiche hanno successo con un avviso"+msgid "Warn but allow"msgstr "Avvisa ma consenti"@@ -13624,6 +13856,9 @@ msgstr "Cos'è {translatedTerm}?"msgid "What it is"msgstr "Che cos'è"+msgid "What kind of change this is: Version updates how the part is made, Revision edits its details and documents, and New Part replaces it with a new part number."+msgstr "Che tipo di cambiamento è: Version aggiorna come la parte è realizzata, Revision modifica i suoi dettagli e documenti, e New Part la sostituisce con un nuovo numero di parte."+msgid "What kind of output this entry records — Production (good units), Scrap (unrecoverable), or Rework (sent back for correction); reveals Scrap Reason when Scrap."msgstr "Quale tipo di output registra questa voce — Produzione (unità buone), Scrap (non recuperabile) o Rilavorazione (rimandato per correzione); rivela Scrap Reason quando Scrap."@@ -13783,6 +14018,9 @@ msgstr "Dove il nuovo stock di questo articolo si posa per impostazione predefinmsgid "Where stock lives and how it ships."msgstr "Dove il magazzino risiede e come viene spedito."+msgid "Where the affected items are used across the system. Informational — nothing here blocks releasing."+msgstr "Dove gli elementi interessati sono utilizzati in tutto il sistema. Informativo — niente qui blocca il rilascio."+msgid "Where this entry originated (manual entry, posting from sales/purchasing, recurring template, etc.)."msgstr "Da dove proviene questa voce (immissione manuale, contabilizzazione da vendite/acquisti, modello ricorrente, ecc.)."@@ -14067,6 +14305,9 @@ msgstr "Sei stato registrato per {hoursElapsed} ore. Hai dimenticato di registramsgid "Your books and how money flows."msgstr "I tuoi libri e come scorre il denaro."+msgid "Your changes go into a new draft version released with this change order."+msgstr "Le tue modifiche vanno in una nuova versione bozza rilasciata con questo ordine di modifica."+msgid "Your Console PIN"msgstr "Il tuo PIN Console"diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.poindex 5e00f0e158..73a35e69ed 100644--- a/packages/locale/locales/it/mes.po+++ b/packages/locale/locales/it/mes.po@@ -610,6 +610,9 @@ msgstr "Nessun Impatto"msgid "No maintenance scheduled for today"msgstr "Nessuna manutenzione programmata per oggi"+msgid "No matches. Type to create one."+msgstr "Nessuna corrispondenza. Digita per crearne una."+msgid "No materials"msgstr "Nessun materiale"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex e2f8a0e823..ab443ec6b0 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -38,6 +38,10 @@ msgstr "「{taskName}」は完了しました — セットアップマップのmsgid "(excluded for this customer)"msgstr "(このお客様では除外されています)"+#. placeholder {0}: open.length+msgid "{0, plural, one {This part is on 1 open change order} other {This part is on # open change orders}}"+msgstr "{0, plural, one {このパーツは1件のオープンな変更指示に含まれています} other {このパーツは#件のオープンな変更指示に含まれています}}"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0}件の残高のある顧客"@@ -211,6 +215,9 @@ msgstr "90日"msgid "A Carbon-run data migration — you load your own data"msgstr "Carbon実行のデータ移行 — あなたが自分のデータをロードします"+msgid "A change order tracks a controlled engineering or manufacturing change through review and implementation."+msgstr "変更指示は、レビューと実装を通じて管理されたエンジニアリングまたは製造上の変更を追跡します。"+msgid "A clearing account holding the value of goods received but not yet billed; the supplier invoice clears it."msgstr "受け取ったが請求されていない商品の価値を保有するクリアリング勘定。仕入先請求書がそれを結済します。"@@ -502,6 +509,9 @@ msgstr "取得原価"msgid "Acquisition Date"msgstr "取得日"+msgid "Action"+msgstr "アクション"+msgid "Action Status"msgstr "アクション状態"@@ -592,6 +602,9 @@ msgstr "アクションを追加"msgid "Add Adjustment"msgstr "調整を追加"+msgid "Add Affected Item"+msgstr "影響を受けるアイテムを追加"+msgid "Add any notes about your decision..."msgstr "あなたの決定についてのメモを追加してください..."@@ -670,9 +683,6 @@ msgstr "質問を追加"msgid "Add Receipt"msgstr "領収書を追加"-msgid "Add Required Actions"-msgstr "必須アクションを追加"-msgid "Add Requirement"msgstr "要件を追加"@@ -719,6 +729,9 @@ msgstr "アドオン"msgid "Add-On Cost"msgstr "アドオンコスト"+msgid "Added"+msgstr "追加済み"+msgid "Added for this customer"msgstr "このカスタマー向けに追加"@@ -737,9 +750,15 @@ msgstr "住所2行目"msgid "Adjustment Type"msgstr "調整タイプ"+msgid "Advance to {nextStatus}"+msgstr "{nextStatus}に進む"+msgid "Advanced"msgstr "詳細"+msgid "Affected item not found."+msgstr "影響を受けるアイテムが見つかりません。"+msgid "After"msgstr "後"@@ -846,6 +865,9 @@ msgstr "費用ではなく減価償却する資本化されたアイテムの会msgid "An asset's acquisition cost minus accumulated depreciation — what it's still worth on the books, and the figure it's disposed at."msgstr "資産の取得原価から累計減価償却費を差し引いたもの—帳簿上の現在の価値と処分される金額。"+msgid "An engineering change: the affected items whose methods are revised on a draft and released together, superseding the versions they replace."+msgstr "エンジニアリング変更:ドラフト上で方法が改訂され、一緒にリリースされる影響を受けるアイテム。それらが置き換える版に取って代わります。"+msgid "An integration or a custom change — the small slice that's actually custom."msgstr "統合またはカスタム変更 — 実際にカスタムである小さなスライス。"@@ -1033,6 +1055,10 @@ msgstr "プロセス「{name}」を有効化してもよろしいですか?ドmsgid "Are you sure you want to activate this gauge?."msgstr "このゲージを有効化してもよろしいですか?"+#. placeholder {0}: routeData?.changeOrder?.changeOrderId ?? ""+msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."+msgstr "{0}をキャンセルしてもよろしいですか?閉じられて、再度開くまで読み取り専用になります。"+#. placeholder {0}: routeData?.rfqSummary ?.rfqId!msgid "Are you sure you want to cancel {0}? This will also cancel all related supplier quotes."msgstr "{0}をキャンセルしてもよろしいですか?これにより、関連するすべてのサプライヤー見積もりもキャンセルされます。"@@ -1123,6 +1149,14 @@ msgstr "本当にアカウント {0}{1} を削除してもよろしいですかmsgid "Are you sure you want to delete the API key: {0}? This cannot be undone."msgstr "API キー: {0} を削除してもよろしいですか?この操作は取り消せません。"+#. placeholder {0}: requiredAction.name+msgid "Are you sure you want to delete the change order action: {0}? This cannot be undone."+msgstr "変更オーダーアクション「{0}」を削除してもよろしいですか?この操作は取り消せません。"++#. placeholder {0}: changeOrderType.name+msgid "Are you sure you want to delete the change order category: {0}? This cannot be undone."+msgstr "変更指示カテゴリ「{0}」を削除してもよろしいですか?この操作は取り消せません。"+msgid "Are you sure you want to delete the contractor: {name}? This cannot be undone."msgstr "本当に契約者 {name} を削除してもよろしいですか?この操作は取り消せません。"@@ -1281,6 +1315,9 @@ msgstr "本当にウェブフック: {0} を削除してもよろしいですかmsgid "Are you sure you want to delete this approval rule? This cannot be undone."msgstr "このアプリケーション承認ルールを削除してもよろしいですか?この操作は取り消せません。"+msgid "Are you sure you want to delete this change order?"+msgstr "この変更指示を削除してもよろしいですか?"+msgid "Are you sure you want to delete this gauge?"msgstr "このゲージを削除してもよろしいですか?"@@ -1893,6 +1930,12 @@ msgstr "このファイルをダウンロードできません"msgid "Cancel"msgstr "キャンセル"+msgid "Cancel change order"+msgstr "変更指示をキャンセル"++msgid "Cancel Change Order"+msgstr "変更指示をキャンセル"+msgid "Cancel Job"msgstr "ジョブをキャンセル"@@ -2055,12 +2098,30 @@ msgstr "チャンピオン"msgid "Change"msgstr "変更"+msgid "Change order"+msgstr "変更オーダー"++msgid "Change Order"+msgstr "変更指示"++msgid "Change Order Actions"+msgstr "変更オーダーアクション"++msgid "Change Order Types"+msgstr "変更指示タイプ"++msgid "Change Orders"+msgstr "変更指示"+msgid "Change status"msgstr "ステータスを変更"msgid "Change the item type (e.g. Part, Material, Tool, etc.)"msgstr "アイテムタイプを変更します(例:部品、材料、工具など)"+msgid "Change type"+msgstr "種類を変更"+msgid "Change Type"msgstr "タイプを変更"@@ -2076,6 +2137,9 @@ msgstr "これを変更すると、既存のメソッドが上書きされますmsgid "Changing this will update the part ID"msgstr "これを変更するとパーツIDが更新されます"+msgid "Changing type resets this item's draft edits."+msgstr "種類を変更すると、このアイテムのドラフト編集がリセットされます。"+msgid "Chart of accounts"msgstr "勘定科目表"@@ -2411,6 +2475,9 @@ msgstr "確認"msgid "Confirm {0}"msgstr "{0}を確認"+msgid "Confirm & release"+msgstr "確認してリリース"+msgid "Confirm and sign the scope"msgstr "スコープを確認して署名する"@@ -2549,6 +2616,9 @@ msgstr "コントローラー、会計士"msgid "Controls how planning handles a discontinued item: Consume First exhausts on-hand before switching to the successor, Prefer New redirects new demand to the successor immediately, Stock Only keeps only a minimum service reserve, and No Stock drops the item from planning entirely."msgstr "計画が廃止品目をどのように処理するかを制御します。「Consume First」は在庫を使い切ってから後継品に切り替え、「Prefer New」は新規需要をすぐに後継品にリダイレクト、「Stock Only」は最小限のサービス在庫のみを保持、「No Stock」は品目を計画から完全に削除します。"+msgid "Controls whether the bill of material and bill of process of a released (Production) revision can be edited outside a change order."+msgstr "リリース(本番)リビジョンのBOM(部品表)およびBOP(工程表)を変更指示の外で編集できるかどうかを制御します。"+msgid "Convention"msgstr "慣例"@@ -2630,6 +2700,9 @@ msgstr "ジョブ番号をコピー"msgid "Copy link"msgstr "リンクをコピー"+msgid "Copy link to change order"+msgstr "変更指示へのリンクをコピー"+msgid "Copy link to consumable"msgstr "消耗品へのリンクをコピー"@@ -2848,6 +2921,9 @@ msgstr "{0}個の値を作成"msgid "Create & Snapshot"msgstr "作成とスナップショット"+msgid "Create a change order for the new revision and open it"+msgstr "新しいリビジョンの変更オーダーを作成して開く"+msgid "Create a new kanban card for scan-based replenishment."msgstr "スキャンベースの補充用に新しいかんばんカードを作成します。"@@ -2875,6 +2951,9 @@ msgstr "購買注文を作成して承認する"msgid "Create audit trail entries"msgstr "監査証跡エントリを作成"+msgid "Create Change Order"+msgstr "変更指示を作成"+msgid "Create Issue"msgstr "問題を作成"@@ -2932,6 +3011,12 @@ msgstr "作成日時"msgid "Created By"msgstr "作成者"+msgid "Created change order action"+msgstr "変更オーダーアクションを作成"++msgid "Created change order type"+msgstr "変更指示タイプを作成"+msgid "Created consumable"msgstr "消耗品を作成しました"@@ -3550,6 +3635,12 @@ msgstr "{periodLabel}を削除"msgid "Delete {storageUnitName}"msgstr "{storageUnitName}を削除"+msgid "Delete action"+msgstr "アクションを削除"++msgid "Delete Action"+msgstr "アクションを削除"+msgid "Delete API Key"msgstr "APIキーを削除"@@ -3565,6 +3656,9 @@ msgstr "属性を削除"msgid "Delete Category"msgstr "カテゴリを削除"+msgid "Delete Change Order"+msgstr "変更指示を削除"+msgid "Delete Consumable"msgstr "消耗品を削除"@@ -3794,6 +3888,9 @@ msgstr "転送を削除"msgid "Delete Transfer Line"msgstr "転送ラインを削除"+msgid "Delete Type"+msgstr "タイプを削除"+msgid "Delete Unit of Measure"msgstr "測定単位を削除"@@ -3884,6 +3981,9 @@ msgstr "説明"msgid "Description (optional)"msgstr "説明(オプション)"+msgid "Description of Change"+msgstr "変更の説明"+msgid "Description of Issue"msgstr "問題の説明"@@ -3929,6 +4029,9 @@ msgstr "無効"msgid "Discard"msgstr "破棄"+msgid "Discontinuation date"+msgstr "廃止日"+msgid "Discontinuation Date"msgstr "廃止日"@@ -4196,6 +4299,9 @@ msgstr "<0>問題</0>ワークフローを編集"msgid "Edit Account"msgstr "アカウントを編集"+msgid "Edit Action"+msgstr "アクションを編集"+msgid "Edit API Key"msgstr "APIキーを編集"@@ -4217,6 +4323,15 @@ msgstr "属性カテゴリを編集"msgid "Edit Category"msgstr "カテゴリを編集"+msgid "Edit Change Order"+msgstr "変更指示を編集"++msgid "Edit Change Order Action"+msgstr "変更オーダーアクションを編集"++msgid "Edit Change Order Type"+msgstr "変更指示タイプを編集"+msgid "Edit column visibility"msgstr "列の表示/非表示を編集"@@ -4466,6 +4581,9 @@ msgstr "転送を編集"msgid "Edit Transfer Line"msgstr "転送ラインを編集"+msgid "Edit Type"+msgstr "タイプを編集"+msgid "Edit Unit of Measure"msgstr "計測単位を編集"@@ -4583,6 +4701,9 @@ msgstr "前四半期末"msgid "End Time"msgstr "終了時刻"+msgid "Enforce — edits are blocked"+msgstr "強制 - 編集はブロックされます"+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "領収書、出荷、転送、および調整全体にわたって、品目ごとの検証とガイドラインを実施します。"@@ -6004,6 +6125,9 @@ msgstr "II(通常デフォルト)"msgid "III (tightened)"msgstr "III(厳しい)"+msgid "Impact"+msgstr "影響"+msgid "Imperial"msgstr "インペリアル"@@ -6551,6 +6675,9 @@ msgstr "現在の設定を保持"msgid "Keep existing pricing, only add new items"msgstr "既存の価格を保持し、新しい項目のみを追加"+msgid "Keep Open"+msgstr "開いたままにする"+msgid "Key"msgstr "キー"@@ -6655,6 +6782,9 @@ msgstr "関連するすべての領収書はそのままにしておく"msgid "Leave blank for built-in"msgstr "組み込みの場合は空白のままにしてください"+msgid "Leave blank to use the next revision automatically"+msgstr "空白のままにして、次のリビジョンを自動的に使用します"+msgid "Leave empty for exact match"msgstr "正確な一致のために空のままにしてください"@@ -6750,6 +6880,9 @@ msgstr "Linear イシューをリンク"msgid "Linked entity quantity ({0}) does not match row quantity ({1})."msgstr "リンクされたエンティティの数量({0})が行の数量({1})と一致しません。"+msgid "Linked NCR"+msgstr "リンクされたNCR"+msgid "Linked PO"msgstr "リンク済みPO"@@ -7352,6 +7485,9 @@ msgstr "ジョブからモデルが削除されました"msgid "Model removed from line"msgstr "モデルがラインから削除されました"+msgid "Modified"+msgstr "修正済み"+msgid "Module"msgstr "モジュール"@@ -7501,6 +7637,15 @@ msgstr "新しい属性"msgid "New Attribute Category"msgstr "新しい属性カテゴリ"+msgid "New Change Order"+msgstr "新しい変更指示"++msgid "New Change Order Action"+msgstr "新しい変更オーダーアクション"++msgid "New Change Order Type"+msgstr "新しい変更指示タイプ"+msgid "New Consumable"msgstr "新しい消耗品"@@ -7815,6 +7960,12 @@ msgstr "アクティブな見積がありません"msgid "No addresses found"msgstr "住所が見つかりません"+msgid "No affected items to assess."+msgstr "評価する影響を受けるアイテムがありません。"++msgid "No affected items."+msgstr "影響を受けるアイテムがありません。"+msgid "No applications. Payment will be on-account."msgstr "申請がありません。支払いはオンアカウントになります。"@@ -7840,6 +7991,9 @@ msgstr "キャリブレーション記録が見つかりません"msgid "No changes recorded"msgstr "変更が記録されていません"+msgid "No changes yet."+msgstr "まだ変更がありません。"+msgid "No comments yet. Be the first to add a comment."msgstr "まだコメントがありません。最初のコメントを追加してください。"@@ -7867,12 +8021,18 @@ msgstr "休暇の予定がありません"msgid "No default attachments yet."msgstr "まだデフォルト添付ファイルがありません。"+msgid "No draft make method for this item yet."+msgstr "このアイテムのドラフト製造方法はまだありません。"+msgid "No draft versions available"msgstr "ドラフト版は利用できません"msgid "No due date"msgstr "期限なし"+msgid "No editable properties for this item."+msgstr "このアイテムの編集可能なプロパティはありません。"+msgid "No employees assigned yet. Add groups to see status."msgstr "まだ従業員が割り当てられていません。グループを追加してステータスを確認してください。"@@ -7897,6 +8057,9 @@ msgstr "フィールドが見つかりません。"msgid "No files"msgstr "ファイルなし"+msgid "No files for this item."+msgstr "このアイテムのファイルはありません。"+msgid "No files uploaded"msgstr "ファイルがアップロードされていません"@@ -7933,6 +8096,9 @@ msgstr "一致するものがありません"msgid "No matches for \"{query}\". Try a different search term."msgstr "\"{query}\"に一致するものがありません。別の検索用語を試してください。"+msgid "No matches. Type to create one."+msgstr "一致するものがありません。作成するには入力してください。"+msgid "No new notifications"msgstr "新しい通知はありません"@@ -8098,6 +8264,9 @@ msgstr "テーブルではなく、総勘定元帳残高:ジョブ材料が発msgid "Not enough jobs to cover quantity"msgstr "数量をカバーするのに十分なジョブがありません"+msgid "Not referenced anywhere yet."+msgstr "どこでも参照されていません。"+msgid "Not Required"msgstr "不要"@@ -8149,6 +8318,9 @@ msgstr "OEM (オリジナル機器メーカー)"msgid "of"msgstr "の"+msgid "Off — released revisions stay editable"+msgstr "オフ - リリースされたリビジョンは編集可能なままです"+msgid "OK"msgstr "OK"@@ -8236,6 +8408,9 @@ msgstr "申し訳ございません。アクセスしようとしているリンmsgid "Open"msgstr "開く"+msgid "Open a change order"+msgstr "変更オーダーを開く"+msgid "Open Actions"msgstr "オープンアクション"@@ -8251,6 +8426,9 @@ msgstr "未払い売掛金"msgid "Open Audit Log"msgstr "監査ログを開く"+msgid "Open change orders affecting this part"+msgstr "この部品に影響を与える開いている変更指示"+msgid "Open Date"msgstr "開始日"@@ -8504,6 +8682,9 @@ msgstr "見積方法をソース方法で上書きします"msgid "Overwrite the target manufacturing method with the quote method"msgstr "見積方法でターゲット製造方法を上書きします"+msgid "Owner"+msgstr "所有者"+msgid "Owner (cost center)"msgstr "親コストセンター"@@ -8568,6 +8749,12 @@ msgstr "部品ID"msgid "Part is configured for manufacturing"msgstr "部品は製造用に構成されています"+msgid "Part Number"+msgstr "部品番号"++msgid "Part Supersession"+msgstr "パーツの廃止予定"+msgid "Partial"msgstr "部分的"@@ -9531,6 +9718,9 @@ msgstr "理由"msgid "Reason Account"msgstr "理由アカウント"+msgid "Reason for Change"+msgstr "変更の理由"+msgid "Reason for declining (Optional)"msgstr "辞退する理由(オプション)"@@ -9733,12 +9923,27 @@ msgstr "相対的なタイムライン · 日付は確認待ちです"msgid "Release"msgstr "リリース"+msgid "Release change order"+msgstr "変更オーダーをリリース"++msgid "Release control"+msgstr "リリース管理"++msgid "Release Control"+msgstr "リリース管理"+msgid "Release Job"msgstr "ジョブをリリース"msgid "Released"msgstr "リリース済み"+msgid "Released revision"+msgstr "リリースされたリビジョン"++msgid "Released revision is locked"+msgstr "リリースされたリビジョンはロックされています"+msgid "Remaining"msgstr "残高"@@ -9785,6 +9990,9 @@ msgstr "列でソートを削除"msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."msgstr "このストレージタイプをすべての参照ストレージユニットから削除し、削除します。これは元に戻すことはできません。"+msgid "Removed"+msgstr "削除済み"+msgid "Rendering label preview..."msgstr "ラベルプレビューをレンダリング中..."@@ -10006,6 +10214,9 @@ msgstr "逆請求売上税 (既定)"msgid "Reverse the related journal entries"msgstr "関連する仕訳エントリを取り消す"+msgid "Review each item's changes, then confirm — releasing can't be undone."+msgstr "各アイテムの変更をレビューしてから確認してください。リリースは取り消せません。"+msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "当期の貸借対照表と損益計算書を確認し、数字が正しいことを確認してください。これは手動による認可です。確認後、完了とマークしてください。"@@ -10019,6 +10230,9 @@ msgstr "リビジョン"msgid "Revision {0}"msgstr "リビジョン {0}"+msgid "Revisions"+msgstr "リビジョン"+msgid "Revoke"msgstr "取り消す"@@ -11361,6 +11575,9 @@ msgstr "見積書を正常にコピーしました"msgid "Successfully created a new revision"msgstr "新しいリビジョンが正常に作成されました"+msgid "Successor effectivity"+msgstr "後継の有効性"+msgid "Successor Effectivity Date"msgstr "後継品有効日"@@ -12432,6 +12649,9 @@ msgstr "この情報はドキュメントヘッダーで使用されます"msgid "This information will be visible to all users, so be careful what you share."msgstr "この情報はすべてのユーザーに表示されるため、共有する内容に注意してください。"+msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."+msgstr "これは購入アイテムです。BoM/BoP はありません。属性と文書のみ変更できます。"+msgid "This is a unique identifier for the webhook"msgstr "これはウェブフックの一意の識別子です"@@ -12489,6 +12709,12 @@ msgstr "この期間には転記された仕訳がなく、永久に削除できmsgid "This Quarter"msgstr "今四半期"+msgid "This revision is released (Production). Changes should normally flow through a change order."+msgstr "このリビジョンは本番環境にリリースされています。変更は通常、変更注文を通じて行われるべきです。"++msgid "This revision is released (Production). Open a change order to modify it."+msgstr "このリビジョンは本番環境にリリースされています。これを変更するには、変更注文を開いてください。"+msgid "This sales order has associated jobs. Choose what to do with them."msgstr "この販売注文には関連するジョブがあります。それらをどうするかを選択してください。"@@ -12531,6 +12757,9 @@ msgstr "これにより、他のリビジョンのすべてのメソッドマテmsgid "This will replace all method materials of other sizes with this size."msgstr "これにより、他のサイズのすべてのメソッドマテリアルがこのサイズに置き換わります。"+msgid "This will set the current version of the make method to Active, making it read-only."+msgstr "これにより、製造方法の現在のバージョンがアクティブに設定され、読み取り専用になります。"+msgid "This will write off the remaining book value of the asset."msgstr "これはアセットの残りの帳簿価額を償却します。"@@ -13493,6 +13722,9 @@ msgstr "倉庫、オペレーション"msgid "Warn"msgstr "警告"+msgid "Warn — edits succeed with a warning"+msgstr "警告 — 編集は警告付きで成功します"+msgid "Warn but allow"msgstr "警告するが許可する"@@ -13624,6 +13856,9 @@ msgstr "{translatedTerm}とは何ですか?"msgid "What it is"msgstr "それが何であるか"+msgid "What kind of change this is: Version updates how the part is made, Revision edits its details and documents, and New Part replaces it with a new part number."+msgstr "このような変更の種類:バージョンはパーツの製造方法を更新し、リビジョンはその詳細と文書を編集し、新しいパーツは新しいパーツ番号で置き換えます。"+msgid "What kind of output this entry records — Production (good units), Scrap (unrecoverable), or Rework (sent back for correction); reveals Scrap Reason when Scrap."msgstr "このエントリが記録する出力のタイプ — 生産(良好ユニット)、スクラップ(回復不可)、または再作業(修正のために返送)。スクラップの場合、スクラップの理由を表示します。"@@ -13783,6 +14018,9 @@ msgstr "このアイテムの新しいストックが受取時にデフォルトmsgid "Where stock lives and how it ships."msgstr "在庫がどこに保管され、どのように出荷されるか。"+msgid "Where the affected items are used across the system. Informational — nothing here blocks releasing."+msgstr "影響を受けるアイテムがシステム全体でどこで使用されているか。情報提供 - ここに何もリリースをブロックしません。"+msgid "Where this entry originated (manual entry, posting from sales/purchasing, recurring template, etc.)."msgstr "このエントリーの出所(手動入力、販売/購買からのポスティング、反復テンプレートなど)。"@@ -14067,6 +14305,9 @@ msgstr "あなたは{hoursElapsed}時間クロックインしています。クmsgid "Your books and how money flows."msgstr "あなたの帳簿とお金の流れ。"+msgid "Your changes go into a new draft version released with this change order."+msgstr "変更は、このチェンジオーダーとともにリリースされる新しいドラフトバージョンに入ります。"+msgid "Your Console PIN"msgstr "あなたのコンソールPIN"diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.poindex 791d884fa3..b150db5f02 100644--- a/packages/locale/locales/ja/mes.po+++ b/packages/locale/locales/ja/mes.po@@ -610,6 +610,9 @@ msgstr "影響なし"msgid "No maintenance scheduled for today"msgstr "本日のメンテナンス予定はありません"+msgid "No matches. Type to create one."+msgstr "一致するものがありません。入力して新しく作成してください。"+msgid "No materials"msgstr "材料なし"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 6e0b296c77..d607bf5337 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -38,6 +38,10 @@ msgstr "\"{taskName}\" 완료 — 설정 맵 항목 {0}개가 모두 설정되msgid "(excluded for this customer)"msgstr "(이 고객에게는 제외됨)"+#. placeholder {0}: open.length+msgid "{0, plural, one {This part is on 1 open change order} other {This part is on # open change orders}}"+msgstr "{0, plural, one {이 부품은 1개의 미처리 변경주문에 있습니다} other {이 부품은 #개의 미처리 변경주문에 있습니다}}"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "잔액이 있는 고객 {0}명"@@ -211,6 +215,9 @@ msgstr "90일"msgid "A Carbon-run data migration — you load your own data"msgstr "Carbon이 진행하는 데이터 마이그레이션 — 직접 데이터를 업로드"+msgid "A change order tracks a controlled engineering or manufacturing change through review and implementation."+msgstr "변경주문은 검토 및 시행을 통해 제어되는 엔지니어링 또는 제조 변경사항을 추적합니다."+msgid "A clearing account holding the value of goods received but not yet billed; the supplier invoice clears it."msgstr "입고되었으나 아직 청구되지 않은 재화의 금액을 보관하는 경과 계정으로, 공급업체 인보이스가 처리되면 정산됩니다."@@ -502,6 +509,9 @@ msgstr "취득원가"msgid "Acquisition Date"msgstr "취득일"+msgid "Action"+msgstr "작업"+msgid "Action Status"msgstr "조치 상태"@@ -592,6 +602,9 @@ msgstr "조치 추가"msgid "Add Adjustment"msgstr "조정 추가"+msgid "Add Affected Item"+msgstr "영향받는 항목 추가"+msgid "Add any notes about your decision..."msgstr "결정에 대한 메모를 추가하세요..."@@ -670,9 +683,6 @@ msgstr "질문 추가"msgid "Add Receipt"msgstr "입고 추가"-msgid "Add Required Actions"-msgstr "필수 조치 추가"-msgid "Add Requirement"msgstr "요구사항 추가"@@ -719,6 +729,9 @@ msgstr "애드온"msgid "Add-On Cost"msgstr "애드온 비용"+msgid "Added"+msgstr "추가됨"+msgid "Added for this customer"msgstr "이 고객을 위해 추가됨"@@ -737,9 +750,15 @@ msgstr "주소 2"msgid "Adjustment Type"msgstr "조정 유형"+msgid "Advance to {nextStatus}"+msgstr "{nextStatus}로 진행"+msgid "Advanced"msgstr "고급"+msgid "Affected item not found."+msgstr "영향받는 항목을 찾을 수 없습니다."+msgid "After"msgstr "이후"@@ -846,6 +865,9 @@ msgstr "비용 처리 대신 감가상각하는 자본화 항목의 회계 기msgid "An asset's acquisition cost minus accumulated depreciation — what it's still worth on the books, and the figure it's disposed at."msgstr "자산의 취득원가에서 감가상각누계액을 뺀 값 — 장부상 남은 가치이며 처분 시 사용되는 금액입니다."+msgid "An engineering change: the affected items whose methods are revised on a draft and released together, superseding the versions they replace."+msgstr "엔지니어링 변경: 초안에서 방법이 수정되고 함께 릴리스되는 영향받는 항목으로, 이들이 대체하는 버전을 무효화합니다."+msgid "An integration or a custom change — the small slice that's actually custom."msgstr "연동이나 커스텀 변경 — 실제로 커스텀인 작은 부분."@@ -1033,6 +1055,10 @@ msgstr "공정 {name}을(를) 활성화하시겠습니까? 드롭다운에 다msgid "Are you sure you want to activate this gauge?."msgstr "이 측정기를 활성화하시겠습니까?"+#. placeholder {0}: routeData?.changeOrder?.changeOrderId ?? ""+msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."+msgstr "{0}을(를) 취소하시겠습니까? 취소되면 다시 열 때까지 닫힌 상태로 읽기 전용이 됩니다."+#. placeholder {0}: routeData?.rfqSummary ?.rfqId!msgid "Are you sure you want to cancel {0}? This will also cancel all related supplier quotes."msgstr "{0}을(를) 취소하시겠습니까? 관련된 모든 공급업체 견적도 함께 취소됩니다."@@ -1123,6 +1149,14 @@ msgstr "계정 {0}{1}을(를) 삭제하시겠습니까? 이 작업은 되돌릴msgid "Are you sure you want to delete the API key: {0}? This cannot be undone."msgstr "API 키 {0}을(를) 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."+#. placeholder {0}: requiredAction.name+msgid "Are you sure you want to delete the change order action: {0}? This cannot be undone."+msgstr "변경 주문 작업 '{0}'을(를) 삭제하시겠습니까? 이 작업은 실행 취소할 수 없습니다."++#. placeholder {0}: changeOrderType.name+msgid "Are you sure you want to delete the change order category: {0}? This cannot be undone."+msgstr "변경주문 카테고리 {0}을(를) 삭제하시겠습니까? 이는 실행 취소할 수 없습니다."+msgid "Are you sure you want to delete the contractor: {name}? This cannot be undone."msgstr "계약직 {name}을(를) 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."@@ -1281,6 +1315,9 @@ msgstr "웹훅 {0}을(를) 삭제하시겠습니까? 이 작업은 되돌릴 수msgid "Are you sure you want to delete this approval rule? This cannot be undone."msgstr "이 승인 규칙을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."+msgid "Are you sure you want to delete this change order?"+msgstr "이 변경주문을 삭제하시겠습니까?"+msgid "Are you sure you want to delete this gauge?"msgstr "이 측정기를 삭제하시겠습니까?"@@ -1893,6 +1930,12 @@ msgstr "이 파일을 다운로드할 수 없습니다"msgid "Cancel"msgstr "취소"+msgid "Cancel change order"+msgstr "변경 주문 취소"++msgid "Cancel Change Order"+msgstr "변경 주문 취소"+msgid "Cancel Job"msgstr "작업 취소"@@ -2055,12 +2098,30 @@ msgstr "챔피언"msgid "Change"msgstr "변경"+msgid "Change order"+msgstr "변경 주문"++msgid "Change Order"+msgstr "변경주문"++msgid "Change Order Actions"+msgstr "변경 주문 작업"++msgid "Change Order Types"+msgstr "변경주문 유형"++msgid "Change Orders"+msgstr "변경주문"+msgid "Change status"msgstr "상태 변경"msgid "Change the item type (e.g. Part, Material, Tool, etc.)"msgstr "품목 유형을 변경하세요(예: 품목, 자재, 공구 등)"+msgid "Change type"+msgstr "변경 유형"+msgid "Change Type"msgstr "변경 유형"@@ -2076,6 +2137,9 @@ msgstr "이를 변경하면 기존 제조방법을 덮어씁니다"msgid "Changing this will update the part ID"msgstr "이를 변경하면 품목 ID가 업데이트됩니다"+msgid "Changing type resets this item's draft edits."+msgstr "유형을 변경하면 이 항목의 초안 편집이 재설정됩니다."+msgid "Chart of accounts"msgstr "계정과목표"@@ -2411,6 +2475,9 @@ msgstr "확인"msgid "Confirm {0}"msgstr "{0} 확인"+msgid "Confirm & release"+msgstr "확인 및 릴리스"+msgid "Confirm and sign the scope"msgstr "범위를 확인하고 서명하세요"@@ -2549,6 +2616,9 @@ msgstr "컨트롤러, 회계 담당자"msgid "Controls how planning handles a discontinued item: Consume First exhausts on-hand before switching to the successor, Prefer New redirects new demand to the successor immediately, Stock Only keeps only a minimum service reserve, and No Stock drops the item from planning entirely."msgstr "단종 예정 품목을 계획에서 어떻게 처리할지 결정합니다: '우선 소진(Consume First)'은 후속 품목으로 전환하기 전에 보유 재고를 먼저 소진하고, '신규 우선(Prefer New)'은 신규 수요를 즉시 후속 품목으로 돌리며, '재고만 유지(Stock Only)'는 최소 서비스 재고만 남기고, '재고 없음(No Stock)'은 해당 품목을 계획에서 완전히 제외합니다."+msgid "Controls whether the bill of material and bill of process of a released (Production) revision can be edited outside a change order."+msgstr "출시된(생산) 개정의 자재명세서 및 공정표를 변경주문 외부에서 편집할 수 있는지 제어합니다."+msgid "Convention"msgstr "명명 규칙"@@ -2630,6 +2700,9 @@ msgstr "작업 번호 복사"msgid "Copy link"msgstr "링크 복사"+msgid "Copy link to change order"+msgstr "변경주문 링크 복사"+msgid "Copy link to consumable"msgstr "소모품 링크 복사"@@ -2848,6 +2921,9 @@ msgstr "{0} 값 생성"msgid "Create & Snapshot"msgstr "생성 및 스냅샷"+msgid "Create a change order for the new revision and open it"+msgstr "새 개정에 대한 변경 주문을 만들고 열기"+msgid "Create a new kanban card for scan-based replenishment."msgstr "스캔 기반 보충을 위한 새 칸반 카드를 생성합니다."@@ -2875,6 +2951,9 @@ msgstr "구매주문 생성 및 승인"msgid "Create audit trail entries"msgstr "감사 추적 항목 생성"+msgid "Create Change Order"+msgstr "변경주문 생성"+msgid "Create Issue"msgstr "이슈 생성"@@ -2932,6 +3011,12 @@ msgstr "생성일"msgid "Created By"msgstr "생성자"+msgid "Created change order action"+msgstr "변경 주문 작업 생성됨"++msgid "Created change order type"+msgstr "생성된 변경 주문 유형"+msgid "Created consumable"msgstr "소모품 생성됨"@@ -3550,6 +3635,12 @@ msgstr "{periodLabel} 삭제"msgid "Delete {storageUnitName}"msgstr "{storageUnitName} 삭제"+msgid "Delete action"+msgstr "작업 삭제"++msgid "Delete Action"+msgstr "작업 삭제"+msgid "Delete API Key"msgstr "API 키 삭제"@@ -3565,6 +3656,9 @@ msgstr "속성 삭제"msgid "Delete Category"msgstr "카테고리 삭제"+msgid "Delete Change Order"+msgstr "변경주문 삭제"+msgid "Delete Consumable"msgstr "소모품 삭제"@@ -3794,6 +3888,9 @@ msgstr "이동 삭제"msgid "Delete Transfer Line"msgstr "이동 라인 삭제"+msgid "Delete Type"+msgstr "유형 삭제"+msgid "Delete Unit of Measure"msgstr "측정 단위 삭제"@@ -3884,6 +3981,9 @@ msgstr "설명"msgid "Description (optional)"msgstr "설명(선택 사항)"+msgid "Description of Change"+msgstr "변경 설명"+msgid "Description of Issue"msgstr "이슈 설명"@@ -3929,6 +4029,9 @@ msgstr "비활성화됨"msgid "Discard"msgstr "폐기"+msgid "Discontinuation date"+msgstr "중단 날짜"+msgid "Discontinuation Date"msgstr "단종일"@@ -4196,6 +4299,9 @@ msgstr "<0>이슈</0> 워크플로 수정"msgid "Edit Account"msgstr "계정 수정"+msgid "Edit Action"+msgstr "작업 편집"+msgid "Edit API Key"msgstr "API 키 수정"@@ -4217,6 +4323,15 @@ msgstr "속성 카테고리 수정"msgid "Edit Category"msgstr "카테고리 수정"+msgid "Edit Change Order"+msgstr "변경주문 편집"++msgid "Edit Change Order Action"+msgstr "변경 주문 작업 편집"++msgid "Edit Change Order Type"+msgstr "변경 주문 유형 편집"+msgid "Edit column visibility"msgstr "열 표시 여부 수정"@@ -4466,6 +4581,9 @@ msgstr "이동 수정"msgid "Edit Transfer Line"msgstr "이동 라인 수정"+msgid "Edit Type"+msgstr "유형 편집"+msgid "Edit Unit of Measure"msgstr "측정 단위 수정"@@ -4583,6 +4701,9 @@ msgstr "지난 분기 말"msgid "End Time"msgstr "종료 시간"+msgid "Enforce — edits are blocked"+msgstr "강제 — 편집이 차단되었습니다."+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "입고, 출하, 이동, 조정 전반에 걸쳐 품목별 검증 및 지침을 적용합니다."@@ -6004,6 +6125,9 @@ msgstr "II(일반 기본값)"msgid "III (tightened)"msgstr "III(강화)"+msgid "Impact"+msgstr "영향"+msgid "Imperial"msgstr "야드파운드법"@@ -6551,6 +6675,9 @@ msgstr "현재 값 유지"msgid "Keep existing pricing, only add new items"msgstr "기존 가격은 유지하고 새 품목만 추가"+msgid "Keep Open"+msgstr "열린 상태 유지"+msgid "Key"msgstr "키"@@ -6655,6 +6782,9 @@ msgstr "관련 입고는 그대로 둡니다"msgid "Leave blank for built-in"msgstr "내장 값을 사용하려면 비워두세요"+msgid "Leave blank to use the next revision automatically"+msgstr "다음 리비전을 자동으로 사용하려면 공백으로 두세요"+msgid "Leave empty for exact match"msgstr "정확히 일치시키려면 비워두세요"@@ -6750,6 +6880,9 @@ msgstr "Linear 이슈 연결"msgid "Linked entity quantity ({0}) does not match row quantity ({1})."msgstr "연결된 개체 수량({0})이 행 수량({1})과 일치하지 않습니다."+msgid "Linked NCR"+msgstr "연결된 NCR"+msgid "Linked PO"msgstr "연결된 구매주문"@@ -7352,6 +7485,9 @@ msgstr "작업에서 모델이 제거됨"msgid "Model removed from line"msgstr "라인에서 모델이 제거됨"+msgid "Modified"+msgstr "수정됨"+msgid "Module"msgstr "모듈"@@ -7501,6 +7637,15 @@ msgstr "신규 속성"msgid "New Attribute Category"msgstr "신규 속성 카테고리"+msgid "New Change Order"+msgstr "새 변경 주문"++msgid "New Change Order Action"+msgstr "새 변경 주문 작업"++msgid "New Change Order Type"+msgstr "새 변경 주문 유형"+msgid "New Consumable"msgstr "신규 소모품"@@ -7815,6 +7960,12 @@ msgstr "활성 견적 없음"msgid "No addresses found"msgstr "주소가 없습니다"+msgid "No affected items to assess."+msgstr "평가할 영향받는 항목이 없습니다."++msgid "No affected items."+msgstr "영향받는 항목이 없습니다."+msgid "No applications. Payment will be on-account."msgstr "적용 내역이 없습니다. 결제는 계정 잔액으로 처리됩니다."@@ -7840,6 +7991,9 @@ msgstr "교정 기록이 없습니다"msgid "No changes recorded"msgstr "기록된 변경 사항이 없습니다"+msgid "No changes yet."+msgstr "아직 변경사항이 없습니다."+msgid "No comments yet. Be the first to add a comment."msgstr "아직 댓글이 없습니다. 첫 댓글을 남겨보세요."@@ -7867,12 +8021,18 @@ msgstr "예정된 휴무가 없습니다"msgid "No default attachments yet."msgstr "아직 기본 첨부파일이 없습니다."+msgid "No draft make method for this item yet."+msgstr "이 항목에 대한 초안 제작 방법이 아직 없습니다."+msgid "No draft versions available"msgstr "사용 가능한 초안 버전이 없습니다"msgid "No due date"msgstr "마감일 없음"+msgid "No editable properties for this item."+msgstr "이 항목에 대한 편집 가능한 속성이 없습니다."+msgid "No employees assigned yet. Add groups to see status."msgstr "아직 배정된 직원이 없습니다. 그룹을 추가하면 상태를 확인할 수 있습니다."@@ -7897,6 +8057,9 @@ msgstr "필드가 없습니다."msgid "No files"msgstr "파일 없음"+msgid "No files for this item."+msgstr "이 항목에 대한 파일이 없습니다."+msgid "No files uploaded"msgstr "업로드된 파일이 없습니다"@@ -7933,6 +8096,9 @@ msgstr "일치하는 항목 없음"msgid "No matches for \"{query}\". Try a different search term."msgstr "\"{query}\"에 대해 일치하는 항목이 없습니다. 다른 검색어를 시도해 보세요."+msgid "No matches. Type to create one."+msgstr "일치하는 항목 없음. 입력하여 새로 만드세요."+msgid "No new notifications"msgstr "새 알림이 없습니다"@@ -8098,6 +8264,9 @@ msgstr "테이블이 아니라 총계정원장 잔액입니다. 작업 자재가msgid "Not enough jobs to cover quantity"msgstr "수량을 충족할 만큼 작업이 충분하지 않습니다"+msgid "Not referenced anywhere yet."+msgstr "아직 어디에서도 참조되지 않음."+msgid "Not Required"msgstr "필수 아님"@@ -8149,6 +8318,9 @@ msgstr "OEM(주문자상표부착생산)"msgid "of"msgstr "중"+msgid "Off — released revisions stay editable"+msgstr "꺼짐 — 릴리스된 리비전은 편집 가능한 상태로 유지됨"+msgid "OK"msgstr "확인"@@ -8236,6 +8408,9 @@ msgstr "이런! 접근하려는 링크가 유효하지 않습니다."msgid "Open"msgstr "열림"+msgid "Open a change order"+msgstr "변경 주문 열기"+msgid "Open Actions"msgstr "미결 조치"@@ -8251,6 +8426,9 @@ msgstr "미결 매출채권"msgid "Open Audit Log"msgstr "감사 로그 열기"+msgid "Open change orders affecting this part"+msgstr "이 부품에 영향을 미치는 개방된 변경 주문"+msgid "Open Date"msgstr "개설일"@@ -8504,6 +8682,9 @@ msgstr "견적 방법을 원본 방법으로 덮어쓰기"msgid "Overwrite the target manufacturing method with the quote method"msgstr "대상 제조 방법을 견적 방법으로 덮어쓰기"+msgid "Owner"+msgstr "소유자"+msgid "Owner (cost center)"msgstr "소유자(원가센터)"@@ -8568,6 +8749,12 @@ msgstr "품목 ID"msgid "Part is configured for manufacturing"msgstr "제조용으로 설정된 품목입니다"+msgid "Part Number"+msgstr "부품 번호"++msgid "Part Supersession"+msgstr "부품 대체"+msgid "Partial"msgstr "부분"@@ -9531,6 +9718,9 @@ msgstr "사유"msgid "Reason Account"msgstr "사유 계정"+msgid "Reason for Change"+msgstr "변경 이유"+msgid "Reason for declining (Optional)"msgstr "거절 사유(선택 사항)"@@ -9733,12 +9923,27 @@ msgstr "상대적 타임라인 · 날짜 확정 예정"msgid "Release"msgstr "릴리즈"+msgid "Release change order"+msgstr "변경 주문 릴리스"++msgid "Release control"+msgstr "릴리스 제어"++msgid "Release Control"+msgstr "릴리스 제어"+msgid "Release Job"msgstr "작업 릴리즈"msgid "Released"msgstr "릴리즈됨"+msgid "Released revision"+msgstr "릴리스된 리비전"++msgid "Released revision is locked"+msgstr "릴리스된 리비전이 잠금됨"+msgid "Remaining"msgstr "남음"@@ -9785,6 +9990,9 @@ msgstr "열 정렬 제거"msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."msgstr "이 저장 유형을 참조하는 모든 저장 단위에서 제거하고 삭제합니다. 이 작업은 되돌릴 수 없습니다."+msgid "Removed"+msgstr "제거됨"+msgid "Rendering label preview..."msgstr "라벨 미리보기 생성 중..."@@ -10006,6 +10214,9 @@ msgstr "매입자 납부 판매세(기본값)"msgid "Reverse the related journal entries"msgstr "관련 분개 취소"+msgid "Review each item's changes, then confirm — releasing can't be undone."+msgstr "각 항목의 변경 사항을 검토한 후 확인하세요 — 릴리스는 실행 취소할 수 없습니다."+msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "기간의 대차대조표와 손익계산서를 검토하고 수치가 올바른지 확인하세요. 이것은 수동 승인입니다. 검토가 끝나면 완료로 표시하세요."@@ -10019,6 +10230,9 @@ msgstr "리비전"msgid "Revision {0}"msgstr "리비전 {0}"+msgid "Revisions"+msgstr "리비전"+msgid "Revoke"msgstr "취소"@@ -11361,6 +11575,9 @@ msgstr "견적이 복사되었습니다"msgid "Successfully created a new revision"msgstr "새 리비전이 생성되었습니다"+msgid "Successor effectivity"+msgstr "후속 유효성"+msgid "Successor Effectivity Date"msgstr "후속 적용일"@@ -12432,6 +12649,9 @@ msgstr "이 정보는 문서 헤더에 사용됩니다"msgid "This information will be visible to all users, so be careful what you share."msgstr "이 정보는 모든 사용자에게 표시되므로 공유하는 내용에 유의하세요."+msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."+msgstr "이것은 구매 항목입니다 — BoM/BoP가 없습니다. 해당 속성과 문서만 변경할 수 있습니다."+msgid "This is a unique identifier for the webhook"msgstr "웹훅의 고유 식별자입니다"@@ -12489,6 +12709,12 @@ msgstr "이 기간에는 게시된 분개가 없으며 영구적으로 삭제할msgid "This Quarter"msgstr "이번 분기"+msgid "This revision is released (Production). Changes should normally flow through a change order."+msgstr "이 리뷰는 릴리스 상태입니다(프로덕션). 변경 사항은 일반적으로 변경 주문을 통해 진행되어야 합니다."++msgid "This revision is released (Production). Open a change order to modify it."+msgstr "이 리뷰는 릴리스 상태입니다(프로덕션). 수정하려면 변경 주문을 열어주세요."+msgid "This sales order has associated jobs. Choose what to do with them."msgstr "이 판매주문에는 연결된 작업이 있습니다. 처리 방법을 선택하세요."@@ -12531,6 +12757,9 @@ msgstr "다른 리비전의 모든 방법 자재가 이 리비전으로 교체msgid "This will replace all method materials of other sizes with this size."msgstr "다른 사이즈의 모든 방법 자재가 이 사이즈로 교체됩니다."+msgid "This will set the current version of the make method to Active, making it read-only."+msgstr "제조 방법의 현재 버전을 활성으로 설정하여 읽기 전용으로 만듭니다."+msgid "This will write off the remaining book value of the asset."msgstr "자산의 남은 장부가액이 상각 처리됩니다."@@ -13493,6 +13722,9 @@ msgstr "창고, 운영"msgid "Warn"msgstr "경고"+msgid "Warn — edits succeed with a warning"+msgstr "경고 — 편집이 경고와 함께 성공했습니다"+msgid "Warn but allow"msgstr "경고 후 허용"@@ -13624,6 +13856,9 @@ msgstr "{translatedTerm}란 무엇인가요?"msgid "What it is"msgstr "무엇인지"+msgid "What kind of change this is: Version updates how the part is made, Revision edits its details and documents, and New Part replaces it with a new part number."+msgstr "변경 유형: 버전은 부품 제조 방식을 업데이트하고, 개정은 세부 정보와 문서를 편집하며, 새 부품은 새 부품 번호로 교체합니다."+msgid "What kind of output this entry records — Production (good units), Scrap (unrecoverable), or Rework (sent back for correction); reveals Scrap Reason when Scrap."msgstr "이 항목이 기록하는 산출물의 종류입니다 — 생산(양품), 스크랩(복구 불가), 재작업(수정을 위해 반송) 중 하나이며, 스크랩을 선택하면 스크랩 사유가 표시됩니다."@@ -13783,6 +14018,9 @@ msgstr "이 품목의 신규 재고가 입고 시 기본적으로 저장되는msgid "Where stock lives and how it ships."msgstr "재고가 어디에 있고 어떻게 출하되는지."+msgid "Where the affected items are used across the system. Informational — nothing here blocks releasing."+msgstr "영향받은 항목이 시스템 전체에서 사용되는 위치입니다. 참고 사항 — 여기의 내용은 릴리스를 막지 않습니다."+msgid "Where this entry originated (manual entry, posting from sales/purchasing, recurring template, etc.)."msgstr "이 항목의 출처(수동 입력, 판매/구매에서의 전기, 반복 템플릿 등)."@@ -14067,6 +14305,9 @@ msgstr "{hoursElapsed}시간 동안 출근 상태입니다. 퇴근 처리를 잊msgid "Your books and how money flows."msgstr "귀사의 장부와 자금 흐름."+msgid "Your changes go into a new draft version released with this change order."+msgstr "변경 사항이 이 변경 주문과 함께 릴리스되는 새로운 초안 버전으로 이동합니다."+msgid "Your Console PIN"msgstr "콘솔 PIN"diff --git a/packages/locale/locales/ko/mes.po b/packages/locale/locales/ko/mes.poindex c56a09501b..badaf7e565 100644--- a/packages/locale/locales/ko/mes.po+++ b/packages/locale/locales/ko/mes.po@@ -610,6 +610,9 @@ msgstr "영향 없음"msgid "No maintenance scheduled for today"msgstr "오늘 예정된 유지보수가 없습니다"+msgid "No matches. Type to create one."+msgstr "일치하는 항목이 없습니다. 입력하여 새로 만드세요."+msgid "No materials"msgstr "자재 없음"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 7126d8c06a..89cb2063bc 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -38,6 +38,10 @@ msgstr "„{taskName}\" jest gotowe — wszystkie {0} jego elementów Setup Mapmsgid "(excluded for this customer)"msgstr "(wykluczone dla tego klienta)"+#. placeholder {0}: open.length+msgid "{0, plural, one {This part is on 1 open change order} other {This part is on # open change orders}}"+msgstr "{0, plural, one {Ta część znajduje się na 1 otwartym zleceniu zmian} other {Ta część znajduje się na # otwartych zleceniach zmian}}"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} klientów z saldem"@@ -211,6 +215,9 @@ msgstr "90 dni"msgid "A Carbon-run data migration — you load your own data"msgstr "Migracja danych prowadzona przez Carbon — ty ładujesz swoje dane"+msgid "A change order tracks a controlled engineering or manufacturing change through review and implementation."+msgstr "Zlecenie zmian śledzi kontrolowaną zmianę inżynieryjną lub produkcyjną poprzez przegląd i wdrożenie."+msgid "A clearing account holding the value of goods received but not yet billed; the supplier invoice clears it."msgstr "Konto kompensacyjne zawierające wartość towarów otrzymanych, ale jeszcze niezafakturowanych; faktura dostawcy go wyzerowuje."@@ -502,6 +509,9 @@ msgstr "Koszt nabycia"msgid "Acquisition Date"msgstr "Data nabycia"+msgid "Action"+msgstr "Akcja"+msgid "Action Status"msgstr "Status działania"@@ -592,6 +602,9 @@ msgstr "Dodaj Działania"msgid "Add Adjustment"msgstr "Dodaj korektę"+msgid "Add Affected Item"+msgstr "Dodaj element dotknięty zmianą"+msgid "Add any notes about your decision..."msgstr "Dodaj dowolne notatki dotyczące Twojej decyzji..."@@ -670,9 +683,6 @@ msgstr "Dodaj pytanie"msgid "Add Receipt"msgstr "Dodaj Paragon"-msgid "Add Required Actions"-msgstr "Dodaj wymagane działania"-msgid "Add Requirement"msgstr "Dodaj Wymóg"@@ -719,6 +729,9 @@ msgstr "Dodatek"msgid "Add-On Cost"msgstr "Koszt dodatku"+msgid "Added"+msgstr "Dodane"+msgid "Added for this customer"msgstr "Dodane dla tego klienta"@@ -737,9 +750,15 @@ msgstr "Linia adresu 2"msgid "Adjustment Type"msgstr "Typ korekty"+msgid "Advance to {nextStatus}"+msgstr "Przejdź do {nextStatus}"+msgid "Advanced"msgstr "Zaawansowane"+msgid "Affected item not found."+msgstr "Element dotknięty zmianą nie został znaleziony."+msgid "After"msgstr "Po"@@ -846,6 +865,9 @@ msgstr "Zapis księżowy dla elementu kapitalizowanego, który deprecjonujesz zamsgid "An asset's acquisition cost minus accumulated depreciation — what it's still worth on the books, and the figure it's disposed at."msgstr "Koszt nabycia zasobu minus skumulowana amortyzacja — ile warte jest wciąż w księgach i kwota, za którą jest zbywany."+msgid "An engineering change: the affected items whose methods are revised on a draft and released together, superseding the versions they replace."+msgstr "Zmiana inżynierska: elementy dotknięte zmianą, których metody zostały zrewidowane w wersji roboczej i wydane razem, zastępując wersje, które zastępują."+msgid "An integration or a custom change — the small slice that's actually custom."msgstr "Integracja lub zmiana niestandardowa — mała część, która jest faktycznie niestandardowa."@@ -1033,6 +1055,10 @@ msgstr "Czy na pewno chcesz aktywować proces: {name}? Pojawi się ponownie w limsgid "Are you sure you want to activate this gauge?."msgstr "Czy na pewno chcesz aktywować ten miernik?."+#. placeholder {0}: routeData?.changeOrder?.changeOrderId ?? ""+msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."+msgstr "Czy na pewno chcesz anulować {0}? Będzie zamknięte i tylko do odczytu do momentu, gdy je ponownie otworzysz."+#. placeholder {0}: routeData?.rfqSummary ?.rfqId!msgid "Are you sure you want to cancel {0}? This will also cancel all related supplier quotes."msgstr "Czy na pewno chcesz anulować {0}? Spowoduje to również anulowanie wszystkich powiązanych ofert dostawców."@@ -1123,6 +1149,14 @@ msgstr "Czy na pewno chcesz usunąć konto: {0}{1}? Tej czynności nie można comsgid "Are you sure you want to delete the API key: {0}? This cannot be undone."msgstr "Czy na pewno chcesz usunąć klucz API: {0}? Tej czynności nie można cofnąć."+#. placeholder {0}: requiredAction.name+msgid "Are you sure you want to delete the change order action: {0}? This cannot be undone."+msgstr "Czy na pewno chcesz usunąć akcję zmian zamówienia: {0}? Nie można tego cofnąć."++#. placeholder {0}: changeOrderType.name+msgid "Are you sure you want to delete the change order category: {0}? This cannot be undone."+msgstr "Czy na pewno chcesz usunąć kategorię zlecenia zmian: {0}? Nie można tego cofnąć."+msgid "Are you sure you want to delete the contractor: {name}? This cannot be undone."msgstr "Czy na pewno chcesz usunąć wykonawcę: {name}? Tej czynności nie można cofnąć."@@ -1281,6 +1315,9 @@ msgstr "Czy na pewno chcesz usunąć webhook: {0}? Tej czynności nie można cofmsgid "Are you sure you want to delete this approval rule? This cannot be undone."msgstr "Czy na pewno chcesz usunąć tę regułę zatwierdzania? Tej operacji nie można cofnąć."+msgid "Are you sure you want to delete this change order?"+msgstr "Czy na pewno chcesz usunąć to zlecenie zmian?"+msgid "Are you sure you want to delete this gauge?"msgstr "Czy na pewno chcesz usunąć ten miernik?"@@ -1893,6 +1930,12 @@ msgstr "Nie można pobrać tego pliku"msgid "Cancel"msgstr "Anuluj"+msgid "Cancel change order"+msgstr "Anuluj zamówienie zmian"++msgid "Cancel Change Order"+msgstr "Anuluj Zamówienie Zmian"+msgid "Cancel Job"msgstr "Anuluj zadanie"@@ -2055,12 +2098,30 @@ msgstr "Mistrzowie"msgid "Change"msgstr "Zmień"+msgid "Change order"+msgstr "Zmiana zamówienia"++msgid "Change Order"+msgstr "Zlecenie Zmian"++msgid "Change Order Actions"+msgstr "Akcje zmiany zamówienia"++msgid "Change Order Types"+msgstr "Typy Zleceń Zmian"++msgid "Change Orders"+msgstr "Zlecenia Zmian"+msgid "Change status"msgstr "Zmień status"msgid "Change the item type (e.g. Part, Material, Tool, etc.)"msgstr "Zmień typ przedmiotu (np. Część, Materiał, Narzędzie itp.)"+msgid "Change type"+msgstr "Zmień typ"+msgid "Change Type"msgstr "Zmień typ"@@ -2076,6 +2137,9 @@ msgstr "Zmiana tego spowoduje zastąpienie istniejącej metody"msgid "Changing this will update the part ID"msgstr "Zmiana tego zaktualizuje identyfikator części"+msgid "Changing type resets this item's draft edits."+msgstr "Zmiana typu resetuje edycje wersji roboczej tego elementu."+msgid "Chart of accounts"msgstr "Plan kont"@@ -2411,6 +2475,9 @@ msgstr "Potwierdź"msgid "Confirm {0}"msgstr "Potwierdź {0}"+msgid "Confirm & release"+msgstr "Potwierdź i wydaj"+msgid "Confirm and sign the scope"msgstr "Potwierdź i podpisz zakres"@@ -2549,6 +2616,9 @@ msgstr "Kontroler, Księgowy"msgid "Controls how planning handles a discontinued item: Consume First exhausts on-hand before switching to the successor, Prefer New redirects new demand to the successor immediately, Stock Only keeps only a minimum service reserve, and No Stock drops the item from planning entirely."msgstr "Kontroluje sposób, w jaki planowanie obsługuje wycofany artykuł: Consume First wyczerpuje dostępne zapasy przed przejściem na następcę, Prefer New natychmiast przekierowuje nowy popyt do następcy, Stock Only utrzymuje tylko minimalną rezerwę serwisową, a No Stock całkowicie usuwa artykuł z planowania."+msgid "Controls whether the bill of material and bill of process of a released (Production) revision can be edited outside a change order."+msgstr "Kontroluje, czy zestawienie materiałów i zestawienie procesu wydanej (Produkcyjnej) wersji może być edytowane poza zleceniem zmian."+msgid "Convention"msgstr "Konwencja"@@ -2630,6 +2700,9 @@ msgstr "Skopiuj numer zadania"msgid "Copy link"msgstr "Skopiuj link"+msgid "Copy link to change order"+msgstr "Skopiuj link do zlecenia zmian"+msgid "Copy link to consumable"msgstr "Skopiuj link do materiału"@@ -2848,6 +2921,9 @@ msgstr "Utwórz {0} wartości"msgid "Create & Snapshot"msgstr "Utwórz i Snapshot"+msgid "Create a change order for the new revision and open it"+msgstr "Utwórz zmianę zamówienia dla nowej wersji i otwórz ją"+msgid "Create a new kanban card for scan-based replenishment."msgstr "Utwórz nową kartę kanban do uzupełniania opartego na skanowaniu."@@ -2875,6 +2951,9 @@ msgstr "Twórz i zatwierdzaj zamówienia zakupu"msgid "Create audit trail entries"msgstr "Utwórz wpisy dziennika audytu"+msgid "Create Change Order"+msgstr "Utwórz Zlecenie Zmian"+msgid "Create Issue"msgstr "Utwórz problem"@@ -2932,6 +3011,12 @@ msgstr "Utworzono"msgid "Created By"msgstr "Utworzono przez"+msgid "Created change order action"+msgstr "Akcja zmiany zamówienia została utworzona"++msgid "Created change order type"+msgstr "Utworzono typ zamówienia zmian"+msgid "Created consumable"msgstr "Utworzono materiał zużywalny"@@ -3550,6 +3635,12 @@ msgstr "Usuń {periodLabel}"msgid "Delete {storageUnitName}"msgstr "Usuń {storageUnitName}"+msgid "Delete action"+msgstr "Usuń akcję"++msgid "Delete Action"+msgstr "Usuń akcję"+msgid "Delete API Key"msgstr "Usuń klucz API"@@ -3565,6 +3656,9 @@ msgstr "Usuń atrybut"msgid "Delete Category"msgstr "Usuń kategorię"+msgid "Delete Change Order"+msgstr "Usuń Zlecenie Zmian"+msgid "Delete Consumable"msgstr "Usuń materiał eksploatacyjny"@@ -3794,6 +3888,9 @@ msgstr "Usuń Transfer"msgid "Delete Transfer Line"msgstr "Usuń linię transferu"+msgid "Delete Type"+msgstr "Usuń typ"+msgid "Delete Unit of Measure"msgstr "Usuń jednostkę miary"@@ -3884,6 +3981,9 @@ msgstr "Opis"msgid "Description (optional)"msgstr "Opis (opcjonalnie)"+msgid "Description of Change"+msgstr "Opis Zmiany"+msgid "Description of Issue"msgstr "Opis problemu"@@ -3929,6 +4029,9 @@ msgstr "Wyłączone"msgid "Discard"msgstr "Odrzuć"+msgid "Discontinuation date"+msgstr "Data wycofania"+msgid "Discontinuation Date"msgstr "Data wycofania"@@ -4196,6 +4299,9 @@ msgstr "Edytuj Przepływ Pracy <0>Problem</0>"msgid "Edit Account"msgstr "Edytuj konto"+msgid "Edit Action"+msgstr "Edytuj akcję"+msgid "Edit API Key"msgstr "Edytuj klucz API"@@ -4217,6 +4323,15 @@ msgstr "Edytuj kategorię atrybutu"msgid "Edit Category"msgstr "Edytuj kategorię"+msgid "Edit Change Order"+msgstr "Edytuj Zlecenie Zmian"++msgid "Edit Change Order Action"+msgstr "Edytuj akcję zmiany zamówienia"++msgid "Edit Change Order Type"+msgstr "Edytuj typ zamówienia zmian"+msgid "Edit column visibility"msgstr "Edytuj widoczność kolumn"@@ -4466,6 +4581,9 @@ msgstr "Edytuj Transfer"msgid "Edit Transfer Line"msgstr "Edytuj linię transferu"+msgid "Edit Type"+msgstr "Edytuj typ"+msgid "Edit Unit of Measure"msgstr "Edytuj jednostkę miary"@@ -4583,6 +4701,9 @@ msgstr "Koniec ostatniego kwartału"msgid "End Time"msgstr "Czas zakończenia"+msgid "Enforce — edits are blocked"+msgstr "Egzekwuj — edycje są zablokowane"+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Wymuszaj walidację i wytyczne dla każdej pozycji w paragonach, wysyłkach, transferach i korektach."@@ -6004,6 +6125,9 @@ msgstr "II (normalne domyślne)"msgid "III (tightened)"msgstr "III (zaostrzony)"+msgid "Impact"+msgstr "Wpływ"+msgid "Imperial"msgstr "Imperialny"@@ -6551,6 +6675,9 @@ msgstr "Zachowaj bieżące"msgid "Keep existing pricing, only add new items"msgstr "Zachowaj istniejące ceny, dodaj tylko nowe pozycje"+msgid "Keep Open"+msgstr "Utrzymaj otwarte"+msgid "Key"msgstr "Klucz"@@ -6655,6 +6782,9 @@ msgstr "Pozostaw wszelkie powiązane paragony bez zmian"msgid "Leave blank for built-in"msgstr "Pozostaw puste dla wbudowanego"+msgid "Leave blank to use the next revision automatically"+msgstr "Pozostaw puste, aby automatycznie używać następnej wersji"+msgid "Leave empty for exact match"msgstr "Pozostaw puste dla dokładnego dopasowania"@@ -6750,6 +6880,9 @@ msgstr "Połącz problem Linear"msgid "Linked entity quantity ({0}) does not match row quantity ({1})."msgstr "Ilość połączonej jednostki ({0}) nie odpowiada ilości wiersza ({1})."+msgid "Linked NCR"+msgstr "Powiązane NCR"+msgid "Linked PO"msgstr "Powiązane PO"@@ -7352,6 +7485,9 @@ msgstr "Model usunięty z zadania"msgid "Model removed from line"msgstr "Model usunięty z linii"+msgid "Modified"+msgstr "Zmodyfikowane"+msgid "Module"msgstr "Moduł"@@ -7501,6 +7637,15 @@ msgstr "Nowy atrybut"msgid "New Attribute Category"msgstr "Nowa Kategoria Atrybutu"+msgid "New Change Order"+msgstr "Nowe Zlecenie Zmiany"++msgid "New Change Order Action"+msgstr "Nowa akcja zmiany zamówienia"++msgid "New Change Order Type"+msgstr "Nowy typ zamówienia zmian"+msgid "New Consumable"msgstr "Nowy materiał zużywalny"@@ -7815,6 +7960,12 @@ msgstr "Brak aktywnych ofert"msgid "No addresses found"msgstr "Nie znaleziono adresów"+msgid "No affected items to assess."+msgstr "Brak elementów dotkniętych zmianą do oceny."++msgid "No affected items."+msgstr "Brak elementów dotkniętych zmianą."+msgid "No applications. Payment will be on-account."msgstr "Brak aplikacji. Płatność będzie na rachunek."@@ -7840,6 +7991,9 @@ msgstr "Nie znaleziono rekordów kalibracji"msgid "No changes recorded"msgstr "Brak zarejestrowanych zmian"+msgid "No changes yet."+msgstr "Brak zmian."+msgid "No comments yet. Be the first to add a comment."msgstr "Brak komentarzy. Bądź pierwszy i dodaj komentarz."@@ -7867,12 +8021,18 @@ msgstr "Brak zaplanowanych dni wolnych"msgid "No default attachments yet."msgstr "Brak domyślnych załączników."+msgid "No draft make method for this item yet."+msgstr "Brak jeszcze wersji roboczej metody wytwarzania dla tego elementu."+msgid "No draft versions available"msgstr "Brak dostępnych wersji roboczych"msgid "No due date"msgstr "Brak daty terminu"+msgid "No editable properties for this item."+msgstr "Brak edytowalnych właściwości dla tego elementu."+msgid "No employees assigned yet. Add groups to see status."msgstr "Brak przypisanych pracowników. Dodaj grupy, aby zobaczyć status."@@ -7897,6 +8057,9 @@ msgstr "Nie znaleziono pól."msgid "No files"msgstr "Brak plików"+msgid "No files for this item."+msgstr "Brak plików dla tego elementu."+msgid "No files uploaded"msgstr "Brak przesłanych plików"@@ -7933,6 +8096,9 @@ msgstr "Brak wyników"msgid "No matches for \"{query}\". Try a different search term."msgstr "Brak wyników dla „{query}\". Spróbuj innego terminu wyszukiwania."+msgid "No matches. Type to create one."+msgstr "Brak dopasowań. Wpisz, aby utworzyć jeden."+msgid "No new notifications"msgstr "Brak nowych powiadomień"@@ -8098,6 +8264,9 @@ msgstr "Nie tabela, ale saldo księgi głównej: koszt gromadzi się w miarę wymsgid "Not enough jobs to cover quantity"msgstr "Niewystarczająca liczba zadań do pokrycia ilości"+msgid "Not referenced anywhere yet."+msgstr "Nie odwołuje się nigdzie."+msgid "Not Required"msgstr "Nie wymagane"@@ -8149,6 +8318,9 @@ msgstr "OEM (producent oryginalnego sprzętu)"msgid "of"msgstr "z"+msgid "Off — released revisions stay editable"+msgstr "Wyłączone — wydane wersje pozostają edytowalne"+msgid "OK"msgstr "OK"@@ -8236,6 +8408,9 @@ msgstr "Ups! Link, do którego próbujesz uzyskać dostęp, jest nieprawidłowy.msgid "Open"msgstr "Otwórz"+msgid "Open a change order"+msgstr "Otwórz zmianę zamówienia"+msgid "Open Actions"msgstr "Otwarte Działania"@@ -8251,6 +8426,9 @@ msgstr "Otwarte należności"msgid "Open Audit Log"msgstr "Otwórz dziennik audytu"+msgid "Open change orders affecting this part"+msgstr "Otwarte Zlecenia Zmian wpływające na tę część"+msgid "Open Date"msgstr "Data otwarcia"@@ -8504,6 +8682,9 @@ msgstr "Zastąp metodę oferty metodą źródłową"msgid "Overwrite the target manufacturing method with the quote method"msgstr "Zastąp docelową metodę produkcji metodą z oferty"+msgid "Owner"+msgstr "Właściciel"+msgid "Owner (cost center)"msgstr "Nadrzędne centrum kosztów"@@ -8568,6 +8749,12 @@ msgstr "Identyfikator części"msgid "Part is configured for manufacturing"msgstr "Część jest skonfigurowana do produkcji"+msgid "Part Number"+msgstr "Numer części"++msgid "Part Supersession"+msgstr "Zastąpienie części"+msgid "Partial"msgstr "Częściowo"@@ -9531,6 +9718,9 @@ msgstr "Powód"msgid "Reason Account"msgstr "Konto przyczyny"+msgid "Reason for Change"+msgstr "Przyczyna Zmiany"+msgid "Reason for declining (Optional)"msgstr "Powód odrzucenia (Opcjonalnie)"@@ -9733,12 +9923,27 @@ msgstr "Względna oś czasu · daty do potwierdzenia"msgid "Release"msgstr "Zwolnienie"+msgid "Release change order"+msgstr "Wydaj zlecenie zmian"++msgid "Release control"+msgstr "Kontrola wydania"++msgid "Release Control"+msgstr "Kontrola Wydania"+msgid "Release Job"msgstr "Zwolnij zadanie"msgid "Released"msgstr "Wydane"+msgid "Released revision"+msgstr "Wydana wersja"++msgid "Released revision is locked"+msgstr "Wydana wersja jest zablokowana"+msgid "Remaining"msgstr "Pozostało"@@ -9785,6 +9990,9 @@ msgstr "Usuń sortowanie według kolumny"msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."msgstr "Usuń ten typ magazynu ze wszystkich jednostek magazynowych, które się do niego odwołują, i usuń go. Tej operacji nie można cofnąć."+msgid "Removed"+msgstr "Usunięte"+msgid "Rendering label preview..."msgstr "Renderowanie podglądu etykiety..."@@ -10006,6 +10214,9 @@ msgstr "Odwrotne obciążenie podatkiem od sprzedaży (domyślnie)"msgid "Reverse the related journal entries"msgstr "Odwróć powiązane wpisy w dzienniku"+msgid "Review each item's changes, then confirm — releasing can't be undone."+msgstr "Przejrzyj zmiany każdego elementu, a następnie potwierdź — wydanie nie może być cofnięte."+msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Przejrzyj bilans i rachunek zysków i strat okresu i potwierdź, że liczby wyglądają prawidłowo. To jest ręczne zatwierdzenie — oznacz jako gotowe po ich przejrzeniu."@@ -10019,6 +10230,9 @@ msgstr "Wersja"msgid "Revision {0}"msgstr "Wersja {0}"+msgid "Revisions"+msgstr "Wersje"+msgid "Revoke"msgstr "Odwołaj"@@ -11361,6 +11575,9 @@ msgstr "Pomyślnie skopiowano ofertę"msgid "Successfully created a new revision"msgstr "Pomyślnie utworzono nową wersję"+msgid "Successor effectivity"+msgstr "Skuteczność następcy"+msgid "Successor Effectivity Date"msgstr "Data Wejścia Następcy"@@ -12432,6 +12649,9 @@ msgstr "Te informacje będą używane w nagłówkach dokumentów"msgid "This information will be visible to all users, so be careful what you share."msgstr "Te informacje będą widoczne dla wszystkich użytkowników, więc uważaj na to, co udostępniasz."+msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."+msgstr "To jest element nabywany — nie ma BoM/BoP; mogą zmieniać się tylko jego atrybuty i dokumenty."+msgid "This is a unique identifier for the webhook"msgstr "To jest unikalny identyfikator dla webhooka"@@ -12489,6 +12709,12 @@ msgstr "Ten okres nie ma żadnych wpisów w dzienniku i może być trwale usunimsgid "This Quarter"msgstr "Ten Kwartał"+msgid "This revision is released (Production). Changes should normally flow through a change order."+msgstr "Ta wersja jest opublikowana (Produkcja). Zmiany powinny zwykle przechodzić przez zamówienie zmian."++msgid "This revision is released (Production). Open a change order to modify it."+msgstr "Ta wersja jest opublikowana (Produkcja). Otwórz zamówienie zmian, aby ją zmodyfikować."+msgid "This sales order has associated jobs. Choose what to do with them."msgstr "To zamówienie sprzedaży ma powiązane zadania. Wybierz, co z nimi zrobić."@@ -12531,6 +12757,9 @@ msgstr "To zastąpi wszystkie materiały metody innych wersji tą wersją."msgid "This will replace all method materials of other sizes with this size."msgstr "To zastąpi wszystkie materiały metody innych rozmiarów tym rozmiarem."+msgid "This will set the current version of the make method to Active, making it read-only."+msgstr "Ustawi to bieżącą wersję metody wytwarzania na Aktywną, czyniąc ją tylko do odczytu."+msgid "This will write off the remaining book value of the asset."msgstr "Spowoduje to wpisanie pozostałej wartości netto w księgach zasobu."@@ -13493,6 +13722,9 @@ msgstr "Magazyn, Operacje"msgid "Warn"msgstr "Ostrzeżenie"+msgid "Warn — edits succeed with a warning"+msgstr "Ostrzeżenie — edycje powodzą się z ostrzeżeniem"+msgid "Warn but allow"msgstr "Ostrzegaj, ale pozwól"@@ -13624,6 +13856,9 @@ msgstr "Co to jest {translatedTerm}?"msgid "What it is"msgstr "Co to jest"+msgid "What kind of change this is: Version updates how the part is made, Revision edits its details and documents, and New Part replaces it with a new part number."+msgstr "Jaki to jest rodzaj zmiany: Wersja aktualizuje sposób wytwarzania części, Rewizja edytuje jej szczegóły i dokumenty, a Nowa Część zastępuje ją nowym numerem części."+msgid "What kind of output this entry records — Production (good units), Scrap (unrecoverable), or Rework (sent back for correction); reveals Scrap Reason when Scrap."msgstr "Jakie dane wyjściowe rejestruje ten wpis — Produkcja (jednostki dobre), Złom (nieodwracalny) lub Przeróbka (odesłane do korekty); ujawnia Powód złomu, gdy złom."@@ -13783,6 +14018,9 @@ msgstr "Gdzie nowy zapas tego artykułu ląduje domyślnie przy odbiorze; wyborymsgid "Where stock lives and how it ships."msgstr "Gdzie znajduje się zapas i jak się wysyła."+msgid "Where the affected items are used across the system. Informational — nothing here blocks releasing."+msgstr "Gdzie używane są dotknięte elementy w całym systemie. Informacyjne — nic tutaj nie blokuje wydawania."+msgid "Where this entry originated (manual entry, posting from sales/purchasing, recurring template, etc.)."msgstr "Skąd pochodzi ten wpis (wpis ręczny, zaksięgowanie ze sprzedaży/zakupów, szablon powtarzalny itp.)."@@ -14067,6 +14305,9 @@ msgstr "Jesteś zalogowany od {hoursElapsed} godzin. Czy zapomniałeś się wylomsgid "Your books and how money flows."msgstr "Twoje księgi i przepływ pieniędzy."+msgid "Your changes go into a new draft version released with this change order."+msgstr "Twoje zmiany trafiają do nowej wersji roboczej wydanej z tym zamówieniem zmian."+msgid "Your Console PIN"msgstr "Twój PIN konsoli"diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.poindex 254f100769..62f9a61b04 100644--- a/packages/locale/locales/pl/mes.po+++ b/packages/locale/locales/pl/mes.po@@ -610,6 +610,9 @@ msgstr "Brak wpływu"msgid "No maintenance scheduled for today"msgstr "Brak zaplanowanego utrzymania ruchu na dziś"+msgid "No matches. Type to create one."+msgstr "Brak wyników. Wpisz, aby utworzyć nowy."+msgid "No materials"msgstr "Brak materiałów"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 5acad888cf..7565c5a79d 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -38,6 +38,10 @@ msgstr "\"{taskName}\" está concluído — todos os {0} itens do seu Mapa de Comsgid "(excluded for this customer)"msgstr "(excluído para este cliente)"+#. placeholder {0}: open.length+msgid "{0, plural, one {This part is on 1 open change order} other {This part is on # open change orders}}"+msgstr "{0, plural, one {Esta peça está em 1 ordem de alteração aberta} other {Esta peça está em # ordens de alteração abertas}}"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} clientes com saldo"@@ -211,6 +215,9 @@ msgstr "90 dias"msgid "A Carbon-run data migration — you load your own data"msgstr "Uma migração de dados executada pela Carbon — você carrega seus próprios dados"+msgid "A change order tracks a controlled engineering or manufacturing change through review and implementation."+msgstr "Uma ordem de alteração rastreia uma mudança de engenharia ou fabricação controlada através de revisão e implementação."+msgid "A clearing account holding the value of goods received but not yet billed; the supplier invoice clears it."msgstr "Uma conta de compensação que mantém o valor das mercadorias recebidas mas ainda não faturadas; a fatura do fornecedor a limpa."@@ -502,6 +509,9 @@ msgstr "Custo de aquisição"msgid "Acquisition Date"msgstr "Data de aquisição"+msgid "Action"+msgstr "Ação"+msgid "Action Status"msgstr "Status da Ação"@@ -592,6 +602,9 @@ msgstr "Adicionar Ações"msgid "Add Adjustment"msgstr "Adicionar ajuste"+msgid "Add Affected Item"+msgstr "Adicionar Item Afetado"+msgid "Add any notes about your decision..."msgstr "Adicione qualquer nota sobre sua decisão..."@@ -670,9 +683,6 @@ msgstr "Adicionar Pergunta"msgid "Add Receipt"msgstr "Adicionar Recebimento"-msgid "Add Required Actions"-msgstr "Adicionar Ações Obrigatórias"-msgid "Add Requirement"msgstr "Adicionar Requisito"@@ -719,6 +729,9 @@ msgstr "Complemento"msgid "Add-On Cost"msgstr "Custo Adicional"+msgid "Added"+msgstr "Adicionado"+msgid "Added for this customer"msgstr "Adicionado para este cliente"@@ -737,9 +750,15 @@ msgstr "Linha de Endereço 2"msgid "Adjustment Type"msgstr "Tipo de Ajuste"+msgid "Advance to {nextStatus}"+msgstr "Avançar para {nextStatus}"+msgid "Advanced"msgstr "Avançado"+msgid "Affected item not found."+msgstr "Item afetado não encontrado."+msgid "After"msgstr "Após"@@ -846,6 +865,9 @@ msgstr "Um registro contábil de um elemento capitalizado que você deprecia emmsgid "An asset's acquisition cost minus accumulated depreciation — what it's still worth on the books, and the figure it's disposed at."msgstr "O custo de aquisição de um ativo menos a depreciação acumulada — o que ainda vale nos livros e o valor em que é alienado."+msgid "An engineering change: the affected items whose methods are revised on a draft and released together, superseding the versions they replace."+msgstr "Uma mudança de engenharia: os itens afetados cujos métodos são revisados em um rascunho e lançados juntos, substituindo as versões que substituem."+msgid "An integration or a custom change — the small slice that's actually custom."msgstr "Uma integração ou uma mudança personalizada — a pequena parte que é realmente personalizada."@@ -1033,6 +1055,10 @@ msgstr "Tem a certeza de que deseja ativar o processo: {name}? Ele aparecerá nomsgid "Are you sure you want to activate this gauge?."msgstr "Tem certeza de que deseja ativar este medidor?."+#. placeholder {0}: routeData?.changeOrder?.changeOrderId ?? ""+msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."+msgstr "Tem certeza de que deseja cancelar {0}? Será fechado e somente leitura até que você o reabra."+#. placeholder {0}: routeData?.rfqSummary ?.rfqId!msgid "Are you sure you want to cancel {0}? This will also cancel all related supplier quotes."msgstr "Tem a certeza de que deseja cancelar {0}? Isto também cancelará todas as cotações de fornecedores relacionadas."@@ -1123,6 +1149,14 @@ msgstr "Tem a certeza de que deseja eliminar a conta: {0}{1}? Esta ação não pmsgid "Are you sure you want to delete the API key: {0}? This cannot be undone."msgstr "Tem a certeza de que deseja eliminar a chave de API: {0}? Esta ação não pode ser desfeita."+#. placeholder {0}: requiredAction.name+msgid "Are you sure you want to delete the change order action: {0}? This cannot be undone."+msgstr "Tem certeza de que deseja excluir a ação da ordem de mudança: {0}? Isso não pode ser desfeito."++#. placeholder {0}: changeOrderType.name+msgid "Are you sure you want to delete the change order category: {0}? This cannot be undone."+msgstr "Tem certeza que deseja deletar a categoria de ordem de alteração: {0}? Isso não pode ser desfeito."+msgid "Are you sure you want to delete the contractor: {name}? This cannot be undone."msgstr "Tem a certeza de que deseja eliminar o contratante: {name}? Esta ação não pode ser desfeita."@@ -1281,6 +1315,9 @@ msgstr "Tem a certeza de que deseja eliminar o webhook: {0}? Esta ação não pomsgid "Are you sure you want to delete this approval rule? This cannot be undone."msgstr "Tem a certeza de que deseja eliminar esta regra de aprovação? Isto não pode ser desfeito."+msgid "Are you sure you want to delete this change order?"+msgstr "Tem certeza que deseja deletar esta ordem de alteração?"+msgid "Are you sure you want to delete this gauge?"msgstr "Tem certeza de que deseja excluir este medidor?"@@ -1893,6 +1930,12 @@ msgstr "Não é possível baixar este arquivo"msgid "Cancel"msgstr "Cancelar"+msgid "Cancel change order"+msgstr "Cancelar ordem de mudança"++msgid "Cancel Change Order"+msgstr "Cancelar Ordem de Mudança"+msgid "Cancel Job"msgstr "Cancelar Trabalho"@@ -2055,12 +2098,30 @@ msgstr "Campeões"msgid "Change"msgstr "Alterar"+msgid "Change order"+msgstr "Ordem de mudança"++msgid "Change Order"+msgstr "Ordem de Alteração"++msgid "Change Order Actions"+msgstr "Ações de Ordem de Mudança"++msgid "Change Order Types"+msgstr "Tipos de Ordem de Alteração"++msgid "Change Orders"+msgstr "Ordens de Alteração"+msgid "Change status"msgstr "Alterar status"msgid "Change the item type (e.g. Part, Material, Tool, etc.)"msgstr "Alterar o tipo de item (por exemplo, Peça, Material, Ferramenta, etc.)"+msgid "Change type"+msgstr "Tipo de mudança"+msgid "Change Type"msgstr "Alterar Tipo"@@ -2076,6 +2137,9 @@ msgstr "Alterar isto irá sobrescrever o método existente"msgid "Changing this will update the part ID"msgstr "Alterar isto atualizará o ID da peça"+msgid "Changing type resets this item's draft edits."+msgstr "Alterar tipo redefine as edições de rascunho deste item."+msgid "Chart of accounts"msgstr "Plano de contas"@@ -2411,6 +2475,9 @@ msgstr "Confirmar"msgid "Confirm {0}"msgstr "Confirmar {0}"+msgid "Confirm & release"+msgstr "Confirmar e lançar"+msgid "Confirm and sign the scope"msgstr "Confirmar e assinar o escopo"@@ -2549,6 +2616,9 @@ msgstr "Controlador, Contador"msgid "Controls how planning handles a discontinued item: Consume First exhausts on-hand before switching to the successor, Prefer New redirects new demand to the successor immediately, Stock Only keeps only a minimum service reserve, and No Stock drops the item from planning entirely."msgstr "Controla como o planejamento lida com um item descontinuado: Consumir Primeiro esgota o estoque existente antes de mudar para o sucessor, Preferir Novo redireciona a nova demanda para o sucessor imediatamente, Apenas Estoque mantém apenas uma reserva mínima de serviço, e Sem Estoque remove o item do planejamento inteiramente."+msgid "Controls whether the bill of material and bill of process of a released (Production) revision can be edited outside a change order."+msgstr "Controla se a lista de materiais e a lista de processos de uma revisão lançada (Produção) podem ser editadas fora de uma ordem de alteração."+msgid "Convention"msgstr "Convenção"@@ -2630,6 +2700,9 @@ msgstr "Copiar número do trabalho"msgid "Copy link"msgstr "Copiar ligação"+msgid "Copy link to change order"+msgstr "Copiar link para ordem de alteração"+msgid "Copy link to consumable"msgstr "Copiar link para consumível"@@ -2848,6 +2921,9 @@ msgstr "Criar {0} valores"msgid "Create & Snapshot"msgstr "Criar e Capturar"+msgid "Create a change order for the new revision and open it"+msgstr "Criar uma ordem de mudança para a nova revisão e abri-la"+msgid "Create a new kanban card for scan-based replenishment."msgstr "Crie um novo cartão kanban para reabastecimento baseado em varredura."@@ -2875,6 +2951,9 @@ msgstr "Criar e aprovar pedidos de compra"msgid "Create audit trail entries"msgstr "Criar entradas de trilha de auditoria"+msgid "Create Change Order"+msgstr "Criar Ordem de Alteração"+msgid "Create Issue"msgstr "Criar Problema"@@ -2932,6 +3011,12 @@ msgstr "Criado em"msgid "Created By"msgstr "Criado por"+msgid "Created change order action"+msgstr "Ação de ordem de mudança criada"++msgid "Created change order type"+msgstr "Tipo de ordem de mudança criado"+msgid "Created consumable"msgstr "Consumível criado"@@ -3550,6 +3635,12 @@ msgstr "Deletar {periodLabel}"msgid "Delete {storageUnitName}"msgstr "Eliminar {storageUnitName}"+msgid "Delete action"+msgstr "Excluir ação"++msgid "Delete Action"+msgstr "Excluir Ação"+msgid "Delete API Key"msgstr "Eliminar Chave de API"@@ -3565,6 +3656,9 @@ msgstr "Eliminar Atributo"msgid "Delete Category"msgstr "Eliminar Categoria"+msgid "Delete Change Order"+msgstr "Deletar Ordem de Alteração"+msgid "Delete Consumable"msgstr "Eliminar Consumível"@@ -3794,6 +3888,9 @@ msgstr "Excluir Transferência"msgid "Delete Transfer Line"msgstr "Eliminar Linha de Transferência"+msgid "Delete Type"+msgstr "Excluir Tipo"+msgid "Delete Unit of Measure"msgstr "Excluir unidade de medida"@@ -3884,6 +3981,9 @@ msgstr "Descrição"msgid "Description (optional)"msgstr "Descrição (opcional)"+msgid "Description of Change"+msgstr "Descrição da Alteração"+msgid "Description of Issue"msgstr "Descrição do Problema"@@ -3929,6 +4029,9 @@ msgstr "Desativado"msgid "Discard"msgstr "Descartar"+msgid "Discontinuation date"+msgstr "Data de descontinuação"+msgid "Discontinuation Date"msgstr "Data de Descontinuação"@@ -4196,6 +4299,9 @@ msgstr "Editar Fluxo de Trabalho <0>Problema</0>"msgid "Edit Account"msgstr "Editar Conta"+msgid "Edit Action"+msgstr "Editar Ação"+msgid "Edit API Key"msgstr "Editar Chave de API"@@ -4217,6 +4323,15 @@ msgstr "Editar Categoria de Atributo"msgid "Edit Category"msgstr "Editar Categoria"+msgid "Edit Change Order"+msgstr "Editar Ordem de Alteração"++msgid "Edit Change Order Action"+msgstr "Editar Ação de Ordem de Mudança"++msgid "Edit Change Order Type"+msgstr "Editar Tipo de Ordem de Mudança"+msgid "Edit column visibility"msgstr "Editar visibilidade da coluna"@@ -4466,6 +4581,9 @@ msgstr "Editar Transferência"msgid "Edit Transfer Line"msgstr "Editar Linha de Transferência"+msgid "Edit Type"+msgstr "Editar Tipo"+msgid "Edit Unit of Measure"msgstr "Editar Unidade de Medida"@@ -4583,6 +4701,9 @@ msgstr "Fim do Trimestre Anterior"msgid "End Time"msgstr "Hora de Término"+msgid "Enforce — edits are blocked"+msgstr "Forçar — edições são bloqueadas"+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Aplicar validação e diretrizes por item em recebimentos, remessas, transferências e ajustes."@@ -6004,6 +6125,9 @@ msgstr "II (padrão normal)"msgid "III (tightened)"msgstr "III (apertado)"+msgid "Impact"+msgstr "Impacto"+msgid "Imperial"msgstr "Imperial"@@ -6551,6 +6675,9 @@ msgstr "Manter Atual"msgid "Keep existing pricing, only add new items"msgstr "Manter preços existentes, adicionar apenas novos itens"+msgid "Keep Open"+msgstr "Manter Aberto"+msgid "Key"msgstr "Chave"@@ -6655,6 +6782,9 @@ msgstr "Deixar qualquer recebimento relacionado intocado"msgid "Leave blank for built-in"msgstr "Deixe em branco para usar o padrão"+msgid "Leave blank to use the next revision automatically"+msgstr "Deixe em branco para usar a próxima revisão automaticamente"+msgid "Leave empty for exact match"msgstr "Deixe vazio para correspondência exata"@@ -6750,6 +6880,9 @@ msgstr "Vincular Problema Linear"msgid "Linked entity quantity ({0}) does not match row quantity ({1})."msgstr "Quantidade de entidade vinculada ({0}) não corresponde à quantidade da linha ({1})."+msgid "Linked NCR"+msgstr "NCR Vinculado"+msgid "Linked PO"msgstr "PO Vinculada"@@ -7352,6 +7485,9 @@ msgstr "Modelo removido do trabalho"msgid "Model removed from line"msgstr "Modelo removido da linha"+msgid "Modified"+msgstr "Modificado"+msgid "Module"msgstr "Módulo"@@ -7501,6 +7637,15 @@ msgstr "Novo Atributo"msgid "New Attribute Category"msgstr "Nova Categoria de Atributo"+msgid "New Change Order"+msgstr "Nova Ordem de Mudança"++msgid "New Change Order Action"+msgstr "Nova Ação de Ordem de Mudança"++msgid "New Change Order Type"+msgstr "Novo Tipo de Ordem de Mudança"+msgid "New Consumable"msgstr "Novo Consumível"@@ -7815,6 +7960,12 @@ msgstr "Sem Cotações Ativas"msgid "No addresses found"msgstr "Nenhum endereço encontrado"+msgid "No affected items to assess."+msgstr "Nenhum item afetado para avaliar."++msgid "No affected items."+msgstr "Nenhum item afetado."+msgid "No applications. Payment will be on-account."msgstr "Sem aplicações. O pagamento será na conta."@@ -7840,6 +7991,9 @@ msgstr "Nenhum registro de calibração encontrado"msgid "No changes recorded"msgstr "Nenhuma alteração registrada"+msgid "No changes yet."+msgstr "Nenhuma mudança ainda."+msgid "No comments yet. Be the first to add a comment."msgstr "Sem comentários ainda. Seja o primeiro a adicionar um comentário."@@ -7867,12 +8021,18 @@ msgstr "Nenhum dia de folga agendado"msgid "No default attachments yet."msgstr "Nenhum anexo padrão ainda."+msgid "No draft make method for this item yet."+msgstr "Nenhum método de fabricação de rascunho para este item ainda."+msgid "No draft versions available"msgstr "Nenhuma versão de rascunho disponível"msgid "No due date"msgstr "Sem data de vencimento"+msgid "No editable properties for this item."+msgstr "Nenhuma propriedade editável para este item."+msgid "No employees assigned yet. Add groups to see status."msgstr "Nenhum funcionário atribuído ainda. Adicione grupos para ver o status."@@ -7897,6 +8057,9 @@ msgstr "Nenhum campo encontrado."msgid "No files"msgstr "Nenhum arquivo"+msgid "No files for this item."+msgstr "Nenhum arquivo para este item."+msgid "No files uploaded"msgstr "Nenhum arquivo enviado"@@ -7933,6 +8096,9 @@ msgstr "Nenhuma correspondência"msgid "No matches for \"{query}\". Try a different search term."msgstr "Nenhuma correspondência para \"{query}\". Tente um termo de pesquisa diferente."+msgid "No matches. Type to create one."+msgstr "Nenhuma correspondência. Digite para criar uma."+msgid "No new notifications"msgstr "Sem notificações novas"@@ -8098,6 +8264,9 @@ msgstr "Não é uma tabela, mas um saldo do livro-razão geral: o custo se acumumsgid "Not enough jobs to cover quantity"msgstr "Não há trabalhos suficientes para cobrir a quantidade"+msgid "Not referenced anywhere yet."+msgstr "Não referenciado em lugar nenhum ainda."+msgid "Not Required"msgstr "Não Obrigatório"@@ -8149,6 +8318,9 @@ msgstr "OEM (fabricante de equipamento original)"msgid "of"msgstr "de"+msgid "Off — released revisions stay editable"+msgstr "Desativado — revisões lançadas permanecem editáveis"+msgid "OK"msgstr "OK"@@ -8236,6 +8408,9 @@ msgstr "Oops! O link que está tentando acessar não é válido."msgid "Open"msgstr "Abrir"+msgid "Open a change order"+msgstr "Abrir uma ordem de mudança"+msgid "Open Actions"msgstr "Ações Abertas"@@ -8251,6 +8426,9 @@ msgstr "AR aberto"msgid "Open Audit Log"msgstr "Abrir Registro de Auditoria"+msgid "Open change orders affecting this part"+msgstr "Ordens de mudança abertas que afetam esta peça"+msgid "Open Date"msgstr "Data de Abertura"@@ -8504,6 +8682,9 @@ msgstr "Sobrescrever o método de cotação com o método de origem"msgid "Overwrite the target manufacturing method with the quote method"msgstr "Sobrescrever o método de fabricação de destino com o método de cotação"+msgid "Owner"+msgstr "Proprietário"+msgid "Owner (cost center)"msgstr "Centro de custo principal"@@ -8568,6 +8749,12 @@ msgstr "ID da Peça"msgid "Part is configured for manufacturing"msgstr "Peça configurada para fabricação"+msgid "Part Number"+msgstr "Número da Peça"++msgid "Part Supersession"+msgstr "Substituição de Peça"+msgid "Partial"msgstr "Parcial"@@ -9531,6 +9718,9 @@ msgstr "Motivo"msgid "Reason Account"msgstr "Conta de Motivo"+msgid "Reason for Change"+msgstr "Motivo da Mudança"+msgid "Reason for declining (Optional)"msgstr "Motivo da recusa (Opcional)"@@ -9733,12 +9923,27 @@ msgstr "Cronograma relativo · datas a confirmar"msgid "Release"msgstr "Liberação"+msgid "Release change order"+msgstr "Liberar ordem de alteração"++msgid "Release control"+msgstr "Controle de lançamento"++msgid "Release Control"+msgstr "Controle de Lançamento"+msgid "Release Job"msgstr "Liberar Trabalho"msgid "Released"msgstr "Liberado"+msgid "Released revision"+msgstr "Revisão lançada"++msgid "Released revision is locked"+msgstr "A revisão lançada está bloqueada"+msgid "Remaining"msgstr "Restante"@@ -9785,6 +9990,9 @@ msgstr "Remover ordenação por coluna"msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."msgstr "Remova este tipo de armazenamento de todas as unidades de armazenamento que o referenciam e o delete. Isto não pode ser desfeito."+msgid "Removed"+msgstr "Removido"+msgid "Rendering label preview..."msgstr "Renderizando visualização de etiqueta..."@@ -10006,6 +10214,9 @@ msgstr "Imposto de vendas de cobrança reversa (padrão)"msgid "Reverse the related journal entries"msgstr "Reverter os lançamentos contábeis relacionados"+msgid "Review each item's changes, then confirm — releasing can't be undone."+msgstr "Revise as alterações de cada item e confirme — liberar não pode ser desfeito."+msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Revise o balanço patrimonial e demonstração de resultado do período e confirme se os valores parecem corretos. Esta é uma aprovação manual — marque como concluído depois de tê-los revisado."@@ -10019,6 +10230,9 @@ msgstr "Revisão"msgid "Revision {0}"msgstr "Revisão {0}"+msgid "Revisions"+msgstr "Revisões"+msgid "Revoke"msgstr "Revogar"@@ -11361,6 +11575,9 @@ msgstr "Cotação copiada com sucesso"msgid "Successfully created a new revision"msgstr "Revisão criada com sucesso"+msgid "Successor effectivity"+msgstr "Efetividade do sucessor"+msgid "Successor Effectivity Date"msgstr "Data de Efetividade do Sucessor"@@ -12432,6 +12649,9 @@ msgstr "Esta informação será usada nos cabeçalhos de documentos"msgid "This information will be visible to all users, so be careful what you share."msgstr "Esta informação será visível para todos os usuários, portanto, tenha cuidado com o que você compartilha."+msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."+msgstr "Este é um item comprado — não tem BOM/BOP; apenas seus atributos e documentos podem mudar."+msgid "This is a unique identifier for the webhook"msgstr "Este é um identificador único para o webhook"@@ -12489,6 +12709,12 @@ msgstr "Este período não tem lançamentos de diário nele e pode ser deletadomsgid "This Quarter"msgstr "Este Trimestre"+msgid "This revision is released (Production). Changes should normally flow through a change order."+msgstr "Esta revisão foi lançada (Produção). As alterações devem normalmente passar por uma ordem de alteração."++msgid "This revision is released (Production). Open a change order to modify it."+msgstr "Esta revisão foi lançada (Produção). Abra uma ordem de alteração para modificá-la."+msgid "This sales order has associated jobs. Choose what to do with them."msgstr "Esta ordem de venda tem trabalhos associados. Escolha o que fazer com eles."@@ -12531,6 +12757,9 @@ msgstr "Isto substituirá todos os materiais de método de outras revisões pormsgid "This will replace all method materials of other sizes with this size."msgstr "Isto substituirá todos os materiais de método de outros tamanhos por este tamanho."+msgid "This will set the current version of the make method to Active, making it read-only."+msgstr "Isso definirá a versão atual do método de fabricação como Ativa, deixando-a somente leitura."+msgid "This will write off the remaining book value of the asset."msgstr "Isto removerá o valor líquido contábil restante do ativo."@@ -13493,6 +13722,9 @@ msgstr "Armazém, Ops"msgid "Warn"msgstr "Aviso"+msgid "Warn — edits succeed with a warning"+msgstr "Avisar — edições bem-sucedidas com aviso"+msgid "Warn but allow"msgstr "Avisar mas permitir"@@ -13624,6 +13856,9 @@ msgstr "O que é {translatedTerm}?"msgid "What it is"msgstr "O que é"+msgid "What kind of change this is: Version updates how the part is made, Revision edits its details and documents, and New Part replaces it with a new part number."+msgstr "Que tipo de alteração é: Versão atualiza como a peça é feita, Revisão edita seus detalhes e documentos, e Nova Peça a substitui por um novo número de peça."+msgid "What kind of output this entry records — Production (good units), Scrap (unrecoverable), or Rework (sent back for correction); reveals Scrap Reason when Scrap."msgstr "Que tipo de saída esta entrada registra — Produção (unidades boas), Sucata (irrecuperável) ou Retrabaho (enviado de volta para correção); revela Scrap Reason quando Sucata."@@ -13783,6 +14018,9 @@ msgstr "Onde o novo estoque deste item aterroriza por padrão ao receber; as selmsgid "Where stock lives and how it ships."msgstr "Onde o estoque fica e como é enviado."+msgid "Where the affected items are used across the system. Informational — nothing here blocks releasing."+msgstr "Onde os itens afetados são usados em todo o sistema. Informativo — nada aqui bloqueia a liberação."+msgid "Where this entry originated (manual entry, posting from sales/purchasing, recurring template, etc.)."msgstr "De onde esta entrada se originou (entrada manual, contabilização de vendas/compras, modelo recorrente, etc.)."@@ -14067,6 +14305,9 @@ msgstr "Você está marcado há {hoursElapsed} horas. Esqueceu de marcar a saídmsgid "Your books and how money flows."msgstr "Seus livros e como o dinheiro flui."+msgid "Your changes go into a new draft version released with this change order."+msgstr "Suas alterações entram em uma nova versão rascunho lançada com esta ordem de mudança."+msgid "Your Console PIN"msgstr "Seu PIN do Console"diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.poindex 70b833daaa..4f239f8b98 100644--- a/packages/locale/locales/pt/mes.po+++ b/packages/locale/locales/pt/mes.po@@ -610,6 +610,9 @@ msgstr "Sem Impacto"msgid "No maintenance scheduled for today"msgstr "Nenhuma manutenção programada para hoje"+msgid "No matches. Type to create one."+msgstr "Nenhuma correspondência. Digite para criar uma."+msgid "No materials"msgstr "Nenhum material"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 3b82a71186..192fcbe8fb 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -38,6 +38,10 @@ msgstr "\"{taskName}\" выполнена — все {0} элементов еёmsgid "(excluded for this customer)"msgstr "(исключено для этого клиента)"+#. placeholder {0}: open.length+msgid "{0, plural, one {This part is on 1 open change order} other {This part is on # open change orders}}"+msgstr "{0, plural, one {Эта деталь находится в 1 открытом приказе об изменении} other {Эта деталь находится в # открытых приказах об изменении}}"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} клиентов с остатком"@@ -211,6 +215,9 @@ msgstr "90 дней"msgid "A Carbon-run data migration — you load your own data"msgstr "Миграция данных, управляемая Carbon — вы загружаете свои собственные данные"+msgid "A change order tracks a controlled engineering or manufacturing change through review and implementation."+msgstr "Приказ об изменении отслеживает контролируемое инженерное или производственное изменение на этапах проверки и внедрения."+msgid "A clearing account holding the value of goods received but not yet billed; the supplier invoice clears it."msgstr "Расчетный счет, содержащий стоимость полученных, но не выставленных счетом товаров; счет поставщика его закрывает."@@ -502,6 +509,9 @@ msgstr "Первоначальная стоимость"msgid "Acquisition Date"msgstr "Дата приобретения"+msgid "Action"+msgstr "Действие"+msgid "Action Status"msgstr "Статус действия"@@ -592,6 +602,9 @@ msgstr "Добавить действия"msgid "Add Adjustment"msgstr "Добавить корректировку"+msgid "Add Affected Item"+msgstr "Добавить затронутый элемент"+msgid "Add any notes about your decision..."msgstr "Добавьте любые заметки о вашем решении..."@@ -670,9 +683,6 @@ msgstr "Добавить вопрос"msgid "Add Receipt"msgstr "Добавить приходную накладную"-msgid "Add Required Actions"-msgstr "Добавить требуемые действия"-msgid "Add Requirement"msgstr "Добавить требование"@@ -719,6 +729,9 @@ msgstr "Дополнительно"msgid "Add-On Cost"msgstr "Дополнительная стоимость"+msgid "Added"+msgstr "Добавлено"+msgid "Added for this customer"msgstr "Добавлено для этого клиента"@@ -737,9 +750,15 @@ msgstr "Адрес, строка 2"msgid "Adjustment Type"msgstr "Тип корректировки"+msgid "Advance to {nextStatus}"+msgstr "Перейти к {nextStatus}"+msgid "Advanced"msgstr "Дополнительно"+msgid "Affected item not found."+msgstr "Затронутый элемент не найден."+msgid "After"msgstr "После"@@ -846,6 +865,9 @@ msgstr "Учетная запись капитализированного элmsgid "An asset's acquisition cost minus accumulated depreciation — what it's still worth on the books, and the figure it's disposed at."msgstr "Первоначальная стоимость активов минус накопленная амортизация — его текущая балансовая стоимость и сумма, по которой он ликвидируется."+msgid "An engineering change: the affected items whose methods are revised on a draft and released together, superseding the versions they replace."+msgstr "Инженерное изменение: затронутые элементы, методы которых пересмотрены в черновике и выпущены вместе, заменяя версии, которые они заменяют."+msgid "An integration or a custom change — the small slice that's actually custom."msgstr "Интеграция или пользовательское изменение — небольшая часть, которая действительно является пользовательской."@@ -1033,6 +1055,10 @@ msgstr "Вы уверены, что хотите активировать проmsgid "Are you sure you want to activate this gauge?."msgstr "Вы уверены, что хотите активировать этот прибор?."+#. placeholder {0}: routeData?.changeOrder?.changeOrderId ?? ""+msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."+msgstr "Вы уверены, что хотите отменить {0}? Он будет закрыт и доступен только для чтения, пока вы его не откроете."+#. placeholder {0}: routeData?.rfqSummary ?.rfqId!msgid "Are you sure you want to cancel {0}? This will also cancel all related supplier quotes."msgstr "Вы уверены, что хотите отменить {0}? Это также отменит все связанные предложения поставщиков."@@ -1123,6 +1149,14 @@ msgstr "Вы уверены, что хотите удалить счет: {0}{1}msgid "Are you sure you want to delete the API key: {0}? This cannot be undone."msgstr "Вы уверены, что хотите удалить API ключ: {0}? Это действие невозможно отменить."+#. placeholder {0}: requiredAction.name+msgid "Are you sure you want to delete the change order action: {0}? This cannot be undone."+msgstr "Вы уверены, что хотите удалить действие приказа об изменении: {0}? Это невозможно отменить."++#. placeholder {0}: changeOrderType.name+msgid "Are you sure you want to delete the change order category: {0}? This cannot be undone."+msgstr "Вы уверены, что хотите удалить категорию приказа об изменении: {0}? Это действие невозможно отменить."+msgid "Are you sure you want to delete the contractor: {name}? This cannot be undone."msgstr "Вы уверены, что хотите удалить подрядчика: {name}? Это действие невозможно отменить."@@ -1281,6 +1315,9 @@ msgstr "Вы уверены, что хотите удалить webhook: {0}? Эmsgid "Are you sure you want to delete this approval rule? This cannot be undone."msgstr "Вы уверены, что хотите удалить это правило утверждения? Это действие невозможно отменить."+msgid "Are you sure you want to delete this change order?"+msgstr "Вы уверены, что хотите удалить этот приказ об изменении?"+msgid "Are you sure you want to delete this gauge?"msgstr "Вы уверены, что хотите удалить этот манометр?"@@ -1893,6 +1930,12 @@ msgstr "Не удается загрузить этот файл"msgid "Cancel"msgstr "Отмена"+msgid "Cancel change order"+msgstr "Отменить заказ на внесение изменений"++msgid "Cancel Change Order"+msgstr "Отменить заказ на внесение изменений"+msgid "Cancel Job"msgstr "Отменить задание"@@ -2055,12 +2098,30 @@ msgstr "Чемпионы"msgid "Change"msgstr "Изменить"+msgid "Change order"+msgstr "Приказ об изменении"++msgid "Change Order"+msgstr "Приказ об изменении"++msgid "Change Order Actions"+msgstr "Действия приказа об изменении"++msgid "Change Order Types"+msgstr "Типы приказов об изменении"++msgid "Change Orders"+msgstr "Приказы об изменении"+msgid "Change status"msgstr "Изменить статус"msgid "Change the item type (e.g. Part, Material, Tool, etc.)"msgstr "Измените тип элемента (например, Деталь, Материал, Инструмент и т. д.)"+msgid "Change type"+msgstr "Тип изменения"+msgid "Change Type"msgstr "Изменить тип"@@ -2076,6 +2137,9 @@ msgstr "Это изменение перезапишет существующиmsgid "Changing this will update the part ID"msgstr "Изменение этого обновит ID детали"+msgid "Changing type resets this item's draft edits."+msgstr "Изменение типа сбрасывает черновые редактирования этого элемента."+msgid "Chart of accounts"msgstr "План счетов"@@ -2411,6 +2475,9 @@ msgstr "Подтвердить"msgid "Confirm {0}"msgstr "Подтвердить {0}"+msgid "Confirm & release"+msgstr "Подтвердить и выпустить"+msgid "Confirm and sign the scope"msgstr "Подтвердите и подпишите объем работ"@@ -2549,6 +2616,9 @@ msgstr "Контроллер, Бухгалтер"msgid "Controls how planning handles a discontinued item: Consume First exhausts on-hand before switching to the successor, Prefer New redirects new demand to the successor immediately, Stock Only keeps only a minimum service reserve, and No Stock drops the item from planning entirely."msgstr "Контролирует, как планирование обрабатывает снятый с производства товар: «Сначала потребить» исчерпывает имеющийся запас перед переходом на преемника, «Предпочесть новый» немедленно перенаправляет новый спрос на преемника, «Только запас» сохраняет только минимальный резерв для обслуживания, а «Без запаса» полностью исключает товар из планирования."+msgid "Controls whether the bill of material and bill of process of a released (Production) revision can be edited outside a change order."+msgstr "Контролирует, может ли спецификация и технологическая документация выпущенной (производственной) редакции редактироваться вне приказа об изменении."+msgid "Convention"msgstr "Соглашение"@@ -2630,6 +2700,9 @@ msgstr "Скопировать номер задания"msgid "Copy link"msgstr "Копировать ссылку"+msgid "Copy link to change order"+msgstr "Скопировать ссылку на приказ об изменении"+msgid "Copy link to consumable"msgstr "Скопировать ссылку на расходный материал"@@ -2848,6 +2921,9 @@ msgstr "Создать {0} значений"msgid "Create & Snapshot"msgstr "Создать и снимок"+msgid "Create a change order for the new revision and open it"+msgstr "Создать приказ об изменении для новой редакции и открыть его"+msgid "Create a new kanban card for scan-based replenishment."msgstr "Создайте новую карточку канбана для пополнения на основе сканирования."@@ -2875,6 +2951,9 @@ msgstr "Создавать и утверждать заказы на покупmsgid "Create audit trail entries"msgstr "Создать записи в журнале аудита"+msgid "Create Change Order"+msgstr "Создать приказ об изменении"+msgid "Create Issue"msgstr "Создать проблему"@@ -2932,6 +3011,12 @@ msgstr "Создано"msgid "Created By"msgstr "Создано"+msgid "Created change order action"+msgstr "Создано действие приказа об изменении"++msgid "Created change order type"+msgstr "Создан тип заказа на внесение изменений"+msgid "Created consumable"msgstr "Расходный материал создан"@@ -3550,6 +3635,12 @@ msgstr "Удалить {periodLabel}"msgid "Delete {storageUnitName}"msgstr "Удалить {storageUnitName}"+msgid "Delete action"+msgstr "Удалить действие"++msgid "Delete Action"+msgstr "Удалить действие"+msgid "Delete API Key"msgstr "Удалить API ключ"@@ -3565,6 +3656,9 @@ msgstr "Удалить атрибут"msgid "Delete Category"msgstr "Удалить категорию"+msgid "Delete Change Order"+msgstr "Удалить приказ об изменении"+msgid "Delete Consumable"msgstr "Удалить расходный материал"@@ -3794,6 +3888,9 @@ msgstr "Удалить передачу"msgid "Delete Transfer Line"msgstr "Удалить строку передачи"+msgid "Delete Type"+msgstr "Удалить тип"+msgid "Delete Unit of Measure"msgstr "Удалить единицу измерения"@@ -3884,6 +3981,9 @@ msgstr "Описание"msgid "Description (optional)"msgstr "Описание (необязательно)"+msgid "Description of Change"+msgstr "Описание изменения"+msgid "Description of Issue"msgstr "Описание проблемы"@@ -3929,6 +4029,9 @@ msgstr "Отключено"msgid "Discard"msgstr "Отклонить"+msgid "Discontinuation date"+msgstr "Дата прекращения"+msgid "Discontinuation Date"msgstr "Дата снятия с производства"@@ -4196,6 +4299,9 @@ msgstr "Редактировать Рабочий процесс <0>Проблеmsgid "Edit Account"msgstr "Редактировать счет"+msgid "Edit Action"+msgstr "Редактировать действие"+msgid "Edit API Key"msgstr "Редактировать API ключ"@@ -4217,6 +4323,15 @@ msgstr "Редактировать категорию атрибута"msgid "Edit Category"msgstr "Редактировать категорию"+msgid "Edit Change Order"+msgstr "Редактировать приказ об изменении"++msgid "Edit Change Order Action"+msgstr "Редактировать действие приказа об изменении"++msgid "Edit Change Order Type"+msgstr "Редактировать тип заказа на внесение изменений"+msgid "Edit column visibility"msgstr "Изменить видимость столбцов"@@ -4466,6 +4581,9 @@ msgstr "Редактировать передачу"msgid "Edit Transfer Line"msgstr "Редактировать строку передачи"+msgid "Edit Type"+msgstr "Редактировать тип"+msgid "Edit Unit of Measure"msgstr "Редактировать единицу измерения"@@ -4583,6 +4701,9 @@ msgstr "Конец последнего квартала"msgid "End Time"msgstr "Время окончания"+msgid "Enforce — edits are blocked"+msgstr "Принудить — редактирование заблокировано"+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Обеспечьте валидацию и рекомендации для каждого товара в квитанциях, отправках, передачах и корректировках."@@ -6004,6 +6125,9 @@ msgstr "II (обычно по умолчанию)"msgid "III (tightened)"msgstr "III (ужесточено)"+msgid "Impact"+msgstr "Воздействие"+msgid "Imperial"msgstr "Имперская"@@ -6551,6 +6675,9 @@ msgstr "Сохранить текущие"msgid "Keep existing pricing, only add new items"msgstr "Сохранить существующие цены, добавить только новые товары"+msgid "Keep Open"+msgstr "Оставить открытым"+msgid "Key"msgstr "Ключ"@@ -6655,6 +6782,9 @@ msgstr "Оставить все связанные квитанции без иmsgid "Leave blank for built-in"msgstr "Оставьте пустым для встроенного"+msgid "Leave blank to use the next revision automatically"+msgstr "Оставьте пусто для использования следующей редакции автоматически"+msgid "Leave empty for exact match"msgstr "Оставьте пустым для точного совпадения"@@ -6750,6 +6880,9 @@ msgstr "Связать проблему Linear"msgid "Linked entity quantity ({0}) does not match row quantity ({1})."msgstr "Количество связанной сущности ({0}) не совпадает с количеством строки ({1})."+msgid "Linked NCR"+msgstr "Связанное NCR"+msgid "Linked PO"msgstr "Связанный ПО"@@ -7352,6 +7485,9 @@ msgstr "Модель удалена из задания"msgid "Model removed from line"msgstr "Модель удалена из строки"+msgid "Modified"+msgstr "Изменено"+msgid "Module"msgstr "Модуль"@@ -7501,6 +7637,15 @@ msgstr "Новый атрибут"msgid "New Attribute Category"msgstr "Новая категория атрибутов"+msgid "New Change Order"+msgstr "Новый приказ на изменение"++msgid "New Change Order Action"+msgstr "Новое действие приказа об изменении"++msgid "New Change Order Type"+msgstr "Новый тип заказа на внесение изменений"+msgid "New Consumable"msgstr "Новый расходный материал"@@ -7815,6 +7960,12 @@ msgstr "Нет активных предложений"msgid "No addresses found"msgstr "Адреса не найдены"+msgid "No affected items to assess."+msgstr "Нет затронутых элементов для оценки."++msgid "No affected items."+msgstr "Нет затронутых элементов."+msgid "No applications. Payment will be on-account."msgstr "Нет приложений. Платеж будет на счет."@@ -7840,6 +7991,9 @@ msgstr "Записи о калибровке не найдены"msgid "No changes recorded"msgstr "Изменений не записано"+msgid "No changes yet."+msgstr "Пока нет изменений."+msgid "No comments yet. Be the first to add a comment."msgstr "Нет комментариев. Будьте первым, кто добавит комментарий."@@ -7867,12 +8021,18 @@ msgstr "Нет запланированных выходных"msgid "No default attachments yet."msgstr "Пока нет вложений по умолчанию."+msgid "No draft make method for this item yet."+msgstr "Пока нет чернового метода производства для этого элемента."+msgid "No draft versions available"msgstr "Нет доступных черновиков версий"msgid "No due date"msgstr "Нет срока выполнения"+msgid "No editable properties for this item."+msgstr "Нет редактируемых свойств для этого элемента."+msgid "No employees assigned yet. Add groups to see status."msgstr "Сотрудники еще не назначены. Добавьте группы, чтобы увидеть статус."@@ -7897,6 +8057,9 @@ msgstr "Поля не найдены."msgid "No files"msgstr "Нет файлов"+msgid "No files for this item."+msgstr "Нет файлов для этого элемента."+msgid "No files uploaded"msgstr "Файлы не загружены"@@ -7933,6 +8096,9 @@ msgstr "Нет совпадений"msgid "No matches for \"{query}\". Try a different search term."msgstr "Нет совпадений для \"{query}\". Попробуйте другой поисковый запрос."+msgid "No matches. Type to create one."+msgstr "Совпадений не найдено. Введите текст для создания."+msgid "No new notifications"msgstr "Нет новых уведомлений"@@ -8098,6 +8264,9 @@ msgstr "Не таблица, а баланс главной книги: стоиmsgid "Not enough jobs to cover quantity"msgstr "Недостаточно заданий для покрытия количества"+msgid "Not referenced anywhere yet."+msgstr "Пока не на что-либо ссылается."+msgid "Not Required"msgstr "Не требуется"@@ -8149,6 +8318,9 @@ msgstr "OEM (производитель оригинального оборудmsgid "of"msgstr "из"+msgid "Off — released revisions stay editable"+msgstr "Выключено — выпущенные версии остаются редактируемыми"+msgid "OK"msgstr "ОК"@@ -8236,6 +8408,9 @@ msgstr "Упс! Ссылка, которую вы пытаетесь открыmsgid "Open"msgstr "Открыть"+msgid "Open a change order"+msgstr "Открыть приказ об изменении"+msgid "Open Actions"msgstr "Открытые действия"@@ -8251,6 +8426,9 @@ msgstr "Открытая дебиторская задолженность"msgid "Open Audit Log"msgstr "Открыть журнал аудита"+msgid "Open change orders affecting this part"+msgstr "Открытые приказы на изменение, влияющие на эту деталь"+msgid "Open Date"msgstr "Дата открытия"@@ -8504,6 +8682,9 @@ msgstr "Перезаписать метод предложения исходнmsgid "Overwrite the target manufacturing method with the quote method"msgstr "Перезаписать целевой производственный метод методом предложения"+msgid "Owner"+msgstr "Владелец"+msgid "Owner (cost center)"msgstr "Главный центр затрат"@@ -8568,6 +8749,12 @@ msgstr "ID детали"msgid "Part is configured for manufacturing"msgstr "Деталь настроена для производства"+msgid "Part Number"+msgstr "Номер детали"++msgid "Part Supersession"+msgstr "Замена детали"+msgid "Partial"msgstr "Частичный"@@ -9531,6 +9718,9 @@ msgstr "Причина"msgid "Reason Account"msgstr "Счет причины"+msgid "Reason for Change"+msgstr "Причина изменения"+msgid "Reason for declining (Optional)"msgstr "Причина отказа (Необязательно)"@@ -9733,12 +9923,27 @@ msgstr "Относительная шкала времени · даты будmsgid "Release"msgstr "Выпуск"+msgid "Release change order"+msgstr "Выпустить заказ на изменение"++msgid "Release control"+msgstr "Контроль выпуска"++msgid "Release Control"+msgstr "Контроль выпуска"+msgid "Release Job"msgstr "Выпустить задание"msgid "Released"msgstr "Выпущено"+msgid "Released revision"+msgstr "Выпущенная версия"++msgid "Released revision is locked"+msgstr "Выпущенная версия заблокирована"+msgid "Remaining"msgstr "Остаток"@@ -9785,6 +9990,9 @@ msgstr "Удалить сортировку по столбцу"msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."msgstr "Удалите этот тип хранилища из всех ссылающихся на него единиц хранения и удалите его. Это невозможно отменить."+msgid "Removed"+msgstr "Удалено"+msgid "Rendering label preview..."msgstr "Отрисовка предпросмотра этикетки..."@@ -10006,6 +10214,9 @@ msgstr "Налог на продажи с обратным взиманием (msgid "Reverse the related journal entries"msgstr "Отменить связанные записи в журнале"+msgid "Review each item's changes, then confirm — releasing can't be undone."+msgstr "Просмотрите изменения каждого элемента, затем подтвердите — выпуск нельзя отменить."+msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Проверьте балансовый лист и отчёт о прибылях и убытках за период и подтвердите, что цифры выглядят правильно. Это ручное утверждение — отметьте как завершённое после их проверки."@@ -10019,6 +10230,9 @@ msgstr "Редакция"msgid "Revision {0}"msgstr "Версия {0}"+msgid "Revisions"+msgstr "Версии"+msgid "Revoke"msgstr "Отозвать"@@ -11361,6 +11575,9 @@ msgstr "Предложение успешно скопировано"msgid "Successfully created a new revision"msgstr "Успешно создана новая редакция"+msgid "Successor effectivity"+msgstr "Эффективность преемника"+msgid "Successor Effectivity Date"msgstr "Дата вступления преемника в силу"@@ -12432,6 +12649,9 @@ msgstr "Эта информация будет использована в заmsgid "This information will be visible to all users, so be careful what you share."msgstr "Эта информация будет видна всем пользователям, поэтому будьте осторожны с тем, что вы делитесь."+msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."+msgstr "Это купленный элемент — у него нет BoM/BoP; могут изменяться только его атрибуты и документы."+msgid "This is a unique identifier for the webhook"msgstr "Это уникальный идентификатор для вебхука"@@ -12489,6 +12709,12 @@ msgstr "В этот период не размещены записи журнаmsgid "This Quarter"msgstr "Этот квартал"+msgid "This revision is released (Production). Changes should normally flow through a change order."+msgstr "Эта версия выпущена (Production). Изменения должны обычно проходить через заказ на изменение."++msgid "This revision is released (Production). Open a change order to modify it."+msgstr "Эта версия выпущена (Production). Откройте заказ на изменение, чтобы изменить её."+msgid "This sales order has associated jobs. Choose what to do with them."msgstr "Этот заказ на продажу имеет связанные работы. Выберите, что с ними делать."@@ -12531,6 +12757,9 @@ msgstr "Это заменит все материалы методов другmsgid "This will replace all method materials of other sizes with this size."msgstr "Это заменит все материалы методов других размеров на этот размер."+msgid "This will set the current version of the make method to Active, making it read-only."+msgstr "Это установит текущую версию способа изготовления на активную, сделав её доступной только для чтения."+msgid "This will write off the remaining book value of the asset."msgstr "Это спишет оставшуюся чистую балансовую стоимость актива."@@ -13493,6 +13722,9 @@ msgstr "Склад, Операции"msgid "Warn"msgstr "Предупреждение"+msgid "Warn — edits succeed with a warning"+msgstr "Предупреждение — редактирование выполнено с предупреждением"+msgid "Warn but allow"msgstr "Предупредить, но разрешить"@@ -13624,6 +13856,9 @@ msgstr "Что такое {translatedTerm}?"msgid "What it is"msgstr "Что это такое"+msgid "What kind of change this is: Version updates how the part is made, Revision edits its details and documents, and New Part replaces it with a new part number."+msgstr "Какой это тип изменения: Version обновляет способ изготовления детали, Revision редактирует её детали и документы, а New Part заменяет её новым номером детали."+msgid "What kind of output this entry records — Production (good units), Scrap (unrecoverable), or Rework (sent back for correction); reveals Scrap Reason when Scrap."msgstr "Какой тип выхода записывает эта запись — Производство (хорошие единицы), Отходы (невозвратные) или Переработка (отправлено на исправление); показывает Причину отходов при отходах."@@ -13783,6 +14018,9 @@ msgstr "Куда новый запас этого товара попадаетmsgid "Where stock lives and how it ships."msgstr "Где находится запас и как он отправляется."+msgid "Where the affected items are used across the system. Informational — nothing here blocks releasing."+msgstr "Где затронутые элементы используются по всей системе. Информационно — ничто здесь не блокирует выпуск."+msgid "Where this entry originated (manual entry, posting from sales/purchasing, recurring template, etc.)."msgstr "Откуда произошла эта запись (ручной ввод, контировка из продаж/покупок, повторяющийся шаблон и т. д.)."@@ -14067,6 +14305,9 @@ msgstr "Вы отметились на работу {hoursElapsed} часов нmsgid "Your books and how money flows."msgstr "Ваши книги и движение денежных средств."+msgid "Your changes go into a new draft version released with this change order."+msgstr "Ваши изменения переходят в новую черновую версию, выпущенную с этим приказом об изменении."+msgid "Your Console PIN"msgstr "Ваш PIN консоли"diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.poindex 1b431ca985..ce9f4aea4d 100644--- a/packages/locale/locales/ru/mes.po+++ b/packages/locale/locales/ru/mes.po@@ -610,6 +610,9 @@ msgstr "Без влияния"msgid "No maintenance scheduled for today"msgstr "На сегодня обслуживание не запланировано"+msgid "No matches. Type to create one."+msgstr "Совпадений не найдено. Введите текст для создания."+msgid "No materials"msgstr "Нет материалов"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 1ba755b49e..d269bb3581 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -38,6 +38,10 @@ msgstr "\"{taskName}\" tamamlandı — tüm {0} Setup Haritası öğesi yapılanmsgid "(excluded for this customer)"msgstr "(bu müşteri için hariç tutulmuş)"+#. placeholder {0}: open.length+msgid "{0, plural, one {This part is on 1 open change order} other {This part is on # open change orders}}"+msgstr "{0, plural, one {Bu parça 1 açık değişiklik emrinde} other {Bu parça # açık değişiklik emrinde}}"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} müşteri bakiye ile"@@ -211,6 +215,9 @@ msgstr "90G"msgid "A Carbon-run data migration — you load your own data"msgstr "Bir Carbon tarafından yönetilen veri taşıması — kendi verilerinizi yüklersiniz"+msgid "A change order tracks a controlled engineering or manufacturing change through review and implementation."+msgstr "Değişiklik emri, kontrollü bir mühendislik veya üretim değişikliğini inceleme ve uygulanmasında takip eder."+msgid "A clearing account holding the value of goods received but not yet billed; the supplier invoice clears it."msgstr "Alınan ancak henüz faturalanmayan malların değerini tutan bir takas hesabı; tedarikçi faturası bunu temizler."@@ -502,6 +509,9 @@ msgstr "Satın alma maliyeti"msgid "Acquisition Date"msgstr "Satın alma tarihi"+msgid "Action"+msgstr "İşlem"+msgid "Action Status"msgstr "Aksiyon Durumu"@@ -592,6 +602,9 @@ msgstr "Eylemler Ekle"msgid "Add Adjustment"msgstr "Ayarlama ekle"+msgid "Add Affected Item"+msgstr "Etkilenen Öğe Ekle"+msgid "Add any notes about your decision..."msgstr "Kararınızla ilgili herhangi bir not ekleyin..."@@ -670,9 +683,6 @@ msgstr "Soru Ekle"msgid "Add Receipt"msgstr "Makbuz Ekle"-msgid "Add Required Actions"-msgstr "Gerekli Eylemler Ekle"-msgid "Add Requirement"msgstr "Gereksinim Ekle"@@ -719,6 +729,9 @@ msgstr "Ek Üzerine Ek"msgid "Add-On Cost"msgstr "Ek Üst Ek Maliyeti"+msgid "Added"+msgstr "Eklendi"+msgid "Added for this customer"msgstr "Bu müşteri için eklendi"@@ -737,9 +750,15 @@ msgstr "Adres Satırı 2"msgid "Adjustment Type"msgstr "Ayarlama Türü"+msgid "Advance to {nextStatus}"+msgstr "{nextStatus} konumuna geç"+msgid "Advanced"msgstr "Gelişmiş"+msgid "Affected item not found."+msgstr "Etkilenen öğe bulunamadı."+msgid "After"msgstr "Sonra"@@ -846,6 +865,9 @@ msgstr "Harcama yerine amorti ettiğiniz kapitalize edilmiş bir öğe için birmsgid "An asset's acquisition cost minus accumulated depreciation — what it's still worth on the books, and the figure it's disposed at."msgstr "Bir varlığın satın alma maliyeti eksi birikmiş amortisman — kitaplarda halen değeri olan ve imha edildiği tutar."+msgid "An engineering change: the affected items whose methods are revised on a draft and released together, superseding the versions they replace."+msgstr "Bir mühendislik değişikliği: yöntemleri taslak üzerinde revize edilen ve birlikte yayınlanan, yerini aldıkları sürümlerin yerine geçen etkilenen öğeler."+msgid "An integration or a custom change — the small slice that's actually custom."msgstr "Bir entegrasyon veya özel bir değişiklik — aslında özel olan küçük dilim."@@ -1033,6 +1055,10 @@ msgstr "İş akışını etkinleştirmek istediğinizden emin misiniz: {name}? Tmsgid "Are you sure you want to activate this gauge?."msgstr "Bu kalibratörü etkinleştirmek istediğinizden emin misiniz?."+#. placeholder {0}: routeData?.changeOrder?.changeOrderId ?? ""+msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."+msgstr "{0} öğesini iptal etmek istediğinizden emin misiniz? Yeniden açana kadar kapalı ve salt okunur durumda olacaktır."+#. placeholder {0}: routeData?.rfqSummary ?.rfqId!msgid "Are you sure you want to cancel {0}? This will also cancel all related supplier quotes."msgstr "{0}'yi iptal etmek istediğinizden emin misiniz? Bu aynı zamanda tüm ilgili tedarikçi tekliflerini de iptal edecektir."@@ -1123,6 +1149,14 @@ msgstr "Hesabı silmek istediğinizden emin misiniz: {0}{1}? Bu geri alınamaz."msgid "Are you sure you want to delete the API key: {0}? This cannot be undone."msgstr "API anahtarını silmek istediğinizden emin misiniz: {0}? Bu geri alınamaz."+#. placeholder {0}: requiredAction.name+msgid "Are you sure you want to delete the change order action: {0}? This cannot be undone."+msgstr "Değişiklik emri işlemini silmek istediğinizden emin misiniz: {0}? Bu geri alınamaz."++#. placeholder {0}: changeOrderType.name+msgid "Are you sure you want to delete the change order category: {0}? This cannot be undone."+msgstr "Değişiklik emri kategorisini silmek istediğinizden emin misiniz: {0}? Bu işlem geri alınamaz."+msgid "Are you sure you want to delete the contractor: {name}? This cannot be undone."msgstr "Yükleniciyi silmek istediğinizden emin misiniz: {name}? Bu geri alınamaz."@@ -1281,6 +1315,9 @@ msgstr "Webhook'u silmek istediğinizden emin misiniz: {0}? Bu geri alınamaz."msgid "Are you sure you want to delete this approval rule? This cannot be undone."msgstr "Bu onay kuralını silmek istediğinizden emin misiniz? Bu geri alınamaz."+msgid "Are you sure you want to delete this change order?"+msgstr "Bu değişiklik emrini silmek istediğinizden emin misiniz?"+msgid "Are you sure you want to delete this gauge?"msgstr "Bu kalibratörü silmek istediğinizden emin misiniz?"@@ -1893,6 +1930,12 @@ msgstr "Bu dosya indirilemiyor"msgid "Cancel"msgstr "İptal"+msgid "Cancel change order"+msgstr "Değişiklik emrini iptal et"++msgid "Cancel Change Order"+msgstr "Değişiklik Emrini İptal Et"+msgid "Cancel Job"msgstr "İşi İptal Et"@@ -2055,12 +2098,30 @@ msgstr "Şampiyonlar"msgid "Change"msgstr "Değiştir"+msgid "Change order"+msgstr "Değişiklik emri"++msgid "Change Order"+msgstr "Değişiklik Emri"++msgid "Change Order Actions"+msgstr "Değişiklik Emri İşlemleri"++msgid "Change Order Types"+msgstr "Değişiklik Emri Türleri"++msgid "Change Orders"+msgstr "Değişiklik Emirleri"+msgid "Change status"msgstr "Durum değiştir"msgid "Change the item type (e.g. Part, Material, Tool, etc.)"msgstr "Ürün türünü değiştirin (örneğin Parça, Malzeme, Alet vb.)"+msgid "Change type"+msgstr "Türü değiştir"+msgid "Change Type"msgstr "Tipi Değiştir"@@ -2076,6 +2137,9 @@ msgstr "Bunu değiştirmek mevcut yöntemi geçersiz kılacaktır"msgid "Changing this will update the part ID"msgstr "Bunu değiştirmek parça kimliğini güncelleyecektir"+msgid "Changing type resets this item's draft edits."+msgstr "Türü değiştirmek bu öğenin taslak düzenlemelerini sıfırlar."+msgid "Chart of accounts"msgstr "Muhasebe planı"@@ -2411,6 +2475,9 @@ msgstr "Onayla"msgid "Confirm {0}"msgstr "Onayla {0}"+msgid "Confirm & release"+msgstr "Onayla ve yayınla"+msgid "Confirm and sign the scope"msgstr "Kapsamı onaylayın ve imzalayın"@@ -2549,6 +2616,9 @@ msgstr "Kontrolör, Muhasebeci"msgid "Controls how planning handles a discontinued item: Consume First exhausts on-hand before switching to the successor, Prefer New redirects new demand to the successor immediately, Stock Only keeps only a minimum service reserve, and No Stock drops the item from planning entirely."msgstr "Planlamanın kullanımdan kaldırılan bir öğeyi nasıl işlediğini kontrol eder: Önce Tüket mevcut stoğu tüketir ve ardından halefi kullanmaya geçer, Yeni Tercih et yeni talebi hemen halefi yönlendirir, Yalnızca Stok minimum bir hizmet rezervi tutar ve Stok Yok öğeyi planlama işleminden tamamen çıkarır.\""+msgid "Controls whether the bill of material and bill of process of a released (Production) revision can be edited outside a change order."+msgstr "Yayınlanan (Üretim) revizyonunun malzeme listesi ve işlem listesinin bir değişiklik emri dışında düzenlenip düzenlenmeyeceğini kontrol eder."+msgid "Convention"msgstr "Sözleşme"@@ -2630,6 +2700,9 @@ msgstr "İş Numarasını Kopyala"msgid "Copy link"msgstr "Bağlantıyı kopyala"+msgid "Copy link to change order"+msgstr "Değişiklik emri bağlantısını kopyala"+msgid "Copy link to consumable"msgstr "Tüketilebilir bağlantısını kopyala"@@ -2848,6 +2921,9 @@ msgstr "{0} değerleri oluştur"msgid "Create & Snapshot"msgstr "Oluştur & Anlık Görüntü"+msgid "Create a change order for the new revision and open it"+msgstr "Yeni revizyon için bir değişiklik emri oluşturun ve açın"+msgid "Create a new kanban card for scan-based replenishment."msgstr "Tarama tabanlı ikmal için yeni bir kanban kartı oluştur."@@ -2875,6 +2951,9 @@ msgstr "Satın alma siparişleri oluşturun ve onaylayın"msgid "Create audit trail entries"msgstr "Denetim izi girdileri oluştur"+msgid "Create Change Order"+msgstr "Değişiklik Emri Oluştur"+msgid "Create Issue"msgstr "Sorun Oluştur"@@ -2932,6 +3011,12 @@ msgstr "Oluşturulma Tarihi"msgid "Created By"msgstr "Oluşturan"+msgid "Created change order action"+msgstr "Oluşturulan değişiklik emri işlemi"++msgid "Created change order type"+msgstr "Oluşturulan değişiklik emri türü"+msgid "Created consumable"msgstr "Tüketilebilir malzeme oluşturuldu"@@ -3550,6 +3635,12 @@ msgstr "{periodLabel} öğesini sil"msgid "Delete {storageUnitName}"msgstr "Delete {storageUnitName}"+msgid "Delete action"+msgstr "Eylemi sil"++msgid "Delete Action"+msgstr "İşlemi Sil"+msgid "Delete API Key"msgstr "API Anahtarını Sil"@@ -3565,6 +3656,9 @@ msgstr "Özniteliği Sil"msgid "Delete Category"msgstr "Kategoriyi Sil"+msgid "Delete Change Order"+msgstr "Değişiklik Emrini Sil"+msgid "Delete Consumable"msgstr "Tüketilebilir Malı Sil"@@ -3794,6 +3888,9 @@ msgstr "Transferi Sil"msgid "Delete Transfer Line"msgstr "Transfer Satırını Sil"+msgid "Delete Type"+msgstr "Türü Sil"+msgid "Delete Unit of Measure"msgstr "Ölçü Birimini Sil"@@ -3884,6 +3981,9 @@ msgstr "Açıklama"msgid "Description (optional)"msgstr "Açıklama (isteğe bağlı)"+msgid "Description of Change"+msgstr "Değişiklimin Açıklaması"+msgid "Description of Issue"msgstr "Sorun Açıklaması"@@ -3929,6 +4029,9 @@ msgstr "Devre Dışı"msgid "Discard"msgstr "Atıkla"+msgid "Discontinuation date"+msgstr "Kullanımdan kaldırılma tarihi"+msgid "Discontinuation Date"msgstr "Üretim Durdurma Tarihi"@@ -4196,6 +4299,9 @@ msgstr "<0>Sorun</0> İş Akışını Düzenle"msgid "Edit Account"msgstr "Hesabı Düzenle"+msgid "Edit Action"+msgstr "İşlemi Düzenle"+msgid "Edit API Key"msgstr "API Anahtarını Düzenle"@@ -4217,6 +4323,15 @@ msgstr "Öznitelik Kategorisini Düzenle"msgid "Edit Category"msgstr "Kategoriyi Düzenle"+msgid "Edit Change Order"+msgstr "Değişiklik Emrini Düzenle"++msgid "Edit Change Order Action"+msgstr "Değişiklik Emri İşlemini Düzenle"++msgid "Edit Change Order Type"+msgstr "Değişiklik Emri Türünü Düzenle"+msgid "Edit column visibility"msgstr "Sütun görünürlüğünü düzenle"@@ -4466,6 +4581,9 @@ msgstr "Transferi Düzenle"msgid "Edit Transfer Line"msgstr "Transfer Satırını Düzenle"+msgid "Edit Type"+msgstr "Türü Düzenle"+msgid "Edit Unit of Measure"msgstr "Birim Ölçü Düzenle"@@ -4583,6 +4701,9 @@ msgstr "Son Çeyreğin Sonu"msgid "End Time"msgstr "Bitiş Saati"+msgid "Enforce — edits are blocked"+msgstr "Zorunlu — düzenlemeler engellendi"+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Alışmalar, sevkiyatlar, transferler ve ayarlamalarda kalem bazında doğrulama ve yönergeleri zorunlu kılın."@@ -6004,6 +6125,9 @@ msgstr "II (normal varsayılan)"msgid "III (tightened)"msgstr "III (sıklaştırılmış)"+msgid "Impact"+msgstr "Etki"+msgid "Imperial"msgstr "İmparatorluk"@@ -6551,6 +6675,9 @@ msgstr "Mevcut Tut"msgid "Keep existing pricing, only add new items"msgstr "Mevcut fiyatlandırmayı koru, yalnızca yeni öğeler ekle"+msgid "Keep Open"+msgstr "Açık Tut"+msgid "Key"msgstr "Anahtar"@@ -6655,6 +6782,9 @@ msgstr "İlgili tüm makbuzları dokunulmamış bırakır"msgid "Leave blank for built-in"msgstr "Yerleşik için boş bırakın"+msgid "Leave blank to use the next revision automatically"+msgstr "Sonraki revizyonu otomatik olarak kullanmak için boş bırakın"+msgid "Leave empty for exact match"msgstr "Tam eşleşme için boş bırakın"@@ -6750,6 +6880,9 @@ msgstr "Linear sorununu bağla"msgid "Linked entity quantity ({0}) does not match row quantity ({1})."msgstr "Bağlantılı varlık miktarı ({0}) satır miktarıyla eşleşmiyor ({1})."+msgid "Linked NCR"+msgstr "Bağlantılı NCR"+msgid "Linked PO"msgstr "Bağlantılı Sipariş"@@ -7352,6 +7485,9 @@ msgstr "Model işten kaldırıldı"msgid "Model removed from line"msgstr "Model satırdan kaldırıldı"+msgid "Modified"+msgstr "Değiştirildi"+msgid "Module"msgstr "Modül"@@ -7501,6 +7637,15 @@ msgstr "Yeni Öznitelik"msgid "New Attribute Category"msgstr "Yeni Öznitelik Kategorisi"+msgid "New Change Order"+msgstr "Yeni Değişiklik Emri"++msgid "New Change Order Action"+msgstr "Yeni Değişiklik Emri İşlemi"++msgid "New Change Order Type"+msgstr "Yeni Değişiklik Emri Türü"+msgid "New Consumable"msgstr "Yeni Sarf Malzemesi"@@ -7815,6 +7960,12 @@ msgstr "Aktif Teklif Yok"msgid "No addresses found"msgstr "Adres bulunamadı"+msgid "No affected items to assess."+msgstr "Değerlendirilecek etkilenen öğe yok."++msgid "No affected items."+msgstr "Etkilenen öğe yok."+msgid "No applications. Payment will be on-account."msgstr "Başvuru yok. Ödeme hesap üzerinden yapılacak."@@ -7840,6 +7991,9 @@ msgstr "Kalibrasyon kaydı bulunamadı"msgid "No changes recorded"msgstr "Değişiklik kaydedilmedi"+msgid "No changes yet."+msgstr "Henüz değişiklik yok."+msgid "No comments yet. Be the first to add a comment."msgstr "Henüz yorum yok. İlk yorumu siz yapın."@@ -7867,12 +8021,18 @@ msgstr "Planlanmış izin yok"msgid "No default attachments yet."msgstr "Henüz varsayılan ek dosya yok."+msgid "No draft make method for this item yet."+msgstr "Bu öğe için henüz taslak yapım yöntemi yok."+msgid "No draft versions available"msgstr "Taslak sürüm mevcut değil"msgid "No due date"msgstr "Teslim tarihi yok"+msgid "No editable properties for this item."+msgstr "Bu öğe için düzenlenebilir özellik yok."+msgid "No employees assigned yet. Add groups to see status."msgstr "Henüz çalışan atanmadı. Durumu görmek için gruplar ekleyin."@@ -7897,6 +8057,9 @@ msgstr "Bul alan bulunamadı."msgid "No files"msgstr "Dosya yok"+msgid "No files for this item."+msgstr "Bu öğe için dosya yok."+msgid "No files uploaded"msgstr "Yüklenmiş dosya yok"@@ -7933,6 +8096,9 @@ msgstr "Eşleşme yok"msgid "No matches for \"{query}\". Try a different search term."msgstr "\"{query}\" için eşleşme bulunamadı. Farklı bir arama terbi deneyin."+msgid "No matches. Type to create one."+msgstr "Eşleşme yok. Bir tane oluşturmak için yazın."+msgid "No new notifications"msgstr "Yeni bildirim yok"@@ -8098,6 +8264,9 @@ msgstr "Bir tablo değil, bir genel muhasebe dengesi: iş malzemeleri verildiğimsgid "Not enough jobs to cover quantity"msgstr "Miktarı karşılayacak yeterli iş yok"+msgid "Not referenced anywhere yet."+msgstr "Henüz hiçbir yerde referans verilmemiş."+msgid "Not Required"msgstr "Gerekli Değil"@@ -8149,6 +8318,9 @@ msgstr "OEM (Orijinal Ekipman Üreticisi)"msgid "of"msgstr "adet"+msgid "Off — released revisions stay editable"+msgstr "Kapalı — yayınlanan revizyonlar düzenlenebilir kalır"+msgid "OK"msgstr "Tamam"@@ -8236,6 +8408,9 @@ msgstr "Üzgünüz! Erişim sağlamaya çalıştığınız bağlantı geçerli dmsgid "Open"msgstr "Aç"+msgid "Open a change order"+msgstr "Bir değişiklik emri açın"+msgid "Open Actions"msgstr "Açık Aksiyonlar"@@ -8251,6 +8426,9 @@ msgstr "Açık AR"msgid "Open Audit Log"msgstr "Denetim Kaydını Aç"+msgid "Open change orders affecting this part"+msgstr "Bu parçayı etkileyen açık değişiklik emirleri"+msgid "Open Date"msgstr "Açılış Tarihi"@@ -8504,6 +8682,9 @@ msgstr "Teklif yöntemini kaynak yöntemle üzerine yaz"msgid "Overwrite the target manufacturing method with the quote method"msgstr "Hedef üretim yöntemini teklif yöntemiyle üzerine yaz"+msgid "Owner"+msgstr "Sahip"+msgid "Owner (cost center)"msgstr "Ana maliyet merkezi"@@ -8568,6 +8749,12 @@ msgstr "Parça Kimliği"msgid "Part is configured for manufacturing"msgstr "Parça üretim için yapılandırılmış"+msgid "Part Number"+msgstr "Parça Numarası"++msgid "Part Supersession"+msgstr "Parça Yerini Alma"+msgid "Partial"msgstr "Kısmi"@@ -9531,6 +9718,9 @@ msgstr "Neden"msgid "Reason Account"msgstr "Neden Hesabı"+msgid "Reason for Change"+msgstr "Değişiklik Nedeni"+msgid "Reason for declining (Optional)"msgstr "Reddetme nedeni (İsteğe bağlı)"@@ -9733,12 +9923,27 @@ msgstr "Göreceli zaman çizelgesi · tarihler onaylanacak"msgid "Release"msgstr "Serbest Bırakma"+msgid "Release change order"+msgstr "Değişim emrini yayınla"++msgid "Release control"+msgstr "Yayın kontrolü"++msgid "Release Control"+msgstr "Yayın Kontrolü"+msgid "Release Job"msgstr "İşi Yayınla"msgid "Released"msgstr "Yayınlandı"+msgid "Released revision"+msgstr "Yayınlanan revizyon"++msgid "Released revision is locked"+msgstr "Yayınlanan revizyon kilitlidir"+msgid "Remaining"msgstr "Kalan"@@ -9785,6 +9990,9 @@ msgstr "Sıralamayı kaldır"msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."msgstr "Bu depolama türünü tüm referans veren depolama birimlerinden kaldırır ve siler. Bu geri alınamaz."+msgid "Removed"+msgstr "Kaldırıldı"+msgid "Rendering label preview..."msgstr "Etiket önizlemesi oluşturuluyor..."@@ -10006,6 +10214,9 @@ msgstr "Ters yükleme satış vergisi (varsayılan)"msgid "Reverse the related journal entries"msgstr "İlgili günlük girişlerini tersine çevir"+msgid "Review each item's changes, then confirm — releasing can't be undone."+msgstr "Her ürünün değişikliklerini gözden geçirin, sonra onaylayın — yayınlama geri alınamaz."+msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Dönemin bilançosunu ve gelir tablosunu gözden geçirin ve rakamların doğru göründüğünü doğrulayın. Bu manuel bir onay — bunları gözden geçirdikten sonra bitti olarak işaretleyin."@@ -10019,6 +10230,9 @@ msgstr "Revizyon"msgid "Revision {0}"msgstr "Revizyon {0}"+msgid "Revisions"+msgstr "Revizyonlar"+msgid "Revoke"msgstr "İptal et"@@ -11361,6 +11575,9 @@ msgstr "Başarıyla kopyalandı"msgid "Successfully created a new revision"msgstr "Başarıyla yeni bir revizyon oluşturuldu"+msgid "Successor effectivity"+msgstr "Halef geçerlilik"+msgid "Successor Effectivity Date"msgstr "Halef Etkinlik Tarihi"@@ -12432,6 +12649,9 @@ msgstr "Bu bilgiler belge başlıklarında kullanılacaktır"msgid "This information will be visible to all users, so be careful what you share."msgstr "Bu bilgiler tüm kullanıcılar tarafından görülecektir, bu yüzden ne paylaştığınıza dikkat edin."+msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."+msgstr "Bu satın alınan bir üründür — BoM/BoP'si yoktur; yalnızca öznitelikleri ve belgeleri değişebilir."+msgid "This is a unique identifier for the webhook"msgstr "Bu, web kancası için benzersiz bir tanımlayıcıdır"@@ -12489,6 +12709,12 @@ msgstr "Bu döneme nakledilen günlük girişi yoktur ve kalıcı olarak silinebmsgid "This Quarter"msgstr "Bu Çeyrek"+msgid "This revision is released (Production). Changes should normally flow through a change order."+msgstr "Bu revizyon yayımlandı (Üretim). Değişiklikler normalde bir değişiklik siparişi aracılığıyla akmalıdır."++msgid "This revision is released (Production). Open a change order to modify it."+msgstr "Bu revizyon yayımlandı (Üretim). Bunu değiştirmek için bir değişiklik siparişi açın."+msgid "This sales order has associated jobs. Choose what to do with them."msgstr "Bu satış siparişi ilgili işlere sahiptir. Onlarla ne yapılacağına karar verin."@@ -12531,6 +12757,9 @@ msgstr "Bu, diğer revizyonlardaki tüm yöntem malzemelerini bu revizyonla değmsgid "This will replace all method materials of other sizes with this size."msgstr "Bu, diğer boyutlardaki tüm yöntem malzemelerini bu boyutuyla değiştirecektir."+msgid "This will set the current version of the make method to Active, making it read-only."+msgstr "Bu, üretim yönteminin mevcut sürümünü Etkin olarak ayarlayacak ve salt okunur hale getirecektir."+msgid "This will write off the remaining book value of the asset."msgstr "Bu, varlığın kalan net defter değerini silebilir."@@ -13493,6 +13722,9 @@ msgstr "Depo, Operasyon"msgid "Warn"msgstr "Uyarı"+msgid "Warn — edits succeed with a warning"+msgstr "Uyar — düzenlemeler bir uyarı ile başarılı olur"+msgid "Warn but allow"msgstr "Uyarı ver ama izin ver"@@ -13624,6 +13856,9 @@ msgstr "{translatedTerm} nedir?"msgid "What it is"msgstr "Ne olduğu"+msgid "What kind of change this is: Version updates how the part is made, Revision edits its details and documents, and New Part replaces it with a new part number."+msgstr "Bu ne tür bir değişikliktir: Sürüm parçanın nasıl yapıldığını günceller, Revizyon ayrıntılarını ve belgelerini düzenler ve Yeni Parça onu yeni bir parça numarasıyla değiştirir."+msgid "What kind of output this entry records — Production (good units), Scrap (unrecoverable), or Rework (sent back for correction); reveals Scrap Reason when Scrap."msgstr "Bu giriş hangi tür çıktıyı kaydediyor — Üretim (iyi birimler), Hurda (kurtarılamaz) veya Yeniden İşlem (düzeltme için geri gönderilen); Hurda olduğunda Hurda Nedeni ortaya çıkar."@@ -13783,6 +14018,9 @@ msgstr "Bu öğenin yeni stoku varsayılan olarak alındığında nereye inerkenmsgid "Where stock lives and how it ships."msgstr "Stokun nerede bulunduğu ve nasıl gönderildiği."+msgid "Where the affected items are used across the system. Informational — nothing here blocks releasing."+msgstr "Etkilenen ürünlerin sistem genelinde nerede kullanıldığı. Bilgilendirici — burada hiçbir şey yayınlamayı engellemiyor."+msgid "Where this entry originated (manual entry, posting from sales/purchasing, recurring template, etc.)."msgstr "Bu giriş nereden geldi (manuel giriş, satış/satın almadan deftere nakil, yinelenen şablon, vb.)."@@ -14067,6 +14305,9 @@ msgstr "Ne kadar süredir giriş yaptınız? Çıkış yapmayı unuttunuz mu?"msgid "Your books and how money flows."msgstr "Muhasebe defterleriniz ve paranın akışı."+msgid "Your changes go into a new draft version released with this change order."+msgstr "Değişiklikleriniz bu değişiklik emri ile yayınlanan yeni bir taslak sürüme girecektir."+msgid "Your Console PIN"msgstr "Konsol PIN'iniz"diff --git a/packages/locale/locales/tr/mes.po b/packages/locale/locales/tr/mes.poindex 0edf9bd8a1..36a9ba5265 100644--- a/packages/locale/locales/tr/mes.po+++ b/packages/locale/locales/tr/mes.po@@ -610,6 +610,9 @@ msgstr "Etki Yok"msgid "No maintenance scheduled for today"msgstr "Bugün planlanmış bakım yok"+msgid "No matches. Type to create one."+msgstr "Eşleşme yok. Bir tane oluşturmak için yazın."+msgid "No materials"msgstr "Malzeme yok"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 218a5b7254..06e5b4d880 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -38,6 +38,10 @@ msgstr "\"{taskName}\"已完成——其所有{0}个设置地图项目都已配msgid "(excluded for this customer)"msgstr "(已为此客户排除)"+#. placeholder {0}: open.length+msgid "{0, plural, one {This part is on 1 open change order} other {This part is on # open change orders}}"+msgstr "{0, plural, one {此部件在1个开放的变更单上} other {此部件在#个开放的变更单上}}"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0}个有余额的客户"@@ -211,6 +215,9 @@ msgstr "90天"msgid "A Carbon-run data migration — you load your own data"msgstr "Carbon 运行的数据迁移 — 您加载自己的数据"+msgid "A change order tracks a controlled engineering or manufacturing change through review and implementation."+msgstr "变更单跟踪受控的工程或制造变更,从审查到实施。"+msgid "A clearing account holding the value of goods received but not yet billed; the supplier invoice clears it."msgstr "持有已收但未开票商品价值的结算账户;供应商发票将其结清。"@@ -502,6 +509,9 @@ msgstr "收购成本"msgid "Acquisition Date"msgstr "收购日期"+msgid "Action"+msgstr "操作"+msgid "Action Status"msgstr "操作状态"@@ -592,6 +602,9 @@ msgstr "添加操作"msgid "Add Adjustment"msgstr "添加调整"+msgid "Add Affected Item"+msgstr "添加受影响项目"+msgid "Add any notes about your decision..."msgstr "添加关于您的决定的任何备注..."@@ -670,9 +683,6 @@ msgstr "添加问题"msgid "Add Receipt"msgstr "添加收据"-msgid "Add Required Actions"-msgstr "添加必需的操作"-msgid "Add Requirement"msgstr "添加要求"@@ -719,6 +729,9 @@ msgstr "附加费"msgid "Add-On Cost"msgstr "附加成本"+msgid "Added"+msgstr "已添加"+msgid "Added for this customer"msgstr "为此客户添加"@@ -737,9 +750,15 @@ msgstr "地址第2行"msgid "Adjustment Type"msgstr "调整类型"+msgid "Advance to {nextStatus}"+msgstr "推进到{nextStatus}"+msgid "Advanced"msgstr "高级"+msgid "Affected item not found."+msgstr "未找到受影响的项目。"+msgid "After"msgstr "之后"@@ -846,6 +865,9 @@ msgstr "资本化项目的会计记录,您要贬值而不是支出;草稿→msgid "An asset's acquisition cost minus accumulated depreciation — what it's still worth on the books, and the figure it's disposed at."msgstr "资产的收购成本减去累计折旧—仍在账簿上的价值和处置的金额。"+msgid "An engineering change: the affected items whose methods are revised on a draft and released together, superseding the versions they replace."+msgstr "工程变更:受影响项目的方法在草稿中进行修改,并一起发布,替代它们替换的版本。"+msgid "An integration or a custom change — the small slice that's actually custom."msgstr "一个集成或自定义更改——实际上是自定义的小部分。"@@ -1033,6 +1055,10 @@ msgstr "您确定要激活流程:{name}?它将再次出现在下拉菜单中msgid "Are you sure you want to activate this gauge?."msgstr "您确定要激活此量规吗?"+#. placeholder {0}: routeData?.changeOrder?.changeOrderId ?? ""+msgid "Are you sure you want to cancel {0}? It will be closed and read-only until you reopen it."+msgstr "您确定要取消 {0} 吗?在您重新打开之前,它将被关闭并处于只读状态。"+#. placeholder {0}: routeData?.rfqSummary ?.rfqId!msgid "Are you sure you want to cancel {0}? This will also cancel all related supplier quotes."msgstr "您确定要取消 {0} 吗?这也将取消所有相关的供应商报价。"@@ -1123,6 +1149,14 @@ msgstr "您确定要删除账户:{0}{1}吗?此操作无法撤销。"msgid "Are you sure you want to delete the API key: {0}? This cannot be undone."msgstr "您确定要删除 API 密钥:{0}?此操作无法撤销。"+#. placeholder {0}: requiredAction.name+msgid "Are you sure you want to delete the change order action: {0}? This cannot be undone."+msgstr "您确定要删除变更单操作:{0}?这无法撤销。"++#. placeholder {0}: changeOrderType.name+msgid "Are you sure you want to delete the change order category: {0}? This cannot be undone."+msgstr "您确定要删除变更单类别:{0}吗?此操作无法撤消。"+msgid "Are you sure you want to delete the contractor: {name}? This cannot be undone."msgstr "您确定要删除承包商:{name}?此操作无法撤销。"@@ -1281,6 +1315,9 @@ msgstr "您确定要删除webhook: {0}吗?此操作无法撤销。"msgid "Are you sure you want to delete this approval rule? This cannot be undone."msgstr "你确定要删除此审批规则吗?此操作无法撤销。"+msgid "Are you sure you want to delete this change order?"+msgstr "您确定要删除此变更单吗?"+msgid "Are you sure you want to delete this gauge?"msgstr "你确定要删除此量规吗?"@@ -1893,6 +1930,12 @@ msgstr "无法下载此文件"msgid "Cancel"msgstr "取消"+msgid "Cancel change order"+msgstr "取消变更单"++msgid "Cancel Change Order"+msgstr "取消变更单"+msgid "Cancel Job"msgstr "取消工作"@@ -2055,12 +2098,30 @@ msgstr "冠军"msgid "Change"msgstr "更改"+msgid "Change order"+msgstr "变更单"++msgid "Change Order"+msgstr "变更单"++msgid "Change Order Actions"+msgstr "变更单操作"++msgid "Change Order Types"+msgstr "变更单类型"++msgid "Change Orders"+msgstr "变更单"+msgid "Change status"msgstr "更改状态"msgid "Change the item type (e.g. Part, Material, Tool, etc.)"msgstr "更改项目类型(例如零件、材料、工具等)"+msgid "Change type"+msgstr "变更类型"+msgid "Change Type"msgstr "更改类型"@@ -2076,6 +2137,9 @@ msgstr "更改此项将覆盖现有方法"msgid "Changing this will update the part ID"msgstr "更改此项将更新零件ID"+msgid "Changing type resets this item's draft edits."+msgstr "更改类型将重置此项目的草稿编辑。"+msgid "Chart of accounts"msgstr "会计科目表"@@ -2411,6 +2475,9 @@ msgstr "确认"msgid "Confirm {0}"msgstr "确认 {0}"+msgid "Confirm & release"+msgstr "确认并发布"+msgid "Confirm and sign the scope"msgstr "确认并签署范围"@@ -2549,6 +2616,9 @@ msgstr "控制器,会计"msgid "Controls how planning handles a discontinued item: Consume First exhausts on-hand before switching to the successor, Prefer New redirects new demand to the successor immediately, Stock Only keeps only a minimum service reserve, and No Stock drops the item from planning entirely."msgstr "控制规划如何处理已停产的物料:优先消耗会在切换到替代物料前耗尽现有库存,优先新品会立即将新需求重定向到替代物料,仅库存会仅保留最少的服务库存,无库存会将物料从规划中完全删除。"+msgid "Controls whether the bill of material and bill of process of a released (Production) revision can be edited outside a change order."+msgstr "控制已发布(生产)版本的物料清单和工艺清单是否可以在变更单外部编辑。"+msgid "Convention"msgstr "惯例"@@ -2630,6 +2700,9 @@ msgstr "复制工作单号"msgid "Copy link"msgstr "复制链接"+msgid "Copy link to change order"+msgstr "复制变更单链接"+msgid "Copy link to consumable"msgstr "复制消耗品链接"@@ -2848,6 +2921,9 @@ msgstr "创建 {0} 个值"msgid "Create & Snapshot"msgstr "创建并快照"+msgid "Create a change order for the new revision and open it"+msgstr "为新修订版本创建变更单并打开它"+msgid "Create a new kanban card for scan-based replenishment."msgstr "为扫描式补货创建新的看板卡。"@@ -2875,6 +2951,9 @@ msgstr "创建并批准采购订单"msgid "Create audit trail entries"msgstr "创建审计跟踪条目"+msgid "Create Change Order"+msgstr "创建变更单"+msgid "Create Issue"msgstr "创建问题"@@ -2932,6 +3011,12 @@ msgstr "创建于"msgid "Created By"msgstr "由...创建"+msgid "Created change order action"+msgstr "已创建变更单操作"++msgid "Created change order type"+msgstr "已创建变更单类型"+msgid "Created consumable"msgstr "已创建易耗品"@@ -3550,6 +3635,12 @@ msgstr "删除{periodLabel}"msgid "Delete {storageUnitName}"msgstr "删除 {storageUnitName}"+msgid "Delete action"+msgstr "删除操作"++msgid "Delete Action"+msgstr "删除操作"+msgid "Delete API Key"msgstr "删除 API 密钥"@@ -3565,6 +3656,9 @@ msgstr "删除属性"msgid "Delete Category"msgstr "删除分类"+msgid "Delete Change Order"+msgstr "删除变更单"+msgid "Delete Consumable"msgstr "删除耗材"@@ -3794,6 +3888,9 @@ msgstr "删除转移"msgid "Delete Transfer Line"msgstr "删除转移行"+msgid "Delete Type"+msgstr "删除类型"+msgid "Delete Unit of Measure"msgstr "删除计量单位"@@ -3884,6 +3981,9 @@ msgstr "描述"msgid "Description (optional)"msgstr "描述(可选)"+msgid "Description of Change"+msgstr "变更说明"+msgid "Description of Issue"msgstr "问题描述"@@ -3929,6 +4029,9 @@ msgstr "已禁用"msgid "Discard"msgstr "丢弃"+msgid "Discontinuation date"+msgstr "停用日期"+msgid "Discontinuation Date"msgstr "停产日期"@@ -4196,6 +4299,9 @@ msgstr "编辑<0>问题</0>工作流"msgid "Edit Account"msgstr "编辑账户"+msgid "Edit Action"+msgstr "编辑操作"+msgid "Edit API Key"msgstr "编辑 API 密钥"@@ -4217,6 +4323,15 @@ msgstr "编辑属性类别"msgid "Edit Category"msgstr "编辑分类"+msgid "Edit Change Order"+msgstr "编辑变更单"++msgid "Edit Change Order Action"+msgstr "编辑变更单操作"++msgid "Edit Change Order Type"+msgstr "编辑变更单类型"+msgid "Edit column visibility"msgstr "编辑列可见性"@@ -4466,6 +4581,9 @@ msgstr "编辑转移"msgid "Edit Transfer Line"msgstr "编辑转移行"+msgid "Edit Type"+msgstr "编辑类型"+msgid "Edit Unit of Measure"msgstr "编辑计量单位"@@ -4583,6 +4701,9 @@ msgstr "上一季度末"msgid "End Time"msgstr "结束时间"+msgid "Enforce — edits are blocked"+msgstr "强制执行—编辑被阻止"+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "在收据、发货、转移和调整中强制执行按项目验证和指南。"@@ -6004,6 +6125,9 @@ msgstr "II(正常默认值)"msgid "III (tightened)"msgstr "III(紧化的)"+msgid "Impact"+msgstr "影响"+msgid "Imperial"msgstr "英制"@@ -6551,6 +6675,9 @@ msgstr "保持当前"msgid "Keep existing pricing, only add new items"msgstr "保留现有定价,仅添加新项目"+msgid "Keep Open"+msgstr "保持开放"+msgid "Key"msgstr "钥匙"@@ -6655,6 +6782,9 @@ msgstr "保留任何相关收据不变"msgid "Leave blank for built-in"msgstr "留空以使用内置"+msgid "Leave blank to use the next revision automatically"+msgstr "留空以自动使用下一版本"+msgid "Leave empty for exact match"msgstr "留空以精确匹配"@@ -6750,6 +6880,9 @@ msgstr "关联 Linear 问题"msgid "Linked entity quantity ({0}) does not match row quantity ({1})."msgstr "关联实体数量 ({0}) 与行数量 ({1}) 不匹配。"+msgid "Linked NCR"+msgstr "关联的不符合项报告"+msgid "Linked PO"msgstr "关联采购订单"@@ -7352,6 +7485,9 @@ msgstr "从工作中移除模型"msgid "Model removed from line"msgstr "模型已从行中移除"+msgid "Modified"+msgstr "已修改"+msgid "Module"msgstr "模块"@@ -7501,6 +7637,15 @@ msgstr "新属性"msgid "New Attribute Category"msgstr "新属性类别"+msgid "New Change Order"+msgstr "新建变更单"++msgid "New Change Order Action"+msgstr "新变更单操作"++msgid "New Change Order Type"+msgstr "新建变更单类型"+msgid "New Consumable"msgstr "新消耗品"@@ -7815,6 +7960,12 @@ msgstr "没有活跃报价"msgid "No addresses found"msgstr "未找到地址"+msgid "No affected items to assess."+msgstr "没有要评估的受影响项目。"++msgid "No affected items."+msgstr "没有受影响的项目。"+msgid "No applications. Payment will be on-account."msgstr "无应用。付款将按账户处理。"@@ -7840,6 +7991,9 @@ msgstr "未找到校准记录"msgid "No changes recorded"msgstr "未记录任何更改"+msgid "No changes yet."+msgstr "还没有变更。"+msgid "No comments yet. Be the first to add a comment."msgstr "还没有评论。成为第一个添加评论的人。"@@ -7867,12 +8021,18 @@ msgstr "未安排休息日"msgid "No default attachments yet."msgstr "还没有默认附件。"+msgid "No draft make method for this item yet."+msgstr "此项目还没有草稿制造方法。"+msgid "No draft versions available"msgstr "没有可用的草稿版本"msgid "No due date"msgstr "无截止日期"+msgid "No editable properties for this item."+msgstr "此项目没有可编辑的属性。"+msgid "No employees assigned yet. Add groups to see status."msgstr "还未分配员工。添加组以查看状态。"@@ -7897,6 +8057,9 @@ msgstr "未找到字段。"msgid "No files"msgstr "没有文件"+msgid "No files for this item."+msgstr "此项目没有文件。"+msgid "No files uploaded"msgstr "未上传任何文件"@@ -7933,6 +8096,9 @@ msgstr "没有匹配项"msgid "No matches for \"{query}\". Try a different search term."msgstr "没有匹配\"{query}\"的结果。请尝试不同的搜索词。"+msgid "No matches. Type to create one."+msgstr "无匹配项。输入内容以创建一个。"+msgid "No new notifications"msgstr "没有新通知"@@ -8098,6 +8264,9 @@ msgstr "不是表格而是总账余额:当发出工作物料时成本积累,msgid "Not enough jobs to cover quantity"msgstr "工作数量不足以覆盖数量"+msgid "Not referenced anywhere yet."+msgstr "还没有在任何地方被引用。"+msgid "Not Required"msgstr "不需要"@@ -8149,6 +8318,9 @@ msgstr "OEM (原始设备制造商)"msgid "of"msgstr "的"+msgid "Off — released revisions stay editable"+msgstr "关闭 — 已发布的版本保持可编辑"+msgid "OK"msgstr "确定"@@ -8236,6 +8408,9 @@ msgstr "哎呀!您尝试访问的链接无效。"msgid "Open"msgstr "打开"+msgid "Open a change order"+msgstr "打开变更单"+msgid "Open Actions"msgstr "开放操作"@@ -8251,6 +8426,9 @@ msgstr "未结应收"msgid "Open Audit Log"msgstr "打开审计日志"+msgid "Open change orders affecting this part"+msgstr "影响此零件的未结变更单"+msgid "Open Date"msgstr "开放日期"@@ -8504,6 +8682,9 @@ msgstr "用源方法覆盖报价方法"msgid "Overwrite the target manufacturing method with the quote method"msgstr "用报价方法覆盖目标制造方法"+msgid "Owner"+msgstr "所有者"+msgid "Owner (cost center)"msgstr "主成本中心"@@ -8568,6 +8749,12 @@ msgstr "零件ID"msgid "Part is configured for manufacturing"msgstr "零件已配置用于制造"+msgid "Part Number"+msgstr "零件编号"++msgid "Part Supersession"+msgstr "零件取代"+msgid "Partial"msgstr "部分"@@ -9531,6 +9718,9 @@ msgstr "原因"msgid "Reason Account"msgstr "原因账户"+msgid "Reason for Change"+msgstr "变更原因"+msgid "Reason for declining (Optional)"msgstr "拒绝原因(可选)"@@ -9733,12 +9923,27 @@ msgstr "相对时间线 · 日期待确认"msgid "Release"msgstr "释放"+msgid "Release change order"+msgstr "发布变更单"++msgid "Release control"+msgstr "发布控制"++msgid "Release Control"+msgstr "发布控制"+msgid "Release Job"msgstr "发布工作"msgid "Released"msgstr "已发布"+msgid "Released revision"+msgstr "已发布的版本"++msgid "Released revision is locked"+msgstr "已发布的版本已锁定"+msgid "Remaining"msgstr "剩余"@@ -9785,6 +9990,9 @@ msgstr "删除按列排序"msgid "Remove this storage type from all referencing storage units and delete it. This cannot be undone."msgstr "从所有引用此存储类型的存储单元中移除它并将其删除。此操作无法撤销。"+msgid "Removed"+msgstr "已移除"+msgid "Rendering label preview..."msgstr "正在渲染标签预览..."@@ -10006,6 +10214,9 @@ msgstr "反向收费销售税 (默认)"msgid "Reverse the related journal entries"msgstr "反转相关日记账分录"+msgid "Review each item's changes, then confirm — releasing can't be undone."+msgstr "审查每个项目的更改,然后确认 — 发布无法撤销。"+msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "审查期间的资产负债表和损益表,并确认数字正确。这是手动签核 — 审查后标记为完成。"@@ -10019,6 +10230,9 @@ msgstr "修订版"msgid "Revision {0}"msgstr "修订版本 {0}"+msgid "Revisions"+msgstr "版本"+msgid "Revoke"msgstr "撤销"@@ -11361,6 +11575,9 @@ msgstr "成功复制报价"msgid "Successfully created a new revision"msgstr "成功创建新版本"+msgid "Successor effectivity"+msgstr "后续生效性"+msgid "Successor Effectivity Date"msgstr "后继产品生效日期"@@ -12432,6 +12649,9 @@ msgstr "此信息将用于文档标题"msgid "This information will be visible to all users, so be careful what you share."msgstr "此信息将对所有用户可见,请谨慎分享。"+msgid "This is a purchased item — it has no BoM/BoP; only its attributes and documents can change."+msgstr "这是一个采购项目 — 它没有BoM/BoP;只有其属性和文档可以更改。"+msgid "This is a unique identifier for the webhook"msgstr "这是webhook的唯一标识符"@@ -12489,6 +12709,12 @@ msgstr "此期间未过账任何日记账分录,可以永久删除。此操作msgid "This Quarter"msgstr "本季度"+msgid "This revision is released (Production). Changes should normally flow through a change order."+msgstr "此版本已发布(生产)。更改应通常通过变更订单流转。"++msgid "This revision is released (Production). Open a change order to modify it."+msgstr "此版本已发布(生产)。打开变更订单进行修改。"+msgid "This sales order has associated jobs. Choose what to do with them."msgstr "此销售订单有关联的工作。选择如何处理它们。"@@ -12531,6 +12757,9 @@ msgstr "这将用此修订版本替换其他修订版本的所有方法材料。msgid "This will replace all method materials of other sizes with this size."msgstr "这将用此尺寸替换其他尺寸的所有方法材料。"+msgid "This will set the current version of the make method to Active, making it read-only."+msgstr "这将把制造方法的当前版本设置为活跃状态,使其变为只读。"+msgid "This will write off the remaining book value of the asset."msgstr "这将注销资产的剩余净账面价值。"@@ -13493,6 +13722,9 @@ msgstr "仓库, 运营"msgid "Warn"msgstr "警告"+msgid "Warn — edits succeed with a warning"+msgstr "警告 — 编辑成功,但显示警告"+msgid "Warn but allow"msgstr "警告但允许"@@ -13624,6 +13856,9 @@ msgstr "{translatedTerm}是什么?"msgid "What it is"msgstr "它是什么"+msgid "What kind of change this is: Version updates how the part is made, Revision edits its details and documents, and New Part replaces it with a new part number."+msgstr "这是什么样的更改:版本更新零件的制造方式,修订编辑其详细信息和文档,新零件用新零件号替换它。"+msgid "What kind of output this entry records — Production (good units), Scrap (unrecoverable), or Rework (sent back for correction); reveals Scrap Reason when Scrap."msgstr "此条目记录的输出类型 — 生产(合格单位)、报废(无法恢复)或返工(送回纠正);当报废时显示报废原因。"@@ -13783,6 +14018,9 @@ msgstr "此项目的新库存在收据时默认登陆到哪里;收据上每行msgid "Where stock lives and how it ships."msgstr "库存存放位置及其发货方式。"+msgid "Where the affected items are used across the system. Informational — nothing here blocks releasing."+msgstr "受影响的项目在整个系统中的使用位置。仅供参考 — 此处没有任何内容阻止发布。"+msgid "Where this entry originated (manual entry, posting from sales/purchasing, recurring template, etc.)."msgstr "此条目的来源(手动输入、来自销售/采购的过账、重复模板等)。"@@ -14067,6 +14305,9 @@ msgstr "您已打卡 {hoursElapsed} 小时。您忘记打卡下班了吗?"msgid "Your books and how money flows."msgstr "您的账簿和资金流向。"+msgid "Your changes go into a new draft version released with this change order."+msgstr "您的更改将进入随此变更单发布的新草稿版本。"+msgid "Your Console PIN"msgstr "您的控制台PIN"diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.poindex 456365a84c..29f1fdfc23 100644--- a/packages/locale/locales/zh/mes.po+++ b/packages/locale/locales/zh/mes.po@@ -610,6 +610,9 @@ msgstr "无影响"msgid "No maintenance scheduled for today"msgstr "今天没有计划的维护"+msgid "No matches. Type to create one."+msgstr "没有匹配项。输入以创建一个。"+msgid "No materials"msgstr "无物料"diff --git a/packages/notifications/src/index.ts b/packages/notifications/src/index.tsindex 58e058cbc3..861c34d4bb 100644--- a/packages/notifications/src/index.ts+++ b/packages/notifications/src/index.ts@@ -8,6 +8,15 @@ export enum NotificationEvent {ApprovalApproved = "approval-approved",ApprovalRejected = "approval-rejected",ApprovalRequested = "approval-requested",+ ChangeOrderApproved = "change-order-approved",+ ChangeOrderRejected = "change-order-rejected",+ ChangeOrderReleased = "change-order-released",+ ChangeOrderSubmittedForReview = "change-order-submitted-for-review",+ // Stage-broadcast events (V1 standalone Change Orders module) — fired to the+ // company team on entry to Start / Implementation / Done.+ ChangeOrderStarted = "change-order-started",+ ChangeOrderImplementation = "change-order-implementation",+ ChangeOrderDone = "change-order-done",DigitalQuoteResponse = "digital-quote-response",GaugeCalibrationExpired = "gauge-calibration-expired",JobAssignment = "job-assignment",@@ -131,6 +140,13 @@ export function getNotificationTopic(case NotificationEvent.ApprovalApproved:case NotificationEvent.ApprovalRejected:case NotificationEvent.ApprovalRequested:+ case NotificationEvent.ChangeOrderApproved:+ case NotificationEvent.ChangeOrderRejected:+ case NotificationEvent.ChangeOrderReleased:+ case NotificationEvent.ChangeOrderSubmittedForReview:+ case NotificationEvent.ChangeOrderStarted:+ case NotificationEvent.ChangeOrderImplementation:+ case NotificationEvent.ChangeOrderDone:return NotificationTopic.Approval;default:return NotificationTopic.General;@@ -201,6 +217,20 @@ export function getNotificationEmailHeading(event: NotificationEvent): string {return "Your request was approved";case NotificationEvent.ApprovalRejected:return "Your request was rejected";+ case NotificationEvent.ChangeOrderSubmittedForReview:+ return "Change order ready for review";+ case NotificationEvent.ChangeOrderApproved:+ return "Change order approved";+ case NotificationEvent.ChangeOrderRejected:+ return "Change order rejected";+ case NotificationEvent.ChangeOrderReleased:+ return "Change order released";+ case NotificationEvent.ChangeOrderStarted:+ return "Change order started";+ case NotificationEvent.ChangeOrderImplementation:+ return "Change order in implementation";+ case NotificationEvent.ChangeOrderDone:+ return "Change order complete";default:return "You have a new notification";}@@ -215,6 +245,15 @@ export function getNotificationEmailCtaLabel(event: NotificationEvent): string {case NotificationEvent.ApprovalApproved:case NotificationEvent.ApprovalRejected:return "View decision";+ case NotificationEvent.ChangeOrderSubmittedForReview:+ return "Review change order";+ case NotificationEvent.ChangeOrderApproved:+ case NotificationEvent.ChangeOrderRejected:+ case NotificationEvent.ChangeOrderReleased:+ case NotificationEvent.ChangeOrderStarted:+ case NotificationEvent.ChangeOrderImplementation:+ case NotificationEvent.ChangeOrderDone:+ return "View change order";case NotificationEvent.JobCompleted:return "View job";case NotificationEvent.SuggestionResponse:diff --git a/packages/react/src/CreateableMultiSelect.tsx b/packages/react/src/CreateableMultiSelect.tsxindex baead492f0..ccfb9f5d32 100644--- a/packages/react/src/CreateableMultiSelect.tsx+++ b/packages/react/src/CreateableMultiSelect.tsx@@ -189,11 +189,11 @@ const CreatableMultiSelect = forwardRef<align="end"onWheel={(e) => e.stopPropagation()}onTouchMove={(e) => e.stopPropagation()}- className="min-w-[var(--radix-popover-trigger-width)] max-w-[min(560px,calc(100vw-2rem))] p-1"+ className="min-w-[max(var(--radix-popover-trigger-width),11rem)] max-w-[min(560px,calc(100vw-2rem))] p-1"style={{width: dropdownContentWidthCh- ? `min(560px, max(var(--radix-popover-trigger-width), ${dropdownContentWidthCh}ch))`- : "var(--radix-popover-trigger-width)"+ ? `min(560px, max(var(--radix-popover-trigger-width), 11rem, ${dropdownContentWidthCh}ch))`+ : "max(var(--radix-popover-trigger-width), 11rem)"}}>{emptyMessage && options.length === 0 ? (@@ -309,7 +309,7 @@ function VirtualizedCommand({height: `${Math.min(filteredOptions.length, 6) * itemHeight + 4}px`}}>- <CommandEmpty>{t`No option found.`}</CommandEmpty>+ <CommandEmpty>{t`No matches. Type to create one.`}</CommandEmpty><CommandGroupstyle={{height: `${virtualizer.getTotalSize()}px`,diff --git a/packages/react/src/ErrorBoundary/ErrorScreen.tsx b/packages/react/src/ErrorBoundary/ErrorScreen.tsxindex dea0cda2b4..5c9adf9f3d 100644--- a/packages/react/src/ErrorBoundary/ErrorScreen.tsx+++ b/packages/react/src/ErrorBoundary/ErrorScreen.tsx@@ -12,41 +12,27 @@ export type ErrorAction = {export type ErrorScreenProps = {code: string;- statusLabel: string;eyebrow: string;title: string;message: string;logLines: string[];highlightIndex?: number;- marqueeItems: string[];actions: ErrorAction[];};export function ErrorScreen({code,- statusLabel,eyebrow,title,message,logLines,highlightIndex,- marqueeItems,actions}: ErrorScreenProps) {return (<main className="relative flex min-h-svh flex-col overflow-hidden bg-background text-foreground"><NoiseOverlay />- {/* Top meta bar */}- <header className="relative z-10 flex items-center justify-between border-b border-border px-5 py-4 font-mono text-[10px] uppercase tracking-[0.3em] text-muted-foreground sm:text-xs">- <span className="text-foreground">{"VOID//SYS"}</span>- <span className="hidden sm:inline">error_handler v9.4.0</span>- <span className="flex items-center gap-2">- <span className="inline-block size-1.5 animate-flicker bg-foreground motion-reduce:animate-none" />- {statusLabel}- </span>- </header>-{/* Body */}<div className="relative z-10 flex flex-1 flex-col justify-center px-5 py-12 sm:px-8"><p className="mb-4 font-mono text-[10px] uppercase tracking-[0.35em] text-muted-foreground sm:text-xs">@@ -86,32 +72,6 @@ export function ErrorScreen({))}</div></div>-- {/* Bottom marquee */}- <div className="relative z-10 overflow-hidden border-t border-border bg-foreground py-3 text-background">- <div className="flex w-max whitespace-nowrap">- <Marquee items={marqueeItems} />- <Marquee items={marqueeItems} />- </div>- </div></main>);}--function Marquee({ items }: { items: string[] }) {- return (- <div className="flex shrink-0 animate-marquee items-center motion-reduce:animate-none">- {items.map((item, i) => (- <span- key={`${item}-${i}`}- className="flex items-center px-6 font-mono text-xs font-medium uppercase tracking-[0.3em]"- >- {item}- <span aria-hidden="true" className="pl-6">- ✳- </span>- </span>- ))}- </div>- );-}diff --git a/packages/react/src/ErrorBoundary/RootErrorBoundary.tsx b/packages/react/src/ErrorBoundary/RootErrorBoundary.tsxindex 6863c3eec3..63d8078c76 100644--- a/packages/react/src/ErrorBoundary/RootErrorBoundary.tsx+++ b/packages/react/src/ErrorBoundary/RootErrorBoundary.tsx@@ -31,7 +31,6 @@ function resolveConfig(error: unknown, retry: () => void): ErrorScreenProps {if (error.status === 404) {return {code: "404",- statusLabel: "signal lost",eyebrow: "— coordinates unresolved",title: "This page slipped through the cracks.",message:@@ -46,14 +45,6 @@ function resolveConfig(error: unknown, retry: () => void): ErrorScreenProps {"> location: /dev/void","> recommendation: return to known coordinates"],- marqueeItems: [- "404 NOT FOUND",- "SIGNAL LOST",- "DEAD END",- "NULL ROUTE",- "OFF THE MAP",- "ERROR ERROR ERROR"- ],actions: [{ label: "return home", to: "/" }]};}@@ -66,7 +57,6 @@ function resolveConfig(error: unknown, retry: () => void): ErrorScreenProps {return {code: String(error.status),- statusLabel: "transmission rejected",eyebrow: "— request refused",title: "The server turned this request away.",message:@@ -81,14 +71,6 @@ function resolveConfig(error: unknown, retry: () => void): ErrorScreenProps {"> channel closed by remote host","> recommendation: verify access or retry"],- marqueeItems: [- `${error.status} ${error.statusText || "ERROR"}`,- "TRANSMISSION REJECTED",- "ACCESS DENIED",- "BAD REQUEST",- "REMOTE FAULT",- "ERROR ERROR ERROR"- ],actions: [{ label: "retry", onClick: retry },{ label: "return home", to: "/", variant: "ghost" }@@ -105,7 +87,6 @@ function resolveConfig(error: unknown, retry: () => void): ErrorScreenProps {return {code: "500",- statusLabel: "core fault",eyebrow: "— unhandled exception",title: "Something broke on our end.",message:@@ -120,14 +101,6 @@ function resolveConfig(error: unknown, retry: () => void): ErrorScreenProps {"> stack unwound to nearest boundary","> recommendation: retry or return home"],- marqueeItems: [- "500 INTERNAL ERROR",- "CORE FAULT",- "EXCEPTION THROWN",- "STACK UNWOUND",- "SYSTEM HICCUP",- "ERROR ERROR ERROR"- ],actions: [{ label: "retry", onClick: retry },{ label: "return home", to: "/", variant: "ghost" }diff --git a/packages/react/src/MultiSelect.tsx b/packages/react/src/MultiSelect.tsxindex f4c1ef7a64..bee10d1601 100644--- a/packages/react/src/MultiSelect.tsx+++ b/packages/react/src/MultiSelect.tsx@@ -323,19 +323,19 @@ function VirtualizedCommand({><div className="flex items-center justify-start gap-2">{isSelected ? (- <FaSquareCheck className="mr-1.5 text-primary" />+ <FaSquareCheck className="mr-1.5 text-primary shrink-0" />) : (- <FaRegSquare className="mr-1.5 text-muted-foreground" />+ <FaRegSquare className="mr-1.5 text-muted-foreground shrink-0" />)}{option.helper ? (- <div className="flex flex-col">+ <div className="flex flex-col min-w-0"><p className="line-clamp-1">{option.label}</p><p className="text-xs text-muted-foreground line-clamp-1">{option.helper}</p></div>) : (- <span className="line-clamp-1">{option.label}</span>+ <span className="line-clamp-1 min-w-0">{option.label}</span>)}</div></CommandItem>diff --git a/scripts/generate-mcp.ts b/scripts/generate-mcp.tsindex d468633229..9abe9892a3 100644--- a/scripts/generate-mcp.ts+++ b/scripts/generate-mcp.ts@@ -295,7 +295,13 @@ function parseInlineObjectType(typeStr: string): Record<string, unknown> {const fields = splitObjectFields(inner);for (const field of fields) {- const f = field.trim();+ // Strip `//` line comments so an inline comment above a field (common in+ // service arg type literals) never gets absorbed into the property key.+ const f = field+ .split("\n")+ .map((line) => line.replace(/\/\/.*$/, ""))+ .join("\n")+ .trim();if (!f) continue;const optional = f.includes("?:");