Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(assembly): review fixes - orphaned job steps re-adopt at their synced position, delete sub-assembly needs delete permission, license headers on new files

aashu8e409057609e
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index 8157f93131..9400716f51 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -13,7 +13,7 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced
- **Operation Batch** (`jobOperationBatch`) — N job operations sharing one run on a **batchable process** (`process.batchable`: laser table, furnace, plating; `process.batchType` `Sequential`/`Simultaneous` = the s-batch/p-batch physics — serial queue vs parallel load — driving the batch's planned duration `setup(max) + Σ|max(run)` via `@carbon/utils` `batchDuration`). Jobs are never merged and the BOM is never modified; each member stays a first-class `jobOperation`. Time/cost split **proportional to `operationQuantity`**, materialized at completion as per-member `productionEvent` slices, so job costing/GL post per job with no special-casing. Status **`Planned → Active → Completing → Completed`** (no `Cancelled` — dissolve deletes a pre-start batch instead). `Planned` is the pre-floor state: composed in the builder from ANY live job's unstarted ops (the planner RPC no longer requires released jobs), fully editable (add/remove/work-center widened to Planned+Active pre-event), invisible to MES. **`Active` displays as "Released"** (exactly like job `Ready`); the `release` edge-fn intent (`Planned → Active`, requires ≥1 member — NO work center: the scheduler pre-pass auto-selects earliest-finish among the process's work centers and persists it to batch + members) puts members on the floor, and releasing it RELEASES its Draft/Planned member jobs through the job page's own path — `releaseBatchMemberJobs` → `releaseJobs` (`production.server.ts`: recalc, MRP, status Ready, outside-operation POs via `create` `purchaseOrderFromJob`, releasedDate) after `getJobReleaseReadiness` validates EVERY such job (assemblies without operations, manufacturing blocked, or an outside operation whose supplier can't be resolved — `resolveOperationSupplier`: its own supplier process, else the process's only supplier — refuse the whole batch untouched; there is no per-operation supplier picker on batch release); a supplier's first new PO is reused for the later jobs so a batch lands on one PO per supplier. The `BatchReleaseModal` (drawer, table row action, builder Create & Release) shows the checks and the per-supplier PO choice; bulk `batches/release` passes no choice, so a batch needing a fix or with Draft POs to choose from is skipped and named. Then it notifies the scheduler; `unrelease` (`Active → Planned`) is allowed only before the first production event. **Membership-handoff floor rule**: an op in a batch is floor-visible iff its BATCH is Released (`Active`/`Completing`) — even when its job is Draft/Planned; an op in no batch follows its JOB's release (the pre-batching rule — a released job's un-batched batchable op always remains runnable, never blocked; removing it from a batch is the escape hatch). Enforced in `get_active_job_operations_by_location`, MES `getOpenJobs`, AND server-side in the MES operation loader + start route (list visibility alone was the leak). **Scheduling**: a Released batch is ONE scheduling unit — the batch pre-pass (`packages/planning/src/scheduling/batch-scheduler.ts`, run by `runLocationSchedule` before the per-job passes) writes a single coalesced `capacityReservation` tagged `jobOperationBatchId` (NOT NULL `operationId`/`jobId` anchored on the min member op), members pin to the window in the selector (generalized pinned-OSP path, no per-member reservation), downstream ops chain after the batch end, and the anchor comes from persisted predecessor forecasts (overruns flag a conflict and converge next wave); a batch whose open members all carry zero time standards still surfaces — a flagged 1h placeholder (`workHours` 0, never blocks) with a conflict naming the data gap, instead of silently vanishing from the reservation-driven forecast; Planned batches still schedule per-op. Completion is **two-phase and resumable** — Phase 1 (one txn) slices events + records quantities + flips `Active → Completing`; Phase 2 (idempotent, edge-fn-owned) issues each member's BOM, flips members `Done`, posts GL, then `Completing → Completed`. A Phase-2 failure leaves the batch `Completing` and re-invoking resumes (no double issue/GL). A retry MUST resubmit the quantities Phase 1 recorded — a changed quantity is rejected, not silently applied. Proportional split logic lives in `@carbon/utils` `batch-time-split` (Deno mirror under `supabase/functions/shared/`). Distinct from lot/batch tracking (`trackedEntity`/`batchNumber`). Mutations go through the `batch-operations` edge function (create/add/remove/update/dissolve/complete); payload record ids are re-read under `companyId` (`assertCompanyRecord` for location/work center) and the batch table's location/process/workCenter FKs are composite `(<col>, "companyId")` (`20260905132037_job-operation-batching.sql` (the consolidated branch migration)), so a cross-tenant id is refused by the fn AND rejected by the schema. Batch COMPOSITION happens ONLY in the batch builder (below) — the operations priority board's select-to-batch flow (checkboxes on cards, `BatchSelectionProvider`, the floating create bar, and the `BatchOpportunity` banner/column hints) was removed 2026-09-01 at Sid's direction, after the dedicated drag-and-drop batching board went the same way 2026-08-21. The board still SHOWS batches: each live batch collapses to one `BatchItemCard` in its work-center column (drag across columns reassigns the batch work center via `priorityBatchingUpdate`; Completing cards are read-only). The one composition surface — a guided **batch builder** — launches from the Batches list (`New Batch`) and an Active batch's drawer (`Add operations` → add-mode): a full-screen three-step drawer wizard (`ui/Batches/BatchBuilder.tsx`) that picks a location + batchable process (deep-linkable via `?location=&process=`; the last scope/view is remembered in localStorage), fetches candidates from `api/production/batchable-operations` (the revived `getBatchableOperations` RPC wrapper, enriched with each op's setup/labor/machine time, due date, and item thumbnail, plus per-work-center queue load and a hidden-ops count), and offers local search, a due-window quick filter (7/14/30d, due-date-sorted), a dynamic local-state "+ Filter" facet picker over the dimensions the candidates' BOMs actually contain (the material ITEM itself plus substance/grade/dimension/form/finish where populated — ANY BOM line matches ALL active facets; active facets render as removable/editable chips), two list views (polished table or group-by-material-signature sections with per-group select-all and setup-saving chips — a line's signature falls back to its BOM item's readable id when no normalized properties exist, so property-less BOMs still group by what they consume; an operation with NO op-linked BOM lines takes the JOB's unassigned (`jobOperationId IS NULL`) lines — BOMs are routinely authored without per-operation assignment, and without the fallback every such op read "No materials", emptied the facet picker, and degraded grouping to the produced item), a prominent scored suggestions banner at the top of the operations list — groups ranked by `rankSuggestions` (blended, normalised score: setup saved + due urgency + capacity fit + dimension specificity; each signature group is first split into due-date clusters no wider than `SUGGESTION_DUE_WINDOW_DAYS` = 7 via `splitByDueWindow`, so a suggestion never spans weeks — same material next month is next month's batch), each row a one-click apply with a reason chip (due now / fills a run); grouping uses `groupingKey` (material signature, falling back to the produced item for material-less assembly ops) while the mixed-materials warning uses the materials-only `materialSignature`, so the fallback never fakes a material clash. The pure logic (signatures, value sets, duration math, scoring) lives in `ui/Batches/batch-builder-logic.ts` — no JSX/lingui, unit-tested by `apps/erp/test/batch-suggestions.test.ts`, and a live preview (count · quantity · estimated run time, setup-saving + due-spread chips, plus a non-blocking "mixing materials" warning — material compatibility guides but never blocks, per the locked spec decision). Create-mode can attach a work center (picker shows each center's queue depth) and optional notes (additive `notes` field on the edge fn's create payload), and — instead of creating a duplicate — offers a searchable **"Add to batch"** footer popover (`AddToBatchButton`: a `Command` list over the compatible Active same-process batches from `deriveAddTargets`, each row `readableId · N ops`, on-select → the same `add` submit) rather than one button per batch, so it scales to hundreds of open batches. When the chosen work center has a `batchCapacity` set, a fill bar under the picker shows selected qty vs capacity ("fits in one run" / "over capacity — N loads") plus a `minimumBatchQuantity` met/short line — purely ADVISORY, Create never blocks (`resources.workCenter.batchCapacity`/`minimumBatchQuantity`). The scoped process's `batchRules` (`process.batchRules`, threaded through `getBatchableProcesses`) drives compatibility: the candidate signature/facets/mixed-material warning use every non-"ignore" dimension (default substance/grade/dimension, with the material item as a fallback for property-less BOMs), a "guide" mismatch versus the current selection shows a quiet amber tag on the row, and a "must" mismatch renders the row visible-but-LOCKED (grey lock tag, checkbox no-op, excluded from suggestions/select-all — clears when the selection empties). All resolution/enforcement is the shared `@carbon/utils` `batch-compatibility` module (`resolveBatchRules`/`mustViolations`); the client uses names and the edge fn uses ids through the same value-agnostic fold, so they always agree. The edge fn's `assertMaterialCompatible` re-checks the WHOLE membership (create: incoming set; add: existing members + incoming) after `assertEligible` and rejects a must-violating batch naming the dimension — the LOCK in the UI is advisory-fast; the edge fn is the real gate. It submits `create`/`add` to the same `batching.update` action + `batch-operations` edge fn — no new mutation path. Completion (MES modal → `complete`) can mark a member "not in this run" (`excluded`): it detaches back to the schedule un-run inside the Phase-1 txn instead of flipping Done; excluded members carry no quantities, all-excluded is rejected (dissolve instead), and a resume drops already-applied exclusions but rejects new ones. Batches LIST at `/x/production/batches` (nav: Production → Batches; `getJobOperationBatches` + `getJobOperationBatchMemberStats` + `getJobOperationBatchMembers`); rows are **expandable** (`renderExpandedRow`/`canExpandRow` on the shared `Table`, same mechanism as the ECO change-notices table) to reveal each member operation (job link, item thumbnail + readable id, completed/qty + scrap); clicking a batch opens a FULL-SIZE detail drawer (`ui/Batches/BatchDetailDrawer.tsx`): header meta (status/process/WC/location/created-by/notes), an enriched member table (thumbnails, completed/qty + scrap, status badges), and a Run card — per-type actual-vs-plan progress (per-type plan buckets = max member setup + Σ|max labor/machine by `process.batchType`; the "Planned time" total = shared setup + Σ|max of each member's run `max(labor, machine)`, matching the scheduler's reservation and MES batch mode via `@carbon/utils` `batchPlanBreakdown`) with a pulsing timer-running badge and the batch's production-event history (`getJobOperationBatchWithMembers` + `getJobOperationBatchEvents`; completed batches show the per-member slices, which keep the batch tag). The Batches list also bulk-RELEASES via selectable rows → a "Release N batches" bulk action posting the selected **Planned** ids to the `batches/release` route (one release per id, mirroring the single-batch `batching.update` release branch: `releaseBatchMemberJobs` → `releaseJobOperationBatch` → `notifyScheduleInputsChanged`; per-batch edge-fn refusals land in the toast summary's `failed` list, the rest still release; a non-Planned id from a stale selection is skipped). Deleting from ERP = the edge fn's `dissolve`: single via the `batches/delete/:batchId` ConfirmDelete route (destructive "Dissolve Batch" in the table's row context menu + a destructive Dissolve button on the detail drawer, Active only), and bulk via selectable rows → a "Dissolve N batches" bulk action posting the selected Active ids to the `batches/dissolve` route (one edge-fn dissolve per id; the server's per-batch refusal for started batches lands in the toast summary's `failed` list, the rest still dissolve), and a printable **batch list** serves at `/file/batch/:id.pdf` (`BatchListPDF` in `@carbon/documents`; menu entries on the batch card and MES batch chip). **Materials and output lots (2026-09-16):** the MES batch-mode materials panel shows each item's summed BATCH requirement alongside the member's own (`getBatchMaterialTotals`), and ONE pick covers the whole batch — `issue` case `trackedEntitiesToBatch` splits the picked lot(s) **pro-rata by each member's REMAINING requirement** (`splitPickAcrossMembers` in `@carbon/utils` `batch-pick-split`, largest-remainder so shares sum exactly) and records each member's own consumption against its own WIP entity, so cost and lot genealogy stay per job while the operator acts once; the pick modal's default quantity is the batch remaining, NOT the member's share (defaulting to one member's share splits it again across all of them and satisfies none). Completion finalizes each member's produced lot via the lean `issue` case `jobOperationBatchOutput` (the `Produce` activity + entity flip EXTRACTED from `jobOperationBatchComplete`, WITHOUT that case's `productionQuantity` insert and backflush — Phase 1 and the Phase-2 issue step already did both), under lot numbers PLANNED AT CREATION — the builder's Output section (`ui/Batches/BatchOutputLots.tsx`) either sets each member's lot (written to its WIP `trackedEntity.readableId` by the `batch-operations` create) or, when every member makes the same batch-tracked item, "Combine output into one lot" (`jobOperationBatch.mergeOutput` + `outputLotNumber`, migration `20260918094217_batch-output-lot-at-creation.sql`); the operator never edits lots at completion. A merged batch's member lots are combined right after completion (and the batch drawer's "Merge output lots" covers a Completed batch kept separate) into ONE lot via `issue` `mergeTrackedEntities` — genealogy keeps every source job, so the merged lot is strictly more traceable than a single directly-produced one. Both entry points derive the parent ids SERVER-SIDE from the batch's membership: these routes invoke `issue` with the service role, so the edge fn's `inventory` permission check validates the service role rather than the operator. Eligibility gained a `producedItem` dimension in `BATCH_RULE_DIMENSIONS` (default `ignore`) so a process can require members to make the same item. Serial-tracked members are unchanged — batch mode still disables tracked activity for them. Job surfaces show live-batch membership: a Batches column on the jobs table (loader-side lookup), a badge on the `JobBillOfProcess` operation row (`jobOperationBatch` embed), and a chip on the MES job DAG node.
- **Procedure** — versioned work instructions linked to operations via `processId`. Statuses: Draft/Active/Archived.
- **Assembly Instructions** — 3D animated work instructions, available to all users. (Previously gated to Carbon-internal emails via `requireAssembliesInternal` / `useFlags().isInternal`; that gate was removed to ship publicly.) **Versioned** (Draft/Published/Archived) as **row-per-version**, not an in-place counter: sibling versions are grouped by a self-referential `assemblyInstruction.rootInstructionId` (NULL = "I am the root"; group root = `rootInstructionId ?? id`, siblings = `id = root OR rootInstructionId = root`). `copyAssemblyInstructionAsVersion` spins a new editable **Draft** as a perfect copy (`version = max+1`, deep-copies steps with `parentStepId` remapped + each step's materials/slides/tools). `activateAssemblyInstructionVersion` makes a version active: publishes it, **archives the prior Published sibling**, and repoints `jobOperation.assemblyInstructionId` from other group versions to it — but only for active operations (status ≠ Done/Canceled) on active jobs (`!isJobLocked`). Only Draft is editable; the header exposes a "Versions" switcher + Make Active / New Version. `updateAssemblyInstructionStatus` no longer bumps `version`. The **list** (`getAssemblyInstructions`) reads the `assemblyInstructions` **view** (not the base table): it collapses each group to its latest version (`WHERE version = MAX(version)` per `rootInstructionId ?? id`) and rolls every sibling into a `versions` jsonb array, mirroring the `procedures` view — the table shows a `Version N` subtitle on the name plus a "Versions" hover card. Migration `20260730153412_assembly-instructions-view.sql`.
-- **Sub-assembly staging** — `assemblyInstructionStep.parentStepId` = the later JOIN step a step is built aside for (NULL = built in place); written only by `updateAssemblyStepJoin` (one level, base step never staged, join must come later), cleared by `updateAssemblyInstructionStepOrder` when a reorder makes it point backwards. The join step's own `componentNodeIds` never re-list the carried-in parts, so BOM materials are seeded once. Viewer side: `packages/viewer/src/staging.ts`.
+- **Sub-assemblies** — a header row (`assemblyInstructionStep.isSubAssembly`, no parts of its own) plus the steps whose `parentStepId` is that header, stored directly BEFORE it in `sortOrder` (play order); the header's `usedInStepId` is the later step that fits the finished unit (NULL = it joins the main build at the header). One level only. Every structural write (`makeAssemblySubAssembly`, `insertAssemblyInstructionStep`, `updateAssemblySubAssembly`, `ungroupAssemblySubAssembly`, `deleteAssemblySubAssembly`, `updateAssemblyInstructionStepOrder`) is a Kysely transaction that locks the instruction, applies the change in memory, checks `validateSubAssemblies` and writes the new order — never a partial update. Header rows are never copied into job steps. The step that uses a sub-assembly never re-lists its parts, so BOM materials are seeded once. Viewer side: `packages/viewer/src/subassembly.ts`.
- **Maintenance Dispatch** — reactive/scheduled repair for work centers with comments, events, items, and linked work centers.
- **Scheduling** — forecast-first finite scheduling run **IN-PROCESS in Node** via `runLocationSchedule` / `runExpediteWhatIf` from `@carbon/planning` (the ERP app and `@carbon/jobs` call it directly — no edge cold-start/HTTP hop; the `schedule` Deno edge function was DELETED, and the engine now lives in `packages/planning/src/scheduling/`). It regenerates a **whole LOCATION** in one deterministic FORWARD-ASAP pass (no backward JIT pass in placement, no `initial`/`reschedule` modes). Machine availability comes from a per-work-center ladder: `workCenter.alwaysOn` = 24×7 lights-out → explicit `workCenterShift` rows → the location's `shift` rows → a stock Mon–Fri 8h week; open maintenance dispatches flagged `takesWorkCenterOffline` subtract downtime from those windows. Work centers are finite (capacity 1 — one op at a time) AND, for ability-gated processes, qualified PEOPLE are finite: work only accumulates while a qualified employee is on shift (`employeeShift` ⋈ `shift`; no shift assignment = the job location's calendar) and not reserved elsewhere. Started ops net **remaining work** only — labor+machine scaled by `(1 − quantityComplete/operationQuantity)`, setup done once any `productionEvent` exists. Placements persist as `capacityReservation` rows (a materialized output: delete-by-job + bulk insert per run, `scenarioId IS NULL`; `WorkCenter` + `Employee` kinds — `OperatorPool` is read-tolerated legacy, never written); the run also writes `job.projectedCompletionAt` (forecast finish) and clears the job's schedule-outdated stamps. **Dual dates** (`20260818031629_dual-dates.sql`, spec `.ai/specs/2026-08-15-dual-dates-due-vs-projected.md`): every regen writes each op's forward projection — `startDate` (projected start day) + `jobOperation.projectedCompletionAt` (projected finish instant) — and DIFF-writes `jobOperation.dueDate` from a backward demand-anchored need-by pass (`computeNeedByDates`, `packages/planning/src/scheduling/need-by-calculator.ts` — a pure pre-placement step: reverse-topo from `job.dueDate`, `operationLeadTime` + assembly lead times, day lengths from the work centers' real calendars). Targets NEVER floor placement; `manuallyScheduled` = a human owns the need-by (the pin is taken as-is, propagates upstream, and is never overwritten — pinned ops still place normally; the old frozen-window branch is gone). An op projected past its need-by gets an informational amber behind-target state (BOP rows, ops-board `ItemCard`, MES operation detail) — never per-op `hasConflict`; when the job is late, the cause sentence appends "First behind target: {op} (due X, projected Y)". `jobOperation.priority` = the per-work-center placement order (reservation start ascending) — one source of truth for dispatch order (there is no configurable dispatch-sequencing policy). **People assignments** (manning board, `peopleAssignment`) make a staffed station a TEAM: the station still runs ONE op at a time, but the whole team present is booked on that op together — labor is parallelized across the present people (two people halve the labor wall-clock; setup and machine time are never compressed). Gated ops team-book people∩qualified on their assigned dates, falling back to an any-qualified single-person relay — but the board is a COMMITMENT, not a soft preference: the fallback may only draw on true FLOATERS (people with NO board assignment anywhere in the horizon, via `assignmentsByEmployee.has(id)`). A person you have manned anywhere is spoken for and is never pulled to a station they weren't assigned to — so moving your only welder off a station makes that station's op an unschedulable placeholder (visible on the Forecast) rather than silently double-booking the welder or shoving the op onto an unmanned weekend. A blank board leaves every qualified person a floater ⇒ classic any-qualified fallback, unchanged. Ungated ops at a staffed station are manned the same way with machine-only fallback. **Require-staffing policy** (`location.requiresStaffing`, per-location, default off, edited on the Production settings page (Settings → Production → Scheduling)): when ON, the scheduler places work ONLY where an operator is manned — the gated floater fallback and the ungated machine-only fallback are both removed, EXCEPT lights-out (`workCenter.alwaysOn`) stations keep running unattended. An op with no manned coverage (and not lights-out) becomes an unschedulable placeholder, so work routes to the staffed work centers and unstaffed ones get nothing. Threaded through `provider.getLocationRequiresStaffing` + `getAlwaysOnWorkCenterIds` → `FiniteSchedulingContext.requiresStaffing` + `capacity.workCenter.alwaysOn`. `peopleAbsence` subtracts the person's availability for that date everywhere; `peopleAssignment.overtimeHours` lengthens the person's day (window extension) and `peopleAssignment.hours` splits deal the day out per station sequentially — all as pure window edits before allocation. A blank board changes nothing. To reschedule, call `notifyScheduleInputsChanged` (stamps jobs; the debounced wave regenerates the whole location) — never direct date writes. An expedite what-if (`expediteJobId`) re-runs the sim with one job first, simulate-only, and returns its projected completion.
- **Ability requirements** — resolved through the operation's PROCESS: `process.requiresAbility` → the ability linked 1:1 to the process (`ability.processId`) → **presence-based** `employeeAbility` qualification (a row exists ∧ not expired; no `active`/`trainingCompleted` gate). Gates both the scheduler's operator pools and MES operation start. There are no operation-level ability tables.
diff --git a/apps/erp/app/modules/production/production.service.test.ts b/apps/erp/app/modules/production/production.service.test.ts
index b2eff4e812..2aa74add90 100644
--- a/apps/erp/app/modules/production/production.service.test.ts
+++ b/apps/erp/app/modules/production/production.service.test.ts
@@ -210,6 +210,44 @@ describe("planOrphanStepAdoption", () => {
expect(adoption.get("orphan2")).toBe("src2");
});
+ it("adopts orphans that follow the operation's own steps", () => {
+ const adoption = planOrphanStepAdoption(
+ [
+ { id: "src1", title: "Fit cover", sortOrder: 1 },
+ { id: "src2", title: "Torque bolts", sortOrder: 2 }
+ ],
+ [
+ { id: "own1", name: "Clean bench", sortOrder: 1 },
+ { id: "own2", name: "Check kit", sortOrder: 2 },
+ { id: "orphan1", name: "Fit cover", sortOrder: 3 },
+ { id: "orphan2", name: "Torque bolts", sortOrder: 4 }
+ ],
+ new Set()
+ );
+ expect([...adoption]).toEqual([
+ ["orphan1", "src1"],
+ ["orphan2", "src2"]
+ ]);
+ });
+
+ it("adopts by position when sub-assembly rows leave gaps in the source order", () => {
+ const adoption = planOrphanStepAdoption(
+ [
+ { id: "src1", title: "Press bearing", sortOrder: 1 },
+ { id: "src2", title: "Fit hub", sortOrder: 3 }
+ ],
+ [
+ { id: "orphan1", name: "Press bearing", sortOrder: 1 },
+ { id: "orphan2", name: "Fit hub", sortOrder: 2 }
+ ],
+ new Set()
+ );
+ expect([...adoption]).toEqual([
+ ["orphan1", "src1"],
+ ["orphan2", "src2"]
+ ]);
+ });
+
it("adopts each orphan at most once", () => {
const adoption = planOrphanStepAdoption(
[
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 416e63d79c..3c21e8e1f4 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -9092,9 +9092,13 @@ function assemblyStepName(title: string | null, index: number) {
* inserts duplicates beside them.
*
* Deliberately conservative: an orphan is claimed only when it matches a source
- * step on BOTH sortOrder and name AND no already-marked step claims that source
+ * step on BOTH position and name AND no already-marked step claims that source
* step. Genuinely hand-authored steps match no source step and are untouched;
* ambiguous cases are left alone rather than guessed at.
+ *
+ * Position is where the sync wrote the step: after the operation's own steps
+ * (the unmarked steps that share no name with a source step), in source order.
+ * Steps synced before that numbering sit at the source step's own sortOrder.
*/
export function planOrphanStepAdoption(
sourceSteps: { id: string; title: string | null; sortOrder: number | null }[],
@@ -9104,14 +9108,25 @@ export function planOrphanStepAdoption(
const adoption = new Map<string, string>();
const takenOrphans = new Set<string>();
+ const sourceNames = new Set(
+ sourceSteps.map((source, index) => assemblyStepName(source.title, index))
+ );
+ const lastOwnSortOrder = Math.max(
+ 0,
+ ...orphanSteps
+ .filter((orphan) => orphan.name === null || !sourceNames.has(orphan.name))
+ .map((orphan) => orphan.sortOrder ?? 0)
+ );
+
sourceSteps.forEach((source, index) => {
if (claimedSourceIds.has(source.id)) return;
const sourceName = assemblyStepName(source.title, index);
const match = orphanSteps.find(
(orphan) =>
!takenOrphans.has(orphan.id) &&
- orphan.sortOrder === source.sortOrder &&
- orphan.name === sourceName
+ orphan.name === sourceName &&
+ (orphan.sortOrder === lastOwnSortOrder + 1 + index ||
+ orphan.sortOrder === source.sortOrder)
);
if (match) {
adoption.set(match.id, source.id);
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepList.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepList.tsx
index 873c246251..0d8d339043 100644
--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepList.tsx
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepList.tsx
@@ -1,3 +1,7 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
import {
Button,
cn,
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblySubAssemblyProperties.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblySubAssemblyProperties.tsx
index f447076baa..e633d24bf4 100644
--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblySubAssemblyProperties.tsx
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblySubAssemblyProperties.tsx
@@ -1,3 +1,7 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
import { Hidden, Input, Submit, ValidatedForm } from "@carbon/form";
import type { JSONContent } from "@carbon/react";
import {
diff --git a/apps/erp/app/routes/x+/assembly+/$id.sub-assemblies.$stepId.delete.tsx b/apps/erp/app/routes/x+/assembly+/$id.sub-assemblies.$stepId.delete.tsx
index b1327614f6..43519dde98 100644
--- a/apps/erp/app/routes/x+/assembly+/$id.sub-assemblies.$stepId.delete.tsx
+++ b/apps/erp/app/routes/x+/assembly+/$id.sub-assemblies.$stepId.delete.tsx
@@ -1,3 +1,7 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
import { assertIsPost, error, notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
@@ -12,7 +16,7 @@ const logger = getLogger("erp", "assembly-sub-assembly-delete");
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
const { companyId, userId } = await requirePermissions(request, {
- update: "production"
+ delete: "production"
});
const { id, stepId } = params;
diff --git a/apps/erp/app/routes/x+/assembly+/$id.sub-assemblies.$stepId.tsx b/apps/erp/app/routes/x+/assembly+/$id.sub-assemblies.$stepId.tsx
index dd109fd427..841a0b3c22 100644
--- a/apps/erp/app/routes/x+/assembly+/$id.sub-assemblies.$stepId.tsx
+++ b/apps/erp/app/routes/x+/assembly+/$id.sub-assemblies.$stepId.tsx
@@ -1,3 +1,7 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
import { assertIsPost, error, notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
diff --git a/apps/erp/app/routes/x+/assembly+/$id.sub-assemblies.$stepId.ungroup.tsx b/apps/erp/app/routes/x+/assembly+/$id.sub-assemblies.$stepId.ungroup.tsx
index d90164347a..6d14c884bd 100644
--- a/apps/erp/app/routes/x+/assembly+/$id.sub-assemblies.$stepId.ungroup.tsx
+++ b/apps/erp/app/routes/x+/assembly+/$id.sub-assemblies.$stepId.ungroup.tsx
@@ -1,3 +1,7 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
import { assertIsPost, error, notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
diff --git a/apps/erp/app/routes/x+/assembly+/$id.sub-assemblies.new.tsx b/apps/erp/app/routes/x+/assembly+/$id.sub-assemblies.new.tsx
index 493c7e4288..3ccbfa1b8e 100644
--- a/apps/erp/app/routes/x+/assembly+/$id.sub-assemblies.new.tsx
+++ b/apps/erp/app/routes/x+/assembly+/$id.sub-assemblies.new.tsx
@@ -1,3 +1,7 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
import { assertIsPost, error, notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
diff --git a/apps/erp/app/routes/x+/assembly+/$id.units.delete.$unitId.tsx b/apps/erp/app/routes/x+/assembly+/$id.units.delete.$unitId.tsx
index 88adf81153..0668bfdb5f 100644
--- a/apps/erp/app/routes/x+/assembly+/$id.units.delete.$unitId.tsx
+++ b/apps/erp/app/routes/x+/assembly+/$id.units.delete.$unitId.tsx
@@ -30,6 +30,6 @@ export async function action({ request, params }: ActionFunctionArgs) {
return data(
{ success: true },
- await flash(request, success("Successfully deleted unit"))
+ await flash(request, success("Successfully deleted component group"))
);
}
diff --git a/apps/mes/app/components/AssemblyView.tsx b/apps/mes/app/components/AssemblyView.tsx
index 47f46ccdec..5cb1973ca7 100644
--- a/apps/mes/app/components/AssemblyView.tsx
+++ b/apps/mes/app/components/AssemblyView.tsx
@@ -1249,7 +1249,7 @@ export function AssemblyView({
next.set("step", String(target));
return next;
},
- { preventScrollReset: true }
+ { replace: true, preventScrollReset: true }
);
}
@@ -1288,7 +1288,7 @@ export function AssemblyView({
next.delete(SUB_ASSEMBLY_PARAM);
return next;
},
- { preventScrollReset: true }
+ { replace: true, preventScrollReset: true }
);
}
diff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.json
index 89ac0665d8..3b227f80a1 100644
--- a/packages/checks/src/conformance/baseline.json
+++ b/packages/checks/src/conformance/baseline.json
@@ -360,6 +360,7 @@
"no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx::const solveElapsedLabel = `${Math.floor(solveElapsedSeconds / 60)}:${String(",
"no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyStepBom.tsx::)}, ${Math.round(color[2] * 255)}, ${color[3]})`",
"no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyStepBom.tsx::backgroundColor: `rgba(${Math.round(color[0] * 255)}, ${Math.round(",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyStepList.tsx::const wanted = current + Math.round(offsetX / INDENT);",
"no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/ModelConvertProgress.tsx::if (n >= 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`;",
"no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/ModelConvertProgress.tsx::if (n >= 1024) return `${Math.round(n / 1024)} KB`;",
"no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/ModelConvertProgress.tsx::return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;",
diff --git a/packages/database/src/datasets/validate-assembly.test.ts b/packages/database/src/datasets/validate-assembly.test.ts
index 31ff51b636..752af7692b 100644
--- a/packages/database/src/datasets/validate-assembly.test.ts
+++ b/packages/database/src/datasets/validate-assembly.test.ts
@@ -1,3 +1,7 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
import { describe, expect, it } from "vitest";
import { satellite } from "./data/satellite/index.ts";
import type { AssemblyStepSpec, Dataset } from "./types.ts";
diff --git a/packages/database/supabase/migrations/20260930133226_assembly-sub-assemblies.sql b/packages/database/supabase/migrations/20260930133226_assembly-sub-assemblies.sql
index ba9f41da84..d29d89c6d3 100644
--- a/packages/database/supabase/migrations/20260930133226_assembly-sub-assemblies.sql
+++ b/packages/database/supabase/migrations/20260930133226_assembly-sub-assemblies.sql
@@ -19,6 +19,8 @@ CREATE INDEX IF NOT EXISTS "assemblyInstructionStep_usedInStepId_idx"
-- A sub-assembly installs nothing itself: its parts come from its steps. Header
-- rows are never copied into job steps, so a part on one would never reach the floor.
+ALTER TABLE "assemblyInstructionStep"
+ DROP CONSTRAINT IF EXISTS "assemblyInstructionStep_subAssembly_no_parts";
ALTER TABLE "assemblyInstructionStep"
ADD CONSTRAINT "assemblyInstructionStep_subAssembly_no_parts"
CHECK (NOT "isSubAssembly" OR cardinality("componentNodeIds") = 0);
diff --git a/packages/viewer/src/subassembly.test.ts b/packages/viewer/src/subassembly.test.ts
index c078a345c9..89bbf986f1 100644
--- a/packages/viewer/src/subassembly.test.ts
+++ b/packages/viewer/src/subassembly.test.ts
@@ -1,3 +1,7 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
import { describe, expect, it } from "vitest";
import {
arrivalIndexByNode,
diff --git a/packages/viewer/src/subassembly.ts b/packages/viewer/src/subassembly.ts
index 5251e210cb..c42f90fc77 100644
--- a/packages/viewer/src/subassembly.ts
+++ b/packages/viewer/src/subassembly.ts
@@ -1,3 +1,7 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
/**
* Sub-assemblies: pure structure over an instruction's steps. No three.js.
*