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.

95.8 KB
Raw Blame

Production Module

Work orders (jobs), scheduling, routings (operations), bill of materials, procedures, production events/quantities, maintenance dispatches/schedules, demand forecasting, and MRP integration.

Key Domain Concepts

  • Job — production work order. Statuses: Draft → Planned → Ready → In Progress → Paused → Completed → Closed → Cancelled. isJobLocked(status) returns true for Completed/Closed/Cancelled. MUST check before allowing edits.
  • Job Make Method — a job's manufacturing method (BOM + routing). Root method has parentMaterialId = null; sub-assemblies nest via parentMaterialId. Created by getMethod (production.service.ts, ported from the get-method server function; its live and unit tests include production.sandbox.test.ts). Every getMethod body opens its transaction through withTransaction (@carbon/database/client), so it joins one it is handed: createMakeMethodVersion copies into a Draft it has not committed yet.
  • Job Operation — routing step within a make method. operationType (shared enum): Process, Assembly, Inspection (in-house on a work center), or Outside Processing (subcontracted to a supplier process). Statuses: Todo → Ready → In Progress → Done. Ordered by order column.
  • Job Material — BOM line within a make method. Each has a methodType (Pull from Inventory, Purchase to Order, Make to Order) that drives procurement.
  • Production Event — time tracking (Labor/Machine/Setup) against an operation.
  • Production Quantity — output recording (Production/Scrap/Rework) against an operation with optional scrapReason.
  • 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 posting 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 — releaseBatches → releaseBatchMemberJobs → releaseCheckedJobs (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, posting-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. Distinct from lot/batch tracking (trackedEntity/batchNumber). Outside Processing operations are never batchable — a batch is one run on one of our work centers, and joining one would stamp its work center onto subcontracted work: get_batchable_operations leaves them out of the candidates and assertEligible refuses them. Mutations go through the batch-operations posting (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, 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 posting'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 posting uses ids through the same value-agnostic fold, so they always agree. The posting'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 posting is the real gate. It submits create/add to the same batching.update action + batch-operations posting — 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, the same releaseBatches the single-batch batching.update release branch calls: releaseBatchMemberJobs → releaseJobOperationBatch → notifyScheduleInputsChanged, member reads in one query; per-batch posting 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 posting'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 posting 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 and call the issue posting. 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.
  • Outdated model — an instruction keeps the modelUploadId it was made from; when its part's item.modelUploadId is another model (a new upload, a re-push from Onshape), the page shows a notice over the viewer with a link to a new instruction for the part. Derived on read (getAssemblyInstruction embeds item(modelUploadId)), nothing stored. A new version is no answer: copyAssemblyInstructionAsVersion copies the old model and its steps, whose componentNodeIds name that model's nodes.
  • 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; the engine 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.

Strict backflush

companySettings.requireBackflushStorageUnit (Settings → Items → Strict Backflush, off by default; spec .ai/specs/2026-10-14-strict-backflush.md). When it is on, a stocked material is consumed only from its Pull From, never another bin. A missing bin refuses the work. A short bin refuses it only while companySettings.preventNegativeBackflush is on (the nested "Prevent negative stock" switch, on by default); with it off the bin is drawn below zero. getStrictBackflushSettings(db, companyId, locationId?) (@carbon/database/strict-backflush) reads both; given a location, strict is false there unless it is a pull-from location (below). The SQL reads the same columns and makes the same location test.

  • Which lines, which locations. needsPullFrom (@carbon/database/strict-backflush): not Make to Order, item type Material / Part / Consumable, item not Non-Inventory. The locations are getPullFromLocations / isPullFromLocation — each with an active work center AND an active storage unit (a location with no storage unit has no bin a line could name). Strict backflush does not apply anywhere else: activation, release, the backflush, the badges and the settings card all skip such a location.
  • Activation. getMethodPartsMissingPullFrom + activationRefusalMessage (@carbon/database/strict-backflush). convertDocument methodVersionToActive (shared.service.ts) refuses through assertMethodHasPullFrom (~/modules/shared/strict-backflush); createMethodVersion (items.server.ts, behind the New Version route), which makes a single Draft version Active, refuses the same way before it writes. The change-notice draft (createChangeNoticeDraftMethod) freezes a Draft base as Active without the check: that is a side effect of opening the notice, and release still refuses the jobs.
  • Release. getJobReleaseReadiness returns materialsWithoutStorageUnit per job (materialsWithoutStorageUnit in job-release-logic.ts, one entry per part; jobs at other locations are skipped), and every path that sets a job to Ready refuses on it — see "Every path to Ready" below. JobStartModal lists the parts and disables Release Job; while the pull-from locations load it assumes the job's location needs them, and a failed read shows an error and disables Release.
  • Job creation. With strict backflush on at the job's location, getMethod (production.service.ts) gives a line the BoM's Pull From, else the item's default storage unit (pickMethod), and never the fullest bin (withFullestBin in its item prefetch, the same gate in createItemDefaults, and getStorageUnitId(…, allowFullestBin) in itemDerivedJobMaterialFields, which the Consume First swaps use). A line with neither stays without a storage unit, so the job shows in the settings drawer and release refuses it. With the setting off, the fullest bin is still the last fallback.
  • Backflush. issueJobOperationMaterials and partToOperation (issueMaterial, inventory.service.ts; planned material, consuming issue) take picked and unclaimed lineside stock first, then what no pick covered from the line's Pull From only (assertBinCovers / binCoverProblem in ~/modules/shared/strict-backflush: 409, names the part, the bin, need and have). A pick points jobMaterial.storageUnitId at lineside (pointJobMaterialAtLineside), so the Pull From is resolved by resolvePullFromStorageUnits → pullFromStorageUnit: the source bin of the line's OLDEST pick line into its current bin, else the line's own bin. Before the first draw, lockStrictBins takes pg_advisory_xact_lock(hashtextextended('strict-backflush:<companyId>:<bin>:<item>', 0)) for every (Pull From, item) pair in key-hash order; SQL locks the same keys in the same order, so two completions cannot deadlock. Every shortfall is collected and refused once; a refused material still counts its need against the bin, so the refusal names the whole shortfall. A refusal is a toast, so every strict message goes through summarizeList: the first 5 part names or 3 shortfalls, then "and N more" (the full shortfall list is logged). SQL backflush_job_materials (20261015163040_strict-backflush.sql) does the same at job completion: a picked line is drawn from lineside first (up to its on-hand), the rest from the Pull From; quantities compare at round(…, 5).
  • Produced units with no consumption. Callers that record a production quantity before they call issue first invoke issue with type: "jobOperationDryRun" (its own type, not a flag on jobOperation, so an ERP that predates it refuses it instead of issuing for real). It runs dryRunJobOperationIssues (inventory.service.ts): issueJobOperationMaterials with dryRun stops right after the strict check, before any ledger, cost or journal row, and the whole transaction always rolls back (the material loop updates quantityIssued before that point). It takes no locks and is a no-op when the setting is off. Several operations are checked in one dry run, each counting the rows the earlier ones plan to draw, so batch completion holds members that share a bin to their combined demand. MES callers go through checkStrictBackflush (apps/mes/app/services/quality.server.ts, which posts the dry run to the ERP through erpPosting): complete.tsx, end.$operationId.tsx, inspection-lot.$id.complete-passed.tsx, and inspection-lot.$id.disposition.tsx, which checks completion plus scrap BEFORE it closes the lot (a closed lot cannot be dispositioned again). ERP completeOperation (production.server.ts; a refusal keeps its category through serverFnFailure) and batch completion (completeBatch, production.service.ts, one dry run for every member) dry-run too; batch phase 2 keeps a refusal's 409. The dry run narrows the race, it does not close it (its lock ends with its rollback), so a failure after the units are recorded says "Units completed, but …" — the operator must not record them again.
  • Existing Active methods and released jobs are never changed when the setting turns on. Settings → Items counts both gaps with getStrictBackflushGapCounts (settings.service.ts, two count(DISTINCT …) statements; a failed count shows an error line, never a clean card) and each count's Review button opens a route drawer (settings+/items.methods-missing-pull-from.tsx, items.jobs-missing-storage-unit.tsx) over getActiveMethodsMissingPullFrom / getOpenJobsMissingStorageUnit (settings.service.ts). Each count and its list share one query builder (methodLinesMissingPullFrom, jobLinesMissingStorageUnit, the SQL form of needsPullFrom), so they cannot disagree. The jobs list holds only lines a backflush would refuse: stocked, not batch or serial, quantity still to issue, at a pull-from location. The drawers page in memory with pageInMemory (~/utils/query) in a searchable, paged Table (ui/StrictBackflush/StrictBackflushTables.tsx); a failed read flashes an error and returns to the page. A long list never goes in the card itself. Locations render as Enumerable pills; a materials cell shows 3 part IDs and a "+N more" popover with all of them, which stops wheel and touch propagation so it scrolls inside the drawer (conventions-ui.md, "Popovers inside Drawers").
  • Badges. The BoM and job BoM editors mark a line red ("No storage unit"), collapsed and open, from usePullFromLocationIds (~/hooks/usePullFromLocationIds, the cached api+/items.pull-from-locations.ts) — the same locations activation and release use. A changed line item's tracking type is kept until the line is saved, so the badge follows the new item.

Job completion

complete_job_to_inventory (SQL, newest 20261028153518_serial-number-timing-completion.sql, before it 20261015161847_job-receipt-takes-issued-serial-units.sql, 20261014171619_receive-consumed-serial-units.sql, 20261014135003_lock-production-events-at-job-completion.sql (locks the unposted events it posts), 20261009010412_job-costing-always-post.sql and 20261006221601_complete-job-to-asset.sql, forked from the guarded definition in 20260925121735_rpc-function-guards.sql) is the single choke point: completeJob (the ERP complete route and the API/MCP tool) and the sync_finish_job_operation trigger interceptor both go through it.

  • p_quantity_complete is CUMULATIVE, not this completion's delta. The function receives p_quantity_complete - job.quantityReceivedToInventory and stores the cumulative value back, because get_inventory_quantities computes on-production supply as production + scrap − received − shipped. backflush_job_materials takes the same cumulative number and is idempotent, so a re-completion at the received quantity receives nothing and consumes nothing.
  • It refuses a quantity ≤ 0 or below what was already received (stocked items), and a fractional quantity on a serial job. Those raises reach the jobOperation UPDATE when they happen under the trigger — sync_finish_job_operation therefore clamps with GREATEST(computed, received) before calling.
  • The serial branch receives the delta one numbered unit at a time — shop-floor-finished (Available) first, then by readableId — skipping Consumed/Rejected/Scrapped and any unit with a Job Receipt ledger row for this job, so re-completion never double-receives. When the job's rows hold too few single units, an item with a serial sequence has the rest split off the seed (split_serial_units_for_completion) and the units picked again; the units taken are then numbered (number_serial_units_for_receipt). An item with no serial sequence is never split: its single units are received first, then the rest of the delta against its seed (one entity holding the units the shop floor has not touched). The seed gives the units the job has not received from it, plus the units no row holds up to the job quantity (it grows by those); a completion beyond that is refused.
  • Make to Asset branch. A job with fixedAssetClassId completes into one new fixedAsset per unit (status Active, or Under Construction when the class isConstructionInProgress; acquisitionCost = swept WIP ÷ units; one Posted fixedAssetTransfer per asset, type 'Capitalization', sourceType 'Job'); a job with fixedAssetId sweeps its WIP onto that Construction in Progress asset as one fixedAssetCipCost row + one transfer. The units never enter stock: no itemLedger, costLedger, pickMethod or itemCost write, and the WIP discharge posts Dr class assetAccountId / Cr WIP as an 'Asset Transfer' journal (both lines still documentId = jobId, so the per-job WIP balance nets to zero). Each serial unit goes Consumed with attributes["Fixed Asset"] and a 'Capitalize' trackedActivity; every company writes the asset cost (the journal is Provisional before the accounting cutover). Guards raise before anything moves: 'A job linked to a sales order line cannot complete to a fixed asset'; 'A job that completes to a fixed asset class needs a serialized item' (any quantity — every asset a class job makes is a fleet unit followed by its serial); 'Make to Asset needs a serialized item or a quantity of one' (a job attached to an asset under construction); a job attached to a non-CIP asset is also refused ('… is not in a Construction in Progress class'). The item rule is makeToAssetItemError (production.models.ts), applied by x+/job+/new.tsx on save (a field error on the item), by updateJobDetails (the details form), by setJobItem on a property-panel item change and by resumeJob when a paused job goes back to Ready, with the sales order line gate. Covered by packages/database/supabase/tests/job-completion-to-asset.test.sql. Full flow: .claude/rules/fixed-asset-lifecycle.md.
  • Serial number timing: when a produced unit draws its serial number.
    • Setting: companySettings.serialNumberTiming (Settings → Production → Serial Numbers). An item's serial sequence overrides it with itemSerialSequence.serialNumberTiming (NULL follows the company; Settings → Serial Numbers). Readers resolve the item's value first: getSerialNumberTiming / resolveSerialNumberTiming (@carbon/database/sequence). Values: serialNumberTimings (@carbon/database/serial-number-timing, client-safe).
    • jobCreation (default): assignJobSerialNumbers → the assign-serial-numbers posting splits and numbers every unit when the job is created. The posting takes at and numbers only when the item's timing is at.
    • jobRelease: the same posting runs with at: "jobRelease" when releaseCheckedJobs flips the job to Ready (assignJobSerialNumbersAtRelease), on every release path. A failure does not stop the release: the job is listed in the result's warnings (releaseJobs passes it on).
    • production: the job keeps its unnumbered seed. A unit draws its number at its first touch through assignSerialNumberIfMissing: the MES start (services/serial-number.server.ts; only a single unit of the operation's own make method, since the unit id comes from the request), the issue posting's serial completion and operation scrap, and the completion that receives it.
    • A Batch lot is numbered at job creation whatever the timing; batch output never numbers.
    • A unit spawned later (a serial completion's next unit, a scrap's replacement) is numbered by getSpawnSerialNumber, which leaves it unnumbered under production. When the unit touched is an unsplit seed, the next unit or the replacement carries the seed's other units and stays unnumbered, so a job with no serial sequence still has a seed to receive against. The operation scrap refuses a unit already received to stock.
    • Completion: complete_job_to_inventory (20261028153518_serial-number-timing-completion.sql) picks the units, splits what the rows lack off the seed and creates units no row holds yet, up to the job quantity less the units in rows (split_serial_units_for_completion), picks again, then numbers the unnumbered units it took (number_serial_units_for_receipt). Both helpers are SECURITY INVOKER. It does not read the timing: a job left unnumbered by a timing that changed back to jobCreation is numbered too. One query picks the units, so numbering and receipt take the same ones.
    • Every serial is formatted by the SQL get_next_serial_numbers, which getNextSerialNumbers calls.
    • Complete dialog: it unlocks the quantity whenever the item has a serial sequence and units are unnumbered or have no row (getSerialCompleteChoice, mode numberOnReceipt) and says the serials are drawn at receipt. For an item with no sequence it stays locked to what the shop floor finished.
  • Dialog logic lives in ui/Jobs/job-complete-logic.ts (pure, no JSX/lingui, unit-tested by apps/erp/test/job-complete-logic.test.ts); the SQL is covered by packages/database/supabase/tests/job-completion-received-quantity.test.sql, hand-run like its siblings (nothing in CI runs supabase/tests/).

Loaded operation and unattributed machine time

  • Loaded operation (community) — the open workCenterLoad row (unloadedAt null) IS the load; there is no pointer column on workCenter (migration 20261014024119 dropped loadedJobOperationId/loadedAt). The productionEvent interceptor sync_load_work_center_operation loads the operation of any event inserted with endTime null and a workCenterId (Setup, Labor, Machine, the MES QR start): it ends the open row at the event's startTime and opens a new one. An event inserted with an endTime never loads; a start earlier than the newest loadedAt/unloadedAt in the work center's history writes nothing, and a reload of the loaded operation writes nothing. sync_unload_work_center_operation (on jobOperation) ends the open row (unloadedAt = GREATEST(NOW(), loadedAt)) when the operation becomes Done or Canceled, is deleted, or moves to another work center; a Pause does not unload. An event loads only its own company's operation onto its own company's work center. A CHECK refuses unloadedAt < loadedAt, and a partial unique index allows one open row per work center. jobOperationId has no foreign key on purpose: a second jobOperation↔workCenter relationship makes PostgREST refuse embeds like jobOperation → workCenter(name) (PGRST201). The MES work center display shows it as "Loaded: …", read from workCentersWithBlockingStatus.loadedJobOperationId. It exists on every work center, with or without a device. Rows are deleted 7 days after the unload, unless a device on the work center has not planned past it. The OEE sync reads this history to give each piece of a run to the operation loaded when it ran.
  • Machine time from an OEE device — when a workCenterDevice (Settings → Integrations → Sense → Devices) maps a machine to the work center, the oee-sync job records its Running time as Machine productionEvent rows on the loaded operation: employeeId null, createdBy system. The sensor's open event follows the load: a Setup or Labor start on another operation moves the time to it. Those events post to the GL as soon as they end, through postEndedMachineEvents (@carbon/ee/oee.server, which invokes post-production-event): after the sync that ends them, after an Unattributed Time assignment, after an unmap/remap or the Sense uninstall, and at an operator's press or a Down maintenance dispatch (postEndedProductionEvents). Operation finish and job completion stay the catch-up for anything a failure left unposted. There is no posting sweep.
  • Unattributed machine time — unattributedMachineTime is a review queue of Running time that no operation can take: nothing is loaded; the work center is blocked by maintenance (a Down dispatch from its createdAt until Completed or Cancelled, a Planned one from its actual start while In Progress); the loaded operation is Done or Canceled or its job is locked (machineTimeRefusal); or the machine ran on after an operator's Machine press in the same run (a Pause). It has no status: assigning (assignUnattributedMachineTime, inserts a Machine event for the interval) or dismissing (dismissUnattributedMachineTime) deletes the row, and pg_cron deletes rows 30 days after their endTime. Production → "Unattributed Time" (shown in the nav only while an oee integration is active; x+/production+/machine-time.tsx, ui/MachineTime/*.ee.tsx). The drawer (machine-time.$id.tsx) is a one-at-a-time review: suggestion cards from getWorkCenterDayEvents over the days the row touches, ranked by suggestMachineTimeOperations (ui/MachineTime/machine-time-suggestions.ee.ts), a search card over getMachineTimeOperationCandidates (open operations at the work center's location, including ones with no work center), "Not job time", Skip, and j/k; each answer redirects to the next row (getUnattributedMachineTimeNeighbors, keyset from machineTimeQueueKeyset). A row link and the drawer's close keep the list's filters; a queue move replaces the history entry; a failed read shows in the drawer (loadErrors). Both writes are @carbon/ee/oee.server behind requireEntitlement("INTEGRATIONS"); both refuse a row with no endTime, and assign refuses a locked job or a Done/Canceled operation. The list has 5 filters (work center, location, start date, end date, state Running in blue / Stopped in green): parseMachineTimeListFilters (ui/MachineTime/machine-time-filters.ee.ts, pure, inclusive YYYY-MM-DD days) and applyMachineTimeListFilters (service), shared by the list and the review queue; both read the view unattributedMachineTimes, whose startDate/endDate are the row's days in its location's timezone, the timezone the list shows (a '' timezone counts as none). The list has no sort. The list renders MachineTimeUpgradeOverlay when gated.

Engine, sync and press rules: .claude/rules/oee-provider.md.

Safety

Always

  • MUST use recalculateJobRequirements after changing job materials or operations — it recalculates quantities and costs.
  • MUST use notifyScheduleInputsChanged to reschedule — it stamps affected jobs schedule-outdated and the debounced wave regenerates the whole location. Never write jobOperation.startDate/projectedCompletionAt/dueDate directly (the one sanctioned manual write is pinning a need-by via setJobOperationDueDate).
  • MUST check isJobLocked(status) before allowing edits — Completed/Closed/Cancelled jobs are locked.
  • MUST scope queries by companyId; jobs are also scoped by locationId.
  • MUST use calculateJobPriority for priority — it computes from deadline type and due date. Never set job.priority manually.

Ask First

  • Deleting jobs that have posted production events or inventory movements.
  • Changing job status backwards (e.g., Completed → In Progress).
  • Running MRP (runMRP) — it can create/modify planned orders system-wide.

Never

  • Directly modify jobOperation.startDate/projectedCompletionAt — engine-owned forward projections, rewritten every regen. jobOperation.dueDate is the engine-computed need-by target; the only manual write is a pin through setJobOperationDueDate (sets manuallyScheduled, after which the engine never overwrites it).
  • Delete job operations that have production events recorded against them.
  • Set job.priority manually — it's calculated by calculateJobPriority.

Validation Commands

pnpm exec turbo run typecheck --filter=erp --concurrency=1   # the package is "erp", not "@carbon/erp"
pnpm --filter erp test

Key Data Model

Table / View Purpose
job / jobs (view) Work order header: item, quantity, dates, status, priority. fixedAssetClassId / fixedAssetId (Make to Asset target; CHECK job_asset_target_check allows at most one; jobValidator refines the same and JobForm exposes it as Complete To: Inventory / Fixed Asset Class / Asset Under Construction)
jobMakeMethod Manufacturing method instance; tree via parentMaterialId
jobOperation Routing step: process, times, work center, status, dual dates (dueDate = backward need-by target; startDate + projectedCompletionAt = forward projection)
jobMaterial BOM line: item, quantity, methodType, unitCost
jobOperationStep / jobOperationParameter / jobOperationTool Work instruction details on operations
jobOperationDependency Operation sequencing dependencies
capacityReservation Materialized finite-capacity slot allocations (delete-by-job + bulk insert per regen, scenarioId IS NULL; WorkCenter / Employee kinds — OperatorPool is read-tolerated legacy, never written). isPlaceholder = true rows are non-binding markers for ops the scheduler could NOT place (no qualified operator / no feasible slot); they surface the op on the Forecast but are excluded from the live snapshot (getLiveReservations) so they never hold capacity against other jobs
peopleAssignment / peopleAbsence Manning board: person→work-center per date (optional shift; unique per person/day/shift) and person-out-for-date flags; consumed by the People page (x+/priority+/people.tsx — Board/Matrix/Capacity views via ?view=; the route delegates to ui/Schedule/People/ components: PeopleHeader, PeopleBoard + PeopleCard + PeopleColumn, PeopleWeekBoard, PeopleMatrix, PeopleCapacity, PeopleHoursModal, OvertimeDialog, TimeOffDialog, with the shift-hours/time ladders and shared types in peopleShared.ts; the Capacity view's demand/scheduled buckets come from buildPeopleCapacityBuckets in production.service.ts), the MES station default, and the scheduling engine
workCenterShift Which shifts a work center operates (availability-ladder rung 1); empty = all shifts at the location. Owned by the resources module; the scheduler reads it. workCenter.alwaysOn (24×7) is the lights-out override
jobOperationQueueTime (view) Ready → first productionEvent queue time (jobOperation.readyAt stamped by trigger)
productionEvent Time tracking: type (Labor/Machine/Setup), start/end, employee; nullable jobOperationBatchId tags batch-run timers
productionQuantity Output: type (Production/Scrap/Rework), quantity, scrapReason
jobOperationBatch Operation batch header (BAT sequence): process, work center, location, status (Planned = pre-floor, Active displayed "Released"). Members are jobOperation rows via nullable jobOperationBatchId. A Released batch's coalesced schedule slot is a capacityReservation row tagged jobOperationBatchId (spared by per-job regen deletes; visible in every snapshot regardless of the anchor job's status; deleted by a jobOperationBatch status trigger when the batch completes or is unreleased — the sparing rules make that trigger the only retirement path; dissolve self-heals via the FK's column-list SET NULL + the anchor job's next regen)
procedure / procedureStep / procedureParameter Versioned work instructions
assemblyInstruction / assemblyInstructionStep 3D model-based assembly instructions (Draft/Published/Archived); steps carry componentNodeIds + motion/camera JSON for the viewer, hiddenComponentNodeIds (parts hidden on THAT step only — tooling/fixtures/installed parts in the way; never the step's own componentNodeIds, stripped by a DB trigger on every write; applied by the shared player in the ERP editor and MES playback, authored only in the ERP), orientation JSONB (the build's orientation from that step on — a unit quaternion, NULL = same as the previous step of the same build; written through updateAssemblyStepMotion by the Playback panel's five turn buttons — Flip over (180°), Tip toward you, Tip away from you, Spin left, Spin right (90° each), measured from the current view — in ui/Assemblies/AssemblyOrientationRow.tsx; a turn that lands back on the inherited orientation saves NULL. A turn that leaves the step turned also pins the current view as its camera when the step has no manual view (isSavedView, @carbon/viewer: a {source:"plan"} hint does not count), so playback lands on what the author saw; the Camera row (AssemblyCameraRow) uses the same check, so a plan hint reads "Automatic" and offers no Clear; a turn back keeps the pinned view and Reset only clears orientation — the Camera row's Clear returns to automatic framing; see @carbon/viewer orientation.ts), a buildWave INTEGER (the step's longest-path level in the planner's precedence DAG — steps sharing a wave have no ordering constraint and can be built in parallel by different people/stations; NULL for cycle-affected or hand-authored steps; informational, sortOrder still governs playback), and warnings.needsSupport (a part in the step tips once placed — center of mass outside the support polygon of the parts below it — likely needs a fixture or a second hand; shown as a hand icon with a tooltip in the step list), and warnings.plannedMotion (the motion the step had before the author first drew a path in the editor — its presence marks the path as hand-drawn ("Custom path"), overrides flagged (isPlanFlagged / hasCustomMotion in @carbon/viewer — server code imports them from the three-free @carbon/viewer/steps — are the one check, used by toViewerStep, the step list, the Properties panel and the MES AssemblyView), and is what Reset restores; updateAssemblyStepMotion writes it on the first edit, a re-plan clears it by rewriting warnings) AND the typed-step fields mirrored from jobOperationStep (type procedureStepType, tiptap description with derived instructionText, required, UoM/min/max, listValues) for eventual copy into job operations. motion/camera are authored directly in the 3D viewer (drag the red waypoint path → relative linear/L motion, or waypoints once a waypoint is turned with the rotation rings; "Set view" captures the camera pose; a sub-assembly header's motion is the finished unit's own joining path, edited from the using step's Playback box — or the header's own panel when nothing uses it — and saved through the same motion route with the header id), autosaved via updateAssemblyStepMotion / the steps/motion/$stepId route — separate from the step form's upsertAssemblyInstructionStep (which rewrites title/typed fields). There is no numeric motion editor. Step camera is a discriminated union: a manual {position,target,fov} pose (applied verbatim), OR a planner hint {source:"plan",direction} — a mesh-precise view DIRECTION the Rust planner bakes per step (crates/planner/src/view.rs best_view_direction: sight lines against the real triangles of everything installed earlier, so it sees a hollow enclosure's open top where the viewer's AABB scoring can't). The viewer applies the hint with LIVE framing — target, standing distance, frustum fit at the real viewport aspect (fitFraming, @carbon/viewer). null = fully live AABB framing (fallback for hand-edited steps / old plans). Generated steps carry the plan hint (the TS-side camera bake was removed); re-motion refreshes it but never clobbers a manual pose. Playback visibility is presence-based (@carbon/viewer visualForComponent): a component exists on the canvas only once its step has run; components no step installs render like future-step ones (hidden during playback, future-components toggle while paused). Visibility has TWO independent axes — futureMode (not built yet) and installedMode (already built — solid default, so the historical rendering is unchanged; ghost/hidden let an operator see past an assembly that buries the active step's parts) — but the toolbar does NOT expose them as axes. It offers three NAMED views (ASSEMBLY_VIEWS / VIEW_MODES in visibility.ts): Build (installed solid — the historical default), Focus (installed ghosted, so you see past what is already fitted but keep its shape) and Full (everything solid). An "Isolate" view (installed hidden) was dropped: per-step hiddenComponentNodeIds cover removing the clutter an author chooses. The future side is hidden in all but Full: a step you are working is never helped by parts that are not on the bench yet. The same control renders in ERP and MES; nine combinations behind two icon triplets was the design that got rejected for being unreadable on a shop floor. The camera's AABB view-direction scoring honours both via occluderWeight — geometry the operator cannot see is never treated as an obstacle, or hiding it would clear the pixels while the framing still dodged it. AABB fallback motions for "none"-motion steps consider only PRIOR-step components as obstacles and fade in when no collision-free path exists or when the component interpenetrates a present component (mated parts — sliders on rails, fasteners in bores — never get fabricated paths; the planner is the only authority for those)
assemblyInstructionStepMaterial BOM parts consumed at a step (stepId → itemId + optional quantity; stored by itemId so links survive make-method re-versioning; picker limited to the item's make-method BOM; UNIQUE (stepId, itemId)). Auto-populated from assemblyComponentMapping via syncAssemblyStepMaterialsFromMappings — additive only (manual quantities/deletions survive), triggered on step generation, component add, mapping create, and "Match BOM"
assemblyInstructionStepSlide Per-step reference slides (image XOR 3D model via modelUploadId, caption, size, annotations JSONB pins), mirroring methodOperationStepSlide; authored in the step editor's Details tab and copied to jobOperationStepSlide by the BOP sync / get-method. The former assemblyInstructionStepRequirement / assemblyStandardNote tables (fixtures/consumables/notes/media) were dropped — a step definition is parts + tools + slides
assemblyInstructionStepTool Tools used at a step (stepId → itemId of a tool-type item + quantity, UNIQUE (stepId, itemId)) — itemId is the same target jobOperationTool.toolId references, so the BOP sync maps rows 1:1
assemblyComponentMapping / assemblyUnit / assemblyPlanJob Geometry↔BOM item mapping, authored planner units (model-scoped "plan as one component" overrides), and geometry-service plan/convert job tracking. Planning is LAZY — conversion does not chain a plan run; the first "Generate Steps" click (or an explicit re-plan) starts it, pre-creating a Queued assemblyPlanJob row the worker adopts via planJobId. The clicking tab polls and auto-generates the steps when the plan lands
maintenanceDispatch / maintenanceSchedule Equipment maintenance tracking
demandForecast / demandProjection Demand planning data; demandProjection.consumedQuantity is MRP-written (forecast consumption), never user-edited
planningAction The MRP worklist: one row per suggestion (type Order / Make / Expedite / Defer / Cancel / Increase / Decrease / Release, status Open / Dismissed / Actioned, suggestedQuantity, suggestedDate, horizonDate, latestOrderDate, isASAP, requiresManualAction, target jobId / purchaseOrderLineId, supplierId, assignee + assigneeOverridden, the attribution policyName / reason / triggerValues, and the natural key itemId / locationId / periodId). Diff-written by generatePlanningActions after every run; read-only through the API (read production_view or purchasing_view)
scrapReason / maintenanceFailureMode Reference data for production and maintenance

Key Service Functions

  • convertSalesOrderLinesToJobs — creates jobs from sales order Make to Order lines; each job takes the order line's configuration (else the converted quote line's, via resolveJobConfiguration in ~/modules/sales/sales.utils) and is built with itemToJob instead of quoteLineToJob when the order line was reconfigured

  • getJob / getJobs / getJobMethodTree / getJobMethodTreeArray — job reads with method hierarchy

  • releaseJobs (production.server.ts, published as production_releaseJobs) — the one release operation: the job page's Release dialog (x+/job+/$jobId.release.tsx, through useJobRelease), the jobs table's bulk Release Jobs (x+/job+/release.tsx, path.to.bulkReleaseJob), the planning page's Release (useJobPlanningRelease) and the API/MCP all run it. Per selected job: a job that is not Draft/Planned is listed in skipped; the dialog's supplier picks (supplierProcessByOperationId) are saved on the operations first (stampSupplierChoices, validated: the operation belongs to the jobs, the supplier process to its process); then getJobReleaseReadiness once for the selection (every read through fetchAllByIds, pinned by test/job-release-readiness.test.ts) and jobReleaseProblems per job — nothing to make, manufacturing blocked, an assembly with no operations, an outside operation without a supplier, a Make to Asset job that cannot complete to its asset (makeToAssetReleaseError), and, when no purchaseOrdersBySupplierId was sent, a supplier with Draft POs to choose from. A job with a problem is named in failed; the rest go through releaseCheckedJobs one by one on a shared supplier→PO map (a supplier's first new PO is reused), then runLocationSchedule runs once per location AFTER every status flip. Returns { released, warnings, failed, skipped, scheduled, purchaseOrdersBySupplierId }; a job released whose POs failed is in released and warnings. Pinned by test/release-jobs.test.ts. More than 25 selected jobs, or "every matching job" (up to 2,000), go to the background table-bulk-action job instead (x+/job+/release.tsx): it calls releaseJobs per slice of 25 (a system context on behalf of the user, utils/table-jobs.server.ts) and passes the returned supplier→PO map to the next slice as carriedPurchaseOrders, so later jobs go on the PO an earlier slice made (startingPurchaseOrders, ui/Jobs/job-release-logic.ts).

  • releaseCheckedJobs (production.server.ts, unpublished) — the step every release shares, for jobs already checked: recalc, MRP (a failure is logged and never blocks), the guarded Ready flip (updateJobStatus(..., { fromStatuses: ["Draft", "Planned"] }) returns updated: false when someone cancelled or released the job during the recalc/MRP, so the release stops; pinned by test/job-status-guard.test.ts), outside-operation POs, releasedDate (a failed write is reported, since nothing else writes it). Returns releasedJobIds, the PO map and a failure.

  • releaseBatches (production.server.ts, published as production_releaseBatches) — releases Planned batches: member jobs through releaseBatchMemberJobs (all-or-nothing on jobReleaseProblems), then releaseJobOperationBatch, then notifyScheduleInputsChanged. One supplier→PO map runs through the batches of a call, so a supplier's outside operations from every batch go on the PO the first batch created; with no PO choice, a supplier with a Draft PO that is not this release's own refuses the batch. carriedPurchaseOrders passes the map in from an earlier call and the result returns it: the background Batches Release carries it from slice to slice, as Jobs Release does. Used by the batch drawer (batching.update release intent) and the batches table's bulk Release (production+/batches.release.tsx). updateJobStatus and releaseJobOperationBatch are NOT published: each alone skips what release does.

  • Every path to Ready. Each refuses a job that fails jobReleaseProblems, which includes strict backflush lines with no storage unit (materialsWithoutStorageUnit from getJobReleaseReadiness):

    Path Checks
    releaseJobs (Release dialog, bulk release, planning, API/MCP) jobReleaseProblems per job, then releaseCheckedJobs
    Batch release (releaseBatchMemberJobs) jobReleaseProblems, all-or-nothing, then releaseCheckedJobs
    Kanban scan with autoRelease (scanKanban, inventory.server.ts) jobReleaseProblems, then releaseCheckedJobs as the system on behalf of the scanner (source: "kanban"; outside operations go on the supplier's newest Draft PO, else a new one — no one is there to choose), then runLocationSchedule. A refused job stays Draft and linked to the kanban; the route redirects to the job with a flash naming the problems, and MES is not opened. A job whose Get Method failed is not released either, and the flash says so

    resumeJob (Paused → Ready) is not a release. updateJobStatus is not published, so the API cannot set Ready without the checks. No SQL function sets a job to Ready (the SQL writes of 'Ready' are on jobOperation). A new path to Ready must run jobReleaseProblems before releaseCheckedJobs.

  • getJobMaterialsWithQuantityOnHand — BOM with on-hand for shortfall visibility

  • getJobMaterialShortfallByItem — priority-adjusted shortfall calculation

  • getJobOrderStatusMap — procurement status indicators per material

  • recalculateJobRequirements / recalculateJobOperationDependencies — recalculation after changes (recalculateJobOperationDependencies resolves the job's location and runs the whole-location schedule regen in-process via runLocationSchedule from @carbon/planning)

  • notifyScheduleInputsChanged(companyId, kind, reason, entityId?) — thin emitter of carbon/schedule.inputs.changed; every caller sends it after its write, so a failed send is logged and returned as false, never thrown (kinds: ability/shift/employee-shift/work-center/location/reorder/people); stamps affected jobs and the debounced replan wave regenerates each stale location

  • getJobPromiseDate — promise date = job.projectedCompletionAt (forward-ASAP forecast finish), null before the first regen (no operation-date fallback — jobOperation.dueDate is the backward need-by target, so max(op.dueDate) would just echo the job due date); returns the §7 { promiseDate, basis: "schedule", confidence } contract (confidence "low" when the job has a conflicted op or a scheduleOutdatedReason, else "scheduled")

  • runMRP(client, db, params) — triggers Material Requirements Planning in-process via runMrp from @carbon/planning; the route action passes the Kysely handle (getDatabaseClient() from ~/services/database.server) — it is NEVER constructed in this service file (enforced by the no-db-client-in-service conformance check); the runMRP service function (published, update: inventory like the route) passes the service role and ctx.asSystem.pg, since MRP must read the whole company. recalculateJobOperationDependencies(client, db, params) and getJobExpediteForecast(client, db, …) take the handle the same way. Returns the { data, error } shape

  • calculateJobPriority — computes priority from deadline type and due date

  • getJobReceiptSnapshot(db, jobId, companyId) — a job's quantityReceivedToInventory plus the trackedEntity ids its Job Receipt ledger rows already posted, in ONE statement so the two can never come from different moments. Kysely because itemLedger is RLS-hidden from users without inventory/accounting view. Served by api/production/job/:jobId/receipts, read when the Complete dialog opens

  • getActiveJobOperationsByLocation — schedule board data (RPC get_active_job_operations_by_location, now also returns processBatchable/jobOperationBatchId/batchReadableId; never lists an Outside Processing operation, even one holding a stale work center)

  • getBatchableOperations / getBatchableProcesses — batch builder candidate data (RPC get_batchable_operations with per-op BOM material properties), served via api/production/batchable-operations. getBatchableProcesses also selects batchRules so the builder can resolve per-process compatibility rules

  • createJobOperationBatch / updateJobOperationBatch — operation batch mutations (call the batch-operations posting: create/add/remove/update/dissolve). These are building blocks (never tools): x+/priority+/batching.update.tsx makes one call per intent to the service functions createBatch (creates the batch Planned; on Create & Release then releases the member jobs and the batch and tells the scheduler, taking the batch apart again when the jobs' checks refuse), updateBatch (add / remove / work center / dissolve), releaseBatches, unreleaseBatch (then tells the scheduler), reprioritizeBatch (a batch card's dispatch order) and mergeBatchOutputs (production.server.ts). The schedule boards' drops are reorderScheduleOperations (operations board, one card or a column; tells the scheduler on a work-center change) and moveScheduleJob (dates board; the deadline type follows the date, deadlineTypeForDueDate)

  • getBatchOutputLots — a completed batch's MERGEABLE output lots: each member's WIP trackedEntity (by attributes->>Job Make Method), narrowed in-query to Available with stock. Drives the drawer's "Merge output lots"; a merged batch returns none (parents Consumed). The merge itself is inventory's mergeTrackedEntities wrapper over issue mergeTrackedEntities

  • getUnbatchedBatchableOperationCount — head count of open (Todo/Ready/Waiting) unbatched operations on a batchable process for live jobs, mirroring the get_batchable_operations candidate branch; drives the production dashboard's "Unbatched Operations" card (links to /x/production/batches/new)

  • getJobOperationBatches / getJobOperationBatchMemberStats / getJobOperationBatchMembers / getJobOperationBatchWithMembers — the /x/production/batches list (filterable, member count + summed quantity merged in the loader; getJobOperationBatchMembers is a single grouped .in() read of the page's member rows — job/item/quantity — powering the table's expandable member sub-rows, mirroring the ECO change-notices table's renderExpandedRow) and its detail drawer

  • getPeopleAssignments / getPeopleAbsences (single date) and getPeopleAssignmentsRange / getPeopleAbsencesRange (week) — people board/matrix reads; upsertPeopleAssignment (move semantics, optional partial-day hours) / movePeopleAssignment (station move with same-station merge, Kysely txn; returns previousWorkCenterId so movePerson reschedules BOTH the source and destination work centers — otherwise the station the person LEFT keeps a stale booking) / setPeopleAssignmentHours (per-station hours; null = whole shift — lowering releases the remainder to the board's free-hours pool) / setPeopleAssignmentOvertime / setPeopleOvertimeBulk (one date or a date→toDate range — the board's Week horizon applies a whole week; optional department/shift scope, single UPDATE) / deletePeopleAssignment / setPeopleAbsence / setPeopleAbsenceRange (vacation as one action — a row per date, duplicates skipped) / clearPeopleAbsence / copyPeopleBoard (day; copies splits, not overtime) / copyPeopleWeek (whole Monday-start week, same skip rules) / assignPeopleWeek / unassignPeopleWeek / movePeopleWeek (week-basis manning for the Board's Week range: one row per working day from the shift's weekday flags, Mon–Fri fallback; a day the person is off or already booked in the same effective shift — a shift-less row counts as their own shift — is left as it is, and assignPersonWeek answers assigned / skipped) / setPeopleDay (atomic reconciliation of a person's whole day — the PeopleHoursModal Working-hours editor's Save, also anchored on Matrix cells; it deletes the day's rows of the save's shift it is not sent, so every editor opens with editorDayRows (peopleShared.ts): every row of that day in the person's own shift, at any station, whatever the page's shift and department filters hide. The route therefore returns the day's rows for every shift (assignments) and the components filter by shift) — people mutations. They are building blocks (never tools): the board posts to x+/priority+/people.update.tsx, which makes one service-function call per intent (assignPerson, unassignPerson, movePerson, setPersonDay, setPersonHours, setPeopleOvertime, markPersonAbsent, markPersonAbsentRange, clearPersonAbsence, copyPeopleDay, assignPersonWeek, unassignPersonWeek, movePersonWeek, copyPeopleWeekBoard, in production.server.ts); each checks the board's ids belong to the company (requireBoardReferences) and tells the scheduler. usePeopleBoardFeedback (ui/Schedule/People/) toasts their answers

  • getPeopleCapacityOperations — open jobOperation hours for the Capacity view (excludes Done/Canceled ops and Draft/Planned/Completed/Cancelled/Closed jobs — released load only), with quantityComplete and started (any production event) so Due nets remaining work as the scheduler does

  • getWorkCenterOutages / workingHoursByDay / attendedHoursByDay / getOperationAttendedShares — the Capacity view's Available (working windows less open offline maintenance) and the Matrix Coverage's attended hours per station-day. On a shift tab Coverage counts only the hours inside that shift (within, from getShiftWorkingWindows), each on the day the shift starts, so a night shift's hours past midnight stay on the date it is rostered. A shift id that is not one of the location's shifts reads as All shifts

  • getCapacityReservationsForResources — live reservations across jobs (resource timeline + Capacity view's Scheduled series)

  • getCompletionJobs — the Outbound report (x+/scheduling+/outbound.tsx, Production → Scheduling → Outbound), RPC get_completion_jobs (migration 20260930150428, SECURITY INVOKER): open (Planned/Ready/In Progress/Paused) jobs at a location that fill a sales order, with the ship-to (salesOrder.customerLocationId, or the shipment's customer location on a drop shipment), ship-via, promised date and top-level operations. completionDate = the projected completion's day in the location's timezone, else the due date; the service orders by it (paged with fetchAllRecords) and the table groups on it via groupRowsBy

  • getProductionPlanning — MRP-driven production planning (RPC get_production_planning_grid, latest migration 20261006205037: wraps get_production_planning and adds the item group, the planning-horizon fence date, the first negative week, the latest order date and orderQuantity — the open Make actions inside the fence, which the default sort uses (the Order / Make button shows the quantity; there is no Qty to Order column), not the base RPC's quantityToOrder; asOf is the location's today, and actionTypes / actionAssignees filter on OPEN planning actions inside each item's fence, in the database)

  • nextJobPriority(siblings, deadlineType) — pure: a job's fractional priority among the jobs already on its date, by deadline type; calculateJobPriority reads the siblings and calls it, the planning date apply places a batch with it. deadlineTypeForPlanningDate(deadlineType) — the type a job carries once planning gives it a date (No Deadline → Soft Deadline)

  • Job status (production.server.ts, all published except planDraftJob) — the job header's buttons post to x+/job+/$jobId.status.tsx, which maps the status to one operation: Planned → planDraftJob (Draft only), Paused → pauseJob (from Ready / In Progress), Ready → resumeJob (from Paused; refuses blocked manufacturing and the Make to Asset rules, then recalculates and runs MRP), Draft / In Progress → reopenJob (Cancelled → Draft, Completed → In Progress), Closed → closeJob (from Completed, then service.closeJob writes the remaining WIP off as production variance), Cancelled → cancelJob. Each flip is guarded on its from-statuses (moveJobStatus). Complete is completeJob (x+/job+/$jobId.complete.tsx): complete_job_to_inventory, then the picked-material return (a failure there is a warning).

  • Job edits (production.server.ts, published) — updateJobDetails (the details form), configureJob, createJob (x+/job+/new.tsx: the records must be the company's, refused for an item an unreleased change notice holds and for a Make to Asset item that cannot complete to an asset; the route shows those two on the item field), createJobs (x+/job+/bulk.new.tsx), insertJob (the API's and workflows' create: Draft or Planned only), createSalesOrderLineJob (unpublished, x+/sales-order+/$orderId.$lineId.job.tsx; the line must be on the order) and convertSalesOrderLinesToJobs ($orderId.lines.jobs.tsx). Every job creation goes through jobCreationRefusal (the records are the company's, no unreleased change notice holds the item, the Make to Asset rule); orderPlannedJobs skips an item a change notice holds. deleteJobs deletes the jobs isJobDeletable allows (Draft, Planned, and the deprecated Due Today / Overdue), skips the rest, and is refused when it could delete none; the job page's and the jobs table's Delete menus use the same predicate. The property panel's / jobs table's field writes through x+/job+/update.tsx — setJobItem (re-pulls the method), setJobDeadline (re-ranks priority, one read and one write for all jobs; nextJobDeadline keeps date and type in step — ASAP / No Deadline clear the date, a date on a No Deadline or ASAP job makes it Soft; then tells the scheduler), setJobQuantity (recalculates), setJobSalesOrderLine, setJobFields — and updateJobDetails and configureJob refuse a locked job (readUnlockedJobs / requireJob).

  • Job method (production.server.ts, published) — Get Method is copyMethodToJob (upsertJobMethod, then the job's requirements and dependencies) and copyMethodToMaterial; createJobMaterial / updateJobMaterial / deleteJobMaterial / deleteJobMaterials and createJobOperation / updateJobOperation / deleteJobOperation / deleteJobOperations (the plural two are unpublished: Delete Selected, one recalculation) / reorderJobOperations / setJobOperationStatus (a Done operation returns its unconsumed picks) / setJobOperationDueDate / syncJobOperationProcedure back the bill of material and bill of process routes under x+/job+/methods+/; Get Method and the material, operation and procedure writes refuse a locked job (requireJob). Save Method (x+/job+/methods+/save.tsx) is upsertMakeMethodFromJob / upsertMakeMethodFromJobMethod: parts update and the target method's revision lock, as the items' Save Method. completeOperation (published) reports a good quantity on an untracked operation: it records it, backflushes (issue), and at the target sets the operation Done, posts its ended events and returns its picks. createProductionEvent / updateProductionEvent save a production event and post an ended one to the GL (post-production-event; a skipped posting is returned as postingError). createProductionQuantity records a production quantity (refuses a locked job, keeps a scrap reason only on Scrap); updateProductionQuantity corrects one and needs accounting update, so it is not published. The procedure properties panel posts to setProcedureFields. The bare row writes (upsertJobMaterial, upsertJobOperation, upsertJobMethod, upsertProductionEvent, updateJob) are building blocks in production.service.ts and are never tools.

  • cancelJob (production.server.ts, published as production_cancelJob) — the one cancel path, used by the job page's Cancel (x+/job+/$jobId.cancel.tsx), the status route and planning's Cancel action: refuses another company's job (notFound), sets Cancelled and clears the assignee only while the job is in fromStatuses (default CANCELLABLE_JOB_STATUSES; a refusal is a conflict and changes nothing), then returns its unconsumed picked material (post-picking returnJobRemainders, which sweeps only a Completed or Cancelled job) and cancels its open picking-list lines; a failure of either is a warning, the job stays Cancelled. Pinned by test/database/cancel-job.test.ts. Planning edits a job only while isJobEditableFromPlanning (production.models.ts: Draft / Planned)

  • getPlanningActions / getPlanningActionsByIds — the persisted MRP worklist (planningAction, written by generatePlanningActions in @carbon/planning after every MRP run; statuses Open / Dismissed / Actioned). dismissPlanningActions / reopenDismissedPlanningActions (Dismissed ↔ Open; both return the ids they changed, which the routes report), markPlanningActionsActioned (the conditional Open → Actioned claim that is the apply path's lock — an empty result means another apply got there first; it returns the row's suggested quantity and date, which Apply writes instead of the page's possibly stale read) and reopenPlanningActions (its rollback, Actioned → Open), assignPlanningActions (sets the assignee and marks it overridden so the next MRP run keeps it; Open and Dismissed rows only, returning the ids it changed). settleNewSupplyPlanningActions is the page's Order button's settle: the suggested orders it submits carry no action id, so after the PO lines (Order) or jobs (Make) are created it flips the Open / Dismissed action of each ordered (item, week) pair at the location to Actioned — otherwise the suggestion stayed on the page beside its order until the next MRP run. An Apply reads its actions (getPlanningActionsByIds) and their jobs / PO lines in one statement each (Kysely, the ids as parameters — never a PostgREST URL), then applies set-based: applyProductionPlanningDateActions(db, …) moves every Expedite / Defer in one transaction (the claim, the jobs, the jobs already on the target dates, one UPDATE of due date + deadline type + priority via the pure nextJobPriority — a "No Deadline" job becomes Soft Deadline, deadlineTypeForPlanningDate, since the job form hides the due date for No Deadline), and the route sends one schedule-inputs-changed event for the batch; Increase / Decrease / Cancel call postings with their own transactions, so they run per job, three jobs at a time, each claimed right before its change. The transaction-scoped claim and release live in planning-action-claims.ts (claimPlanningActions / releasePlanningActionClaims), shared with purchasing's applyPurchasingPlanningActions. Bad input to either planning route answers 400, a failed read or write 500. releasePlanningActionClaim gives a failed per-job apply's claim back (deleting it instead when MRP has already written an Open row for the same need), and updatePlanningJob is planning's single-job write (the drawer's inline edit, and Increase / Decrease), guarded on Draft / Planned in the UPDATE itself; a quantity change restates scrapQuantity from the item's scrap rate. planDraftJob (production.server.ts) is the drawer's Plan on a Draft job (planJob intent), in releaseJobs' order: the requirements recalculation (a failure leaves the job Draft), the guarded Draft → Planned flip, then MRP, so the job counts as supply. It sends no scheduler notice — the scheduler places only released jobs. replanAfterItemChange (production.server.ts) runs MRP after an item's planning or manufacturing settings are saved, so the planning pages follow them at once. planningAction is read-only through the API; its writers use the service role. Applied from x+/production+/planning.update.tsx (one service-function call per action: order (orderPlannedJobs), updateJob (updatePlannedJob), planJob (planJobFromPlanning), apply and its typed aliases (applyPlanningActions), dismiss (dismissProductionPlanningActions), reopen (reopenProductionPlanningActions), assign (assignProductionPlanningActions); a dismiss / reopen / assign that changes nothing is a conflict) and x+/purchasing+/planning.update.tsx; usePlanningActions reads both routes' answers; UI in ui/Planning/: ProductionPlanningTable + ProductionPlanningOrderDrawer, planningColumns.tsx (the column set shared with purchasing: the Stock Availability week strip via PlanningWeekStrip + planning-week-geometry.ts, LatestOrderDate, PlanningFence + planning-fence.ts), PlanningActionLines (the expanded row), PlanningOrderGrids + PlanningDrawerParts (the drawer's suggested / open-order grids, periodIdFor, the "N More After" button), usePlanningActions (the dismiss / reopen / assign / apply fetcher), and planning-action-scope.ts (resolvePlanningActionScope, actionsOfTypes, PLANNING_ACTIONS_COLUMN, PLANNING_ASSIGNEE_COLUMN, PLANNING_DRAWER_PARAM — pure, re-exported from production.models.ts so vitest can import it), planned-orders-from-actions.ts (pure: the drawer's suggested orders, the row's Order / Make quantity and a bulk order are the item's open Order / Make actions — openNewSupplyActions, plannedOrdersFromActions, productionOrdersFromActions, supplierConversionFactor — never sized again on screen, so a shortfall MRP folded into an Increase is not offered twice), planning-increase.ts (pure: chartedOrderQuantity charts an order at its open Increase), and planning-review.ts (pure: planningActionNeedsReview — Review vs Apply from the order's LIVE status, purchaseOrderStatus / jobStatus from getPlanningActions, not MRP's run-time requiresManualAction stamp, so a PO reopened since applies at once; a date move on a supplier-promised line stays Review — and purchaseOrderPlanningMenu, which order commands a row's ⋯ offers; PlanningActionHandlers.purchaseOrderMenuItems carries them, purchasing only). Both planning grids put the open order drawer's item in the address (?item=<itemId>, useLinkedDrawerItem in ~/hooks/useDrawerItem), so a link reopens it; the loader reads that row on its own (drawerItem) when it is not on the page. Tests: apps/erp/test/apply-production-planning-date-actions.test.ts (nextJobPriority, planJobDateMoves), planning-action-scope.test.ts, planning-fence.test.ts, planning-increase.test.ts, planning-review.test.ts, planned-orders-from-actions.test.ts, planning-week-geometry.test.ts

  • upsertMaintenanceDispatch / upsertMaintenanceSchedule — maintenance management

  • updateAssemblyStepHiddenComponents — autosave for a step's hidden list (route x+/assembly+/$id.steps.hidden.$stepId.tsx). The rule "a step never hides its own parts" lives in ONE place, the assembly_step_strip_own_hidden_components BEFORE trigger (migration 20260925063121), which strips + dedupes on every insert/update of either array — no service strips it by hand.

  • getAssemblyInstruction(s) / upsertAssemblyInstructionStep / getAssemblyInstructionStepMaterials — assembly instruction authoring; the step upsert derives instructionText from the tiptap description (viewer/MES consume the plain text)

  • getAssemblyInstructionVersions / copyAssemblyInstructionAsVersion / activateAssemblyInstructionVersion — versioning (see the Assembly Instructions concept above). Routes: x+/assembly+/$id.version.new.tsx (copy → new Draft) and x+/assembly+/$id.activate.tsx (make active). Change-notice diffs of a methodOperation now surface its assemblyInstructionId (resolved to the instruction name), inspectionDocumentId (drawing/file name), and operationType via stampOperationRefNames + ChangeNoticeDiffViewer (items module)

  • updateAssemblyStepMotion — partial motion/camera/orientation patch for one step, used by the 3D path/camera editor's autosave and the orientation turn buttons (never touches title/typed fields); camera: null clears the pose (return to auto-framing), orientation: null makes the step inherit its build's orientation again, and reset puts back warnings.plannedMotion (the motion before the first hand-drawn path). It takes the Kysely handle (the route passes getDatabaseClient()) and writes every patch as ONE UPDATE … WHERE id AND companyId whose jsonb expressions read motion/warnings from the row being written: a path edit records plannedMotion from the old motion only when the marker is absent, Reset restores it (else {"type":"none"}) and drops the marker (warnings → NULL when nothing else is left), flagged/blockedBy are kept. A drag save and a Reset that land together therefore serialize on the row lock instead of losing the marker — never split it back into a read and a write. Returns { data, error }. The editor route builds every post to it with stepPatchFormData (ui/Assemblies/assembly-step-patch.ts); useStepMotionEditor owns the path/camera edit session (one fetcher per row and column, so a Reset or Set view never aborts a drag save on another row) and useBuildOrientation owns the orientation fetcher and shows the pending orientation in the viewer before the save lands. The panel receives them as the grouped motionEditing / camera / orientation props. Deleting an instruction also drops the model's cached plan via deleteAssemblyInstruction → invalidateAssemblyPlanCache

  • generateAssemblyStepsFromPlan — plan.json → draft steps via buildAssemblyStepGroups (@carbon/viewer): sequence order, consecutive identical components merged, subassembly groups one step (titled by the unit name), mergedInto components riding their host's step; planner-flagged components (blockedBy / failed verification) store motion "none" + warnings: { flagged, blockedBy } (the viewer fades them in — no fabricated paths); a floater fold using the plan's contacts graph merges a placed-but-detached part with the immediately-following step that attaches to it (collision precedence forces the part in first, so it would otherwise render as a lone floating island for one step) — the pair installs as one rigid step along the detached part's motion; skipped on older plans lacking contacts; mode: "regenerate" replaces existing steps, refused while any step is planConfidence: "manual" or status Done. Persists a human title on every step via describeStep (@carbon/viewer) — real editable data, not just a render-time fallback. Seeds each step's materials from the component→BOM mappings (best-effort): auto-runs autoMatchAssemblyComponents once when the model has no mappings yet, and returns unmappedComponentCount (distinct geometry groups with no BOM item) which the generate route surfaces as a "use Match BOM" nudge

  • syncAssemblyStepMaterialsFromMappings — adds mapped BOM items (assemblyComponentMapping) to steps' materials from their componentNodeIds (quantity = instance count in the step); additive + best-effort, never updates or removes rows; scopable by stepIds / geometryHashes / onlyComponentNodeIds. Called from the step-components autosave route (newly added nodes only), the mapping-create route (that hash only), and the "Match BOM" route (full backfill)

  • getAssemblyUnits / upsertAssemblyUnit / deleteAssemblyUnit — model-scoped "plan as one component" overrides (assemblyUnit: componentNodeIds[] + optional itemId), authored from the BOM tree

  • Unit derivation: the geometry planner itself auto-detects "detail swarms" — a populated PCB's hundreds of tiny components seated on a board — from pure geometry (detect_swarm_units, crates/planner/src/pipeline2.rs: a substantial host part + many tiny parts in narrowphase contact with it, each dwarfed by the host; fastener-named parts never join so screws keep their own animations). No BOM or LLM involved. The only TS-side unit source is the user-authored assemblyUnit rows ("plan as one component" from the BOM tree), which loadPlanUnits (@carbon/jobs) sends as options.units; the planner merges units for planning and expands them back to member leaves with a named groups entry (→ one titled step). Detected groups are ALSO materialized as assemblyUnit rows at step generation (sourceGroupId = the plan group id, e.g. swarm:<hostNodeId>; UNIQUE (modelUploadId, sourceGroupId), upsert DO NOTHING so user renames/edits/deletions win within a plan — a regenerate re-materializes deleted ones) — the Components tab shows them like authored units with an "Auto" badge, and loadPlanUnits feeds them back to the planner as caller units so re-plans respect user edits. Flat multi-body STEP uploads (one PRODUCT, many solids, no assembly tree — the common Fusion/SolidWorks export shape) are split into per-solid components by the converter (crates/occt-bridge read_step), so they plan like proper assemblies instead of one un-plannable blob

  • Assembly operations (production.server.ts, published) — the instruction page's writes: createAssemblyInstruction (assemblies.new: picks a usable model, refuses while a conversion is needed and the geometry service is down, converts or starts planning), replanAssembly (plan.rerun, fresh = Regenerate), generateAssemblySteps (starts a missing plan and answers planning: true), cancelAssemblyJob, convertAssemblyModel, reconvertAssemblyModel (model.invalidate), matchAssemblyBom (component-mappings.auto), mapAssemblyComponent, reassignAssemblyComponents, setAssemblyStepComponents and syncAssemblyToOperation. The service helpers they wrap (generateAssemblyStepsFromPlan, createAssemblyPlanJob, invalidateAssemblyModelCache, autoMatchAssemblyComponents, upsertAssemblyComponentMapping, reassignAssemblyStepComponents, updateAssemblyStepComponents, syncAssemblyInstructionToOperation) are building blocks and are never tools.

  • getFlattenedBomMaterials — the item's engineering BOM flattened through Make subassemblies; feeds the assembly BOM tree and the per-step material picker

  • syncAssemblyInstructionToOperation — Assembly → job-operation re-sync (Kysely txn): copies an instruction's steps (any status) into a jobOperation as jobOperationStep rows (typed fields mirror 1:1), links per-step BOM parts via jobMaterialStep (itemId resolved against the operation's own jobMaterial), refreshes slides on synced steps (delete + recreate: the instruction's 3D model leads as a model slide at sortOrder 0, then the step's authored assemblyInstructionStepSlide rows), syncs tools (ensures a jobOperationTool per distinct tool item — never deleted, quantity only ratchets up — and rebuilds jobOperationToolStep links on synced steps), and sets jobOperation.assemblyInstructionId. Synced steps are numbered AFTER the operation's own (procedure / hand-authored) steps — both sets start at 1, so keeping the instruction's sortOrder interleaved them; insertAssemblyDataForJobOperation in get-method does the same. Re-runnable via the assemblyInstructionStepId provenance marker (update matched / insert new / delete stale; hand-authored NULL-marker steps untouched; ON DELETE SET NULL demotes to hand-authored). Route x+/assembly+/$id.sync-bop.tsx calls syncAssemblyToOperation (production_update, refuses a locked job); UI = "Sync Assembly Steps" on an Assembly operation in JobBillOfProcess (AssemblyStepsSyncModal), mirroring the "Sync Procedure" flow. Method/quote operations only store the assemblyInstructionId pointer — they never materialize steps; jobs inherit steps at get-method time (insertAssemblyDataForJobOperation, reading straight from the instruction) and re-sync on demand here. The MES assembly view uses the marker for step-aware 3D playback: getAssemblyPlaybackByOperationId (apps/mes operations.service) loads the linked instruction's GLB/graph/steps and AssemblyView mounts the @carbon/viewer AssemblyPlayer pinned to the operator's current step

  • createJobDocumentUploadUrl — MCP file upload (step 1): presigned URL for a job document (job/{jobId} folder); pair with documents_insertUploadedDocument. See .claude/rules/mcp-tools-reference.md → "File uploads"

Key Exports

import { getJob, insertJob, notifyScheduleInputsChanged, runMRP } from "~/modules/production/production.service";
import { jobValidator, isJobLocked, jobStatus } from "~/modules/production/production.models";

Related Modules

  • sales — jobs created from sales order lines; job.salesOrderLineId links back
  • items — job.itemId references item master; methods come from item make methods
  • inventory — materials issued from inventory; finished goods post on job completion
  • accounting — Make to Asset: a job whose Complete To is a fixed asset class or an asset under construction completes into fixedAsset rows instead of stock (.claude/rules/fixed-asset-lifecycle.md); the fleet register's Build for Fleet opens x+/job+/new.tsx?fixedAssetClassId=… with the Rental Fleet class pre-filled
  • purchasing — outside operations and purchased materials create PO lines via jobId
  • resources — operations run on work centers; scheduling assigns to work centers
  • quality — production quantities can trigger quality inspections; scrap reasons overlap

Rules References

  • .claude/rules/scheduling-data-structures.md — scheduling engine architecture, trigger chain, RPCs
  • .claude/rules/oee-provider.md — OEE providers, the attribution engine, the loaded operation and unattributed machine time
  • .claude/rules/mrp-system.md — MRP run flow, planning data model, and planning UI
  • .claude/rules/method-material-sourcing.md — how material methodType drives procurement