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.
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 viaparentMaterialId. Created bygetMethod(production.service.ts, ported from theget-methodserver function; its live and unit tests includeproduction.sandbox.test.ts). EverygetMethodbody opens its transaction throughwithTransaction(@carbon/database/client), so it joins one it is handed:createMakeMethodVersioncopies 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), orOutside Processing(subcontracted to a supplier process). Statuses: Todo → Ready → In Progress → Done. Ordered byordercolumn. - 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.batchTypeSequential/Simultaneous= the s-batch/p-batch physics — serial queue vs parallel load — driving the batch's planned durationsetup(max) + Σ|max(run)via@carbon/utilsbatchDuration). Jobs are never merged and the BOM is never modified; each member stays a first-classjobOperation. Time/cost split proportional tooperationQuantity, materialized at completion as per-memberproductionEventslices, so job costing/GL post per job with no special-casing. StatusPlanned → Active → Completing → Completed(noCancelled— dissolve deletes a pre-start batch instead).Plannedis 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.Activedisplays as "Released" (exactly like jobReady); thereleaseposting 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 viacreatepurchaseOrderFromJob, releasedDate) aftergetJobReleaseReadinessvalidates 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. TheBatchReleaseModal(drawer, table row action, builder Create & Release) shows the checks and the per-supplier PO choice; bulkbatches/releasepasses 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 inget_active_job_operations_by_location, MESgetOpenJobs, 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 byrunLocationSchedulebefore the per-job passes) writes a single coalescedcapacityReservationtaggedjobOperationBatchId(NOT NULLoperationId/jobIdanchored 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 (workHours0, 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 + flipsActive → Completing; Phase 2 (idempotent, posting-owned) issues each member's BOM, flips membersDone, posts GL, thenCompleting → Completed. A Phase-2 failure leaves the batchCompletingand 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/utilsbatch-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_operationsleaves them out of the candidates andassertEligiblerefuses them. Mutations go through thebatch-operationsposting (create/add/remove/update/dissolve/complete); payload record ids are re-read undercompanyId(assertCompanyRecordfor 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 theBatchOpportunitybanner/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 oneBatchItemCardin its work-center column (drag across columns reassigns the batch work center viapriorityBatchingUpdate; 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 fromapi/production/batchable-operations(the revivedgetBatchableOperationsRPC 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 byrankSuggestions(blended, normalised score: setup saved + due urgency + capacity fit + dimension specificity; each signature group is first split into due-date clusters no wider thanSUGGESTION_DUE_WINDOW_DAYS= 7 viasplitByDueWindow, 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 usesgroupingKey(material signature, falling back to the produced item for material-less assembly ops) while the mixed-materials warning uses the materials-onlymaterialSignature, so the fallback never fakes a material clash. The pure logic (signatures, value sets, duration math, scoring) lives inui/Batches/batch-builder-logic.ts— no JSX/lingui, unit-tested byapps/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 (additivenotesfield on the posting's create payload), and — instead of creating a duplicate — offers a searchable "Add to batch" footer popover (AddToBatchButton: aCommandlist over the compatible Active same-process batches fromderiveAddTargets, each rowreadableId · N ops, on-select → the sameaddsubmit) rather than one button per batch, so it scales to hundreds of open batches. When the chosen work center has abatchCapacityset, a fill bar under the picker shows selected qty vs capacity ("fits in one run" / "over capacity — N loads") plus aminimumBatchQuantitymet/short line — purely ADVISORY, Create never blocks (resources.workCenter.batchCapacity/minimumBatchQuantity). The scoped process'sbatchRules(process.batchRules, threaded throughgetBatchableProcesses) 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/utilsbatch-compatibilitymodule (resolveBatchRules/mustViolations); the client uses names and the posting uses ids through the same value-agnostic fold, so they always agree. The posting'sassertMaterialCompatiblere-checks the WHOLE membership (create: incoming set; add: existing members + incoming) afterassertEligibleand rejects a must-violating batch naming the dimension — the LOCK in the UI is advisory-fast; the posting is the real gate. It submitscreate/addto the samebatching.updateaction +batch-operationsposting — 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/canExpandRowon the sharedTable, 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 byprocess.batchType; the "Planned time" total = shared setup + Σ|max of each member's runmax(labor, machine), matching the scheduler's reservation and MES batch mode via@carbon/utilsbatchPlanBreakdown) 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 thebatches/releaseroute (one release per id, the samereleaseBatchesthe single-batchbatching.updaterelease branch calls:releaseBatchMemberJobs→releaseJobOperationBatch→notifyScheduleInputsChanged, member reads in one query; per-batch posting refusals land in the toast summary'sfailedlist, the rest still release; a non-Planned id from a stale selection is skipped). Deleting from ERP = the posting'sdissolve: single via thebatches/delete/:batchIdConfirmDelete 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 thebatches/dissolveroute (one posting dissolve per id; the server's per-batch refusal for started batches lands in the toast summary'sfailedlist, the rest still dissolve), and a printable batch list serves at/file/batch/:id.pdf(BatchListPDFin@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 —issuecasetrackedEntitiesToBatchsplits the picked lot(s) pro-rata by each member's REMAINING requirement (splitPickAcrossMembersin@carbon/utilsbatch-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 leanissuecasejobOperationBatchOutput(theProduceactivity + entity flip EXTRACTED fromjobOperationBatchComplete, WITHOUT that case'sproductionQuantityinsert 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 WIPtrackedEntity.readableIdby thebatch-operationscreate) or, when every member makes the same batch-tracked item, "Combine output into one lot" (jobOperationBatch.mergeOutput+outputLotNumber, migration20260918094217_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 viaissuemergeTrackedEntities— 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 theissueposting. Eligibility gained aproducedItemdimension inBATCH_RULE_DIMENSIONS(defaultignore) 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 theJobBillOfProcessoperation row (jobOperationBatchembed), 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-referentialassemblyInstruction.rootInstructionId(NULL = "I am the root"; group root =rootInstructionId ?? id, siblings =id = root OR rootInstructionId = root).copyAssemblyInstructionAsVersionspins a new editable Draft as a perfect copy (version = max+1, deep-copies steps withparentStepIdremapped + each step's materials/slides/tools).activateAssemblyInstructionVersionmakes a version active: publishes it, archives the prior Published sibling, and repointsjobOperation.assemblyInstructionIdfrom 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.updateAssemblyInstructionStatusno longer bumpsversion. The list (getAssemblyInstructions) reads theassemblyInstructionsview (not the base table): it collapses each group to its latest version (WHERE version = MAX(version)perrootInstructionId ?? id) and rolls every sibling into aversionsjsonb array, mirroring theproceduresview — the table shows aVersion Nsubtitle on the name plus a "Versions" hover card. Migration20260730153412_assembly-instructions-view.sql. - Outdated model — an instruction keeps the
modelUploadIdit was made from; when its part'sitem.modelUploadIdis 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 (getAssemblyInstructionembedsitem(modelUploadId)), nothing stored. A new version is no answer:copyAssemblyInstructionAsVersioncopies the old model and its steps, whosecomponentNodeIdsname that model's nodes. - Sub-assemblies — a header row (
assemblyInstructionStep.isSubAssembly, no parts of its own) plus the steps whoseparentStepIdis that header, stored directly BEFORE it insortOrder(play order); the header'susedInStepIdis 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, checksvalidateSubAssembliesand 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/runExpediteWhatIffrom@carbon/planning(the ERP app and@carbon/jobscall it directly; the engine lives inpackages/planning/src/scheduling/). It regenerates a whole LOCATION in one deterministic FORWARD-ASAP pass (no backward JIT pass in placement, noinitial/reschedulemodes). Machine availability comes from a per-work-center ladder:workCenter.alwaysOn= 24×7 lights-out → explicitworkCenterShiftrows → the location'sshiftrows → a stock Mon–Fri 8h week; open maintenance dispatches flaggedtakesWorkCenterOfflinesubtract 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 anyproductionEventexists. Placements persist ascapacityReservationrows (a materialized output: delete-by-job + bulk insert per run,scenarioId IS NULL;WorkCenter+Employeekinds —OperatorPoolis read-tolerated legacy, never written); the run also writesjob.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-writesjobOperation.dueDatefrom a backward demand-anchored need-by pass (computeNeedByDates,packages/planning/src/scheduling/need-by-calculator.ts— a pure pre-placement step: reverse-topo fromjob.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-boardItemCard, MES operation detail) — never per-ophasConflict; 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, viaassignmentsByEmployee.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 throughprovider.getLocationRequiresStaffing+getAlwaysOnWorkCenterIds→FiniteSchedulingContext.requiresStaffing+capacity.workCenter.alwaysOn.peopleAbsencesubtracts the person's availability for that date everywhere;peopleAssignment.overtimeHourslengthens the person's day (window extension) andpeopleAssignment.hourssplits deal the day out per station sequentially — all as pure window edits before allocation. A blank board changes nothing. To reschedule, callnotifyScheduleInputsChanged(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-basedemployeeAbilityqualification (a row exists ∧ not expired; noactive/trainingCompletedgate). 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 aregetPullFromLocations/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).convertDocumentmethodVersionToActive(shared.service.ts) refuses throughassertMethodHasPullFrom(~/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.
getJobReleaseReadinessreturnsmaterialsWithoutStorageUnitper job (materialsWithoutStorageUnitinjob-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.JobStartModallists 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 (withFullestBinin its item prefetch, the same gate increateItemDefaults, andgetStorageUnitId(…, allowFullestBin)initemDerivedJobMaterialFields, 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.
issueJobOperationMaterialsandpartToOperation(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/binCoverProblemin~/modules/shared/strict-backflush: 409, names the part, the bin, need and have). A pick pointsjobMaterial.storageUnitIdat lineside (pointJobMaterialAtLineside), so the Pull From is resolved byresolvePullFromStorageUnits→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,lockStrictBinstakespg_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 throughsummarizeList: the first 5 part names or 3 shortfalls, then "and N more" (the full shortfall list is logged). SQLbackflush_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 atround(…, 5). - Produced units with no consumption. Callers that record a production quantity before they call
issuefirst invokeissuewithtype: "jobOperationDryRun"(its own type, not a flag onjobOperation, so an ERP that predates it refuses it instead of issuing for real). It runsdryRunJobOperationIssues(inventory.service.ts):issueJobOperationMaterialswithdryRunstops right after the strict check, before any ledger, cost or journal row, and the whole transaction always rolls back (the material loop updatesquantityIssuedbefore 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 throughcheckStrictBackflush(apps/mes/app/services/quality.server.ts, which posts the dry run to the ERP througherpPosting):complete.tsx,end.$operationId.tsx,inspection-lot.$id.complete-passed.tsx, andinspection-lot.$id.disposition.tsx, which checks completion plus scrap BEFORE it closes the lot (a closed lot cannot be dispositioned again). ERPcompleteOperation(production.server.ts; a refusal keeps its category throughserverFnFailure) 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, twocount(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) overgetActiveMethodsMissingPullFrom/getOpenJobsMissingStorageUnit(settings.service.ts). Each count and its list share one query builder (methodLinesMissingPullFrom,jobLinesMissingStorageUnit, the SQL form ofneedsPullFrom), 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 withpageInMemory(~/utils/query) in a searchable, pagedTable(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 asEnumerablepills; 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 cachedapi+/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_completeis CUMULATIVE, not this completion's delta. The function receivesp_quantity_complete - job.quantityReceivedToInventoryand stores the cumulative value back, becauseget_inventory_quantitiescomputes on-production supply as production + scrap − received − shipped.backflush_job_materialstakes 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
jobOperationUPDATE when they happen under the trigger —sync_finish_job_operationtherefore clamps withGREATEST(computed, received)before calling. - The serial branch receives the delta one numbered unit at a time — shop-floor-finished (
Available) first, then byreadableId— skippingConsumed/Rejected/Scrappedand any unit with aJob Receiptledger 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
fixedAssetClassIdcompletes into one newfixedAssetper unit (statusActive, orUnder Constructionwhen the classisConstructionInProgress;acquisitionCost= swept WIP ÷ units; one PostedfixedAssetTransferper asset,type 'Capitalization',sourceType 'Job'); a job withfixedAssetIdsweeps its WIP onto that Construction in Progress asset as onefixedAssetCipCostrow + one transfer. The units never enter stock: noitemLedger,costLedger,pickMethodoritemCostwrite, and the WIP discharge posts Dr classassetAccountId/ Cr WIP as an'Asset Transfer'journal (both lines stilldocumentId = jobId, so the per-job WIP balance nets to zero). Each serial unit goesConsumedwithattributes["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 ismakeToAssetItemError(production.models.ts), applied byx+/job+/new.tsxon save (a field error on the item), byupdateJobDetails(the details form), bysetJobItemon a property-panel item change and byresumeJobwhen a paused job goes back toReady, with the sales order line gate. Covered bypackages/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 withitemSerialSequence.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→ theassign-serial-numbersposting splits and numbers every unit when the job is created. The posting takesatand numbers only when the item's timing isat.jobRelease: the same posting runs withat: "jobRelease"whenreleaseCheckedJobsflips the job to Ready (assignJobSerialNumbersAtRelease), on every release path. A failure does not stop the release: the job is listed in the result'swarnings(releaseJobspasses it on).production: the job keeps its unnumbered seed. A unit draws its number at its first touch throughassignSerialNumberIfMissing: 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), theissueposting'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 underproduction. 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 areSECURITY INVOKER. It does not read the timing: a job left unnumbered by a timing that changed back tojobCreationis 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, whichgetNextSerialNumberscalls. - Complete dialog: it unlocks the quantity whenever the item has a serial sequence and units are unnumbered or have no row (
getSerialCompleteChoice, modenumberOnReceipt) and says the serials are drawn at receipt. For an item with no sequence it stays locked to what the shop floor finished.
- Setting:
- Dialog logic lives in
ui/Jobs/job-complete-logic.ts(pure, no JSX/lingui, unit-tested byapps/erp/test/job-complete-logic.test.ts); the SQL is covered bypackages/database/supabase/tests/job-completion-received-quantity.test.sql, hand-run like its siblings (nothing in CI runssupabase/tests/).
Loaded operation and unattributed machine time
- Loaded operation (community) — the open
workCenterLoadrow (unloadedAtnull) IS the load; there is no pointer column onworkCenter(migration20261014024119droppedloadedJobOperationId/loadedAt). TheproductionEventinterceptorsync_load_work_center_operationloads the operation of any event inserted withendTimenull and aworkCenterId(Setup, Labor, Machine, the MES QR start): it ends the open row at the event'sstartTimeand opens a new one. An event inserted with anendTimenever loads; a start earlier than the newestloadedAt/unloadedAtin the work center's history writes nothing, and a reload of the loaded operation writes nothing.sync_unload_work_center_operation(onjobOperation) ends the open row (unloadedAt=GREATEST(NOW(), loadedAt)) when the operation becomesDoneorCanceled, 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 refusesunloadedAt < loadedAt, and a partial unique index allows one open row per work center.jobOperationIdhas no foreign key on purpose: a secondjobOperation↔workCenterrelationship makes PostgREST refuse embeds likejobOperation→workCenter(name)(PGRST201). The MES work center display shows it as "Loaded: …", read fromworkCentersWithBlockingStatus.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, theoee-syncjob records its Running time as MachineproductionEventrows on the loaded operation:employeeIdnull,createdBysystem. 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, throughpostEndedMachineEvents(@carbon/ee/oee.server, which invokespost-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 —
unattributedMachineTimeis a review queue of Running time that no operation can take: nothing is loaded; the work center is blocked by maintenance (aDowndispatch from itscreatedAtuntil Completed or Cancelled, aPlannedone from its actual start whileIn 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 theirendTime. Production → "Unattributed Time" (shown in the nav only while anoeeintegration 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 fromgetWorkCenterDayEventsover the days the row touches, ranked bysuggestMachineTimeOperations(ui/MachineTime/machine-time-suggestions.ee.ts), a search card overgetMachineTimeOperationCandidates(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 frommachineTimeQueueKeyset). 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.serverbehindrequireEntitlement("INTEGRATIONS"); both refuse a row with noendTime, 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, inclusiveYYYY-MM-DDdays) andapplyMachineTimeListFilters(service), shared by the list and the review queue; both read the viewunattributedMachineTimes, whosestartDate/endDateare 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 rendersMachineTimeUpgradeOverlaywhen gated.
Engine, sync and press rules: .claude/rules/oee-provider.md.
Safety
Always
- MUST use
recalculateJobRequirementsafter changing job materials or operations — it recalculates quantities and costs. - MUST use
notifyScheduleInputsChangedto reschedule — it stamps affected jobs schedule-outdated and the debounced wave regenerates the whole location. Never writejobOperation.startDate/projectedCompletionAt/dueDatedirectly (the one sanctioned manual write is pinning a need-by viasetJobOperationDueDate). - MUST check
isJobLocked(status)before allowing edits — Completed/Closed/Cancelled jobs are locked. - MUST scope queries by
companyId; jobs are also scoped bylocationId. - MUST use
calculateJobPriorityfor priority — it computes from deadline type and due date. Never setjob.prioritymanually.
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.dueDateis the engine-computed need-by target; the only manual write is a pin throughsetJobOperationDueDate(setsmanuallyScheduled, after which the engine never overwrites it). - Delete job operations that have production events recorded against them.
- Set
job.prioritymanually — it's calculated bycalculateJobPriority.
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'sconfiguration(else the converted quote line's, viaresolveJobConfigurationin~/modules/sales/sales.utils) and is built withitemToJobinstead ofquoteLineToJobwhen the order line was reconfiguredgetJob/getJobs/getJobMethodTree/getJobMethodTreeArray— job reads with method hierarchyreleaseJobs(production.server.ts, published asproduction_releaseJobs) — the one release operation: the job page's Release dialog (x+/job+/$jobId.release.tsx, throughuseJobRelease), 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 inskipped; 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); thengetJobReleaseReadinessonce for the selection (every read throughfetchAllByIds, pinned bytest/job-release-readiness.test.ts) andjobReleaseProblemsper 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 nopurchaseOrdersBySupplierIdwas sent, a supplier with Draft POs to choose from. A job with a problem is named infailed; the rest go throughreleaseCheckedJobsone by one on a shared supplier→PO map (a supplier's first new PO is reused), thenrunLocationScheduleruns once per location AFTER every status flip. Returns{ released, warnings, failed, skipped, scheduled, purchaseOrdersBySupplierId }; a job released whose POs failed is inreleasedandwarnings. Pinned bytest/release-jobs.test.ts. More than 25 selected jobs, or "every matching job" (up to 2,000), go to the backgroundtable-bulk-actionjob instead (x+/job+/release.tsx): it callsreleaseJobsper 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 ascarriedPurchaseOrders, 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"] })returnsupdated: falsewhen someone cancelled or released the job during the recalc/MRP, so the release stops; pinned bytest/job-status-guard.test.ts), outside-operation POs,releasedDate(a failed write is reported, since nothing else writes it). ReturnsreleasedJobIds, the PO map and afailure.releaseBatches(production.server.ts, published asproduction_releaseBatches) — releases Planned batches: member jobs throughreleaseBatchMemberJobs(all-or-nothing onjobReleaseProblems), thenreleaseJobOperationBatch, thennotifyScheduleInputsChanged. 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.carriedPurchaseOrderspasses 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.updaterelease intent) and the batches table's bulk Release (production+/batches.release.tsx).updateJobStatusandreleaseJobOperationBatchare 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 (materialsWithoutStorageUnitfromgetJobReleaseReadiness):Path Checks releaseJobs(Release dialog, bulk release, planning, API/MCP)jobReleaseProblemsper job, thenreleaseCheckedJobsBatch release ( releaseBatchMemberJobs)jobReleaseProblems, all-or-nothing, thenreleaseCheckedJobsKanban scan with autoRelease(scanKanban,inventory.server.ts)jobReleaseProblems, thenreleaseCheckedJobsas 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), thenrunLocationSchedule. 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 soresumeJob(Paused → Ready) is not a release.updateJobStatusis 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 onjobOperation). A new path to Ready must runjobReleaseProblemsbeforereleaseCheckedJobs.getJobMaterialsWithQuantityOnHand— BOM with on-hand for shortfall visibilitygetJobMaterialShortfallByItem— priority-adjusted shortfall calculationgetJobOrderStatusMap— procurement status indicators per materialrecalculateJobRequirements/recalculateJobOperationDependencies— recalculation after changes (recalculateJobOperationDependenciesresolves the job's location and runs the whole-location schedule regen in-process viarunLocationSchedulefrom@carbon/planning)notifyScheduleInputsChanged(companyId, kind, reason, entityId?)— thin emitter ofcarbon/schedule.inputs.changed; every caller sends it after its write, so a failed send is logged and returned asfalse, never thrown (kinds:ability/shift/employee-shift/work-center/location/reorder/people); stamps affected jobs and the debounced replan wave regenerates each stale locationgetJobPromiseDate— promise date =job.projectedCompletionAt(forward-ASAP forecast finish), null before the first regen (no operation-date fallback —jobOperation.dueDateis 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 ascheduleOutdatedReason, else "scheduled")runMRP(client, db, params)— triggers Material Requirements Planning in-process viarunMrpfrom@carbon/planning; the route action passes the Kysely handle (getDatabaseClient()from~/services/database.server) — it is NEVER constructed in this service file (enforced by theno-db-client-in-serviceconformance check); therunMRPservice function (published,update: inventorylike the route) passes the service role andctx.asSystem.pg, since MRP must read the whole company.recalculateJobOperationDependencies(client, db, params)andgetJobExpediteForecast(client, db, …)take the handle the same way. Returns the{ data, error }shapecalculateJobPriority— computes priority from deadline type and due dategetJobReceiptSnapshot(db, jobId, companyId)— a job'squantityReceivedToInventoryplus thetrackedEntityids itsJob Receiptledger rows already posted, in ONE statement so the two can never come from different moments. Kysely becauseitemLedgeris RLS-hidden from users without inventory/accounting view. Served byapi/production/job/:jobId/receipts, read when the Complete dialog opensgetActiveJobOperationsByLocation— schedule board data (RPCget_active_job_operations_by_location, now also returnsprocessBatchable/jobOperationBatchId/batchReadableId; never lists an Outside Processing operation, even one holding a stale work center)getBatchableOperations/getBatchableProcesses— batch builder candidate data (RPCget_batchable_operationswith per-op BOM material properties), served viaapi/production/batchable-operations.getBatchableProcessesalso selectsbatchRulesso the builder can resolve per-process compatibility rulescreateJobOperationBatch/updateJobOperationBatch— operation batch mutations (call thebatch-operationsposting: create/add/remove/update/dissolve). These are building blocks (never tools):x+/priority+/batching.update.tsxmakes one call per intent to the service functionscreateBatch(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) andmergeBatchOutputs(production.server.ts). The schedule boards' drops arereorderScheduleOperations(operations board, one card or a column; tells the scheduler on a work-center change) andmoveScheduleJob(dates board; the deadline type follows the date,deadlineTypeForDueDate)getBatchOutputLots— a completed batch's MERGEABLE output lots: each member's WIPtrackedEntity(byattributes->>Job Make Method), narrowed in-query toAvailablewith stock. Drives the drawer's "Merge output lots"; a merged batch returns none (parentsConsumed). The merge itself isinventory'smergeTrackedEntitieswrapper overissuemergeTrackedEntitiesgetUnbatchedBatchableOperationCount— head count of open (Todo/Ready/Waiting) unbatched operations on a batchable process for live jobs, mirroring theget_batchable_operationscandidate branch; drives the production dashboard's "Unbatched Operations" card (links to/x/production/batches/new)getJobOperationBatches/getJobOperationBatchMemberStats/getJobOperationBatchMembers/getJobOperationBatchWithMembers— the/x/production/batcheslist (filterable, member count + summed quantity merged in the loader;getJobOperationBatchMembersis 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'srenderExpandedRow) and its detail drawergetPeopleAssignments/getPeopleAbsences(single date) andgetPeopleAssignmentsRange/getPeopleAbsencesRange(week) — people board/matrix reads;upsertPeopleAssignment(move semantics, optional partial-dayhours) /movePeopleAssignment(station move with same-station merge, Kysely txn; returnspreviousWorkCenterIdsomovePersonreschedules 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 adate→toDaterange — 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, andassignPersonWeekanswersassigned/skipped) /setPeopleDay(atomic reconciliation of a person's whole day — thePeopleHoursModalWorking-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 witheditorDayRows(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 tox+/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, inproduction.server.ts); each checks the board's ids belong to the company (requireBoardReferences) and tells the scheduler.usePeopleBoardFeedback(ui/Schedule/People/) toasts their answersgetPeopleCapacityOperations— openjobOperationhours for the Capacity view (excludes Done/Canceled ops and Draft/Planned/Completed/Cancelled/Closed jobs — released load only), withquantityCompleteandstarted(any production event) so Due nets remaining work as the scheduler doesgetWorkCenterOutages/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, fromgetShiftWorkingWindows), 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 shiftsgetCapacityReservationsForResources— live reservations across jobs (resource timeline + Capacity view's Scheduled series)getCompletionJobs— the Outbound report (x+/scheduling+/outbound.tsx, Production → Scheduling → Outbound), RPCget_completion_jobs(migration20260930150428, 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 withfetchAllRecords) and the table groups on it viagroupRowsBygetProductionPlanning— MRP-driven production planning (RPCget_production_planning_grid, latest migration20261006205037: wrapsget_production_planningand adds the item group, the planning-horizon fence date, the first negative week, the latest order date andorderQuantity— 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'squantityToOrder;asOfis the location's today, andactionTypes/actionAssigneesfilter 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;calculateJobPriorityreads 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 exceptplanDraftJob) — the job header's buttons post tox+/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, thenservice.closeJobwrites the remaining WIP off as production variance), Cancelled →cancelJob. Each flip is guarded on its from-statuses (moveJobStatus). Complete iscompleteJob(x+/job+/$jobId.complete.tsx):complete_job_to_inventory, then the picked-material return (a failure there is awarning).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) andconvertSalesOrderLinesToJobs($orderId.lines.jobs.tsx). Every job creation goes throughjobCreationRefusal(the records are the company's, no unreleased change notice holds the item, the Make to Asset rule);orderPlannedJobsskips an item a change notice holds.deleteJobsdeletes the jobsisJobDeletableallows (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 throughx+/job+/update.tsx—setJobItem(re-pulls the method),setJobDeadline(re-ranks priority, one read and one write for all jobs;nextJobDeadlinekeeps 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— andupdateJobDetailsandconfigureJobrefuse a locked job (readUnlockedJobs/requireJob).Job method (
production.server.ts, published) — Get Method iscopyMethodToJob(upsertJobMethod, then the job's requirements and dependencies) andcopyMethodToMaterial;createJobMaterial/updateJobMaterial/deleteJobMaterial/deleteJobMaterialsandcreateJobOperation/updateJobOperation/deleteJobOperation/deleteJobOperations(the plural two are unpublished: Delete Selected, one recalculation) /reorderJobOperations/setJobOperationStatus(a Done operation returns its unconsumed picks) /setJobOperationDueDate/syncJobOperationProcedureback the bill of material and bill of process routes underx+/job+/methods+/; Get Method and the material, operation and procedure writes refuse a locked job (requireJob). Save Method (x+/job+/methods+/save.tsx) isupsertMakeMethodFromJob/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/updateProductionEventsave a production event and post an ended one to the GL (post-production-event; a skipped posting is returned aspostingError).createProductionQuantityrecords a production quantity (refuses a locked job, keeps a scrap reason only on Scrap);updateProductionQuantitycorrects one and needs accounting update, so it is not published. The procedure properties panel posts tosetProcedureFields. The bare row writes (upsertJobMaterial,upsertJobOperation,upsertJobMethod,upsertProductionEvent,updateJob) are building blocks inproduction.service.tsand are never tools.cancelJob(production.server.ts, published asproduction_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 infromStatuses(defaultCANCELLABLE_JOB_STATUSES; a refusal is aconflictand changes nothing), then returns its unconsumed picked material (post-pickingreturnJobRemainders, which sweeps only a Completed or Cancelled job) and cancels its open picking-list lines; a failure of either is awarning, the job stays Cancelled. Pinned bytest/database/cancel-job.test.ts. Planning edits a job only whileisJobEditableFromPlanning(production.models.ts: Draft / Planned)getPlanningActions/getPlanningActionsByIds— the persisted MRP worklist (planningAction, written bygeneratePlanningActionsin@carbon/planningafter every MRP run; statusesOpen/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) andreopenPlanningActions(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).settleNewSupplyPlanningActionsis 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 purenextJobPriority— a "No Deadline" job becomesSoft Deadline,deadlineTypeForPlanningDate, since the job form hides the due date for No Deadline), and the route sends oneschedule-inputs-changedevent 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 inplanning-action-claims.ts(claimPlanningActions/releasePlanningActionClaims), shared with purchasing'sapplyPurchasingPlanningActions. Bad input to either planning route answers 400, a failed read or write 500.releasePlanningActionClaimgives a failed per-job apply's claim back (deleting it instead when MRP has already written an Open row for the same need), andupdatePlanningJobis planning's single-job write (the drawer's inline edit, and Increase / Decrease), guarded on Draft / Planned in the UPDATE itself; a quantity change restatesscrapQuantityfrom the item's scrap rate.planDraftJob(production.server.ts) is the drawer's Plan on a Draft job (planJobintent), inreleaseJobs' 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.planningActionis read-only through the API; its writers use the service role. Applied fromx+/production+/planning.update.tsx(one service-function call peraction:order(orderPlannedJobs),updateJob(updatePlannedJob),planJob(planJobFromPlanning),applyand its typed aliases (applyPlanningActions),dismiss(dismissProductionPlanningActions),reopen(reopenProductionPlanningActions),assign(assignProductionPlanningActions); a dismiss / reopen / assign that changes nothing is aconflict) andx+/purchasing+/planning.update.tsx;usePlanningActionsreads both routes' answers; UI inui/Planning/:ProductionPlanningTable+ProductionPlanningOrderDrawer,planningColumns.tsx(the column set shared with purchasing: the Stock Availability week strip viaPlanningWeekStrip+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), andplanning-action-scope.ts(resolvePlanningActionScope,actionsOfTypes,PLANNING_ACTIONS_COLUMN,PLANNING_ASSIGNEE_COLUMN,PLANNING_DRAWER_PARAM— pure, re-exported fromproduction.models.tsso 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:chartedOrderQuantitycharts an order at its open Increase), andplanning-review.ts(pure:planningActionNeedsReview— Review vs Apply from the order's LIVE status,purchaseOrderStatus/jobStatusfromgetPlanningActions, not MRP's run-timerequiresManualActionstamp, so a PO reopened since applies at once; a date move on a supplier-promised line stays Review — andpurchaseOrderPlanningMenu, which order commands a row's ⋯ offers;PlanningActionHandlers.purchaseOrderMenuItemscarries them, purchasing only). Both planning grids put the open order drawer's item in the address (?item=<itemId>,useLinkedDrawerItemin~/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.tsupsertMaintenanceDispatch/upsertMaintenanceSchedule— maintenance managementupdateAssemblyStepHiddenComponents— autosave for a step's hidden list (routex+/assembly+/$id.steps.hidden.$stepId.tsx). The rule "a step never hides its own parts" lives in ONE place, theassembly_step_strip_own_hidden_componentsBEFORE trigger (migration20260925063121), 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 derivesinstructionTextfrom the tiptapdescription(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) andx+/assembly+/$id.activate.tsx(make active). Change-notice diffs of amethodOperationnow surface itsassemblyInstructionId(resolved to the instruction name),inspectionDocumentId(drawing/file name), andoperationTypeviastampOperationRefNames+ChangeNoticeDiffViewer(items module)updateAssemblyStepMotion— partialmotion/camera/orientationpatch for one step, used by the 3D path/camera editor's autosave and the orientation turn buttons (never touchestitle/typed fields);camera: nullclears the pose (return to auto-framing),orientation: nullmakes the step inherit its build's orientation again, andresetputs backwarnings.plannedMotion(the motion before the first hand-drawn path). It takes the Kysely handle (the route passesgetDatabaseClient()) and writes every patch as ONEUPDATE … WHERE id AND companyIdwhose jsonb expressions readmotion/warningsfrom the row being written: a path edit recordsplannedMotionfrom the oldmotiononly when the marker is absent, Reset restores it (else{"type":"none"}) and drops the marker (warnings→ NULL when nothing else is left),flagged/blockedByare 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 withstepPatchFormData(ui/Assemblies/assembly-step-patch.ts);useStepMotionEditorowns 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) anduseBuildOrientationowns the orientation fetcher and shows the pending orientation in the viewer before the save lands. The panel receives them as the groupedmotionEditing/camera/orientationprops. Deleting an instruction also drops the model's cached plan viadeleteAssemblyInstruction→invalidateAssemblyPlanCachegenerateAssemblyStepsFromPlan— plan.json → draft steps viabuildAssemblyStepGroups(@carbon/viewer): sequence order, consecutive identical components merged, subassemblygroupsone step (titled by the unitname),mergedIntocomponents 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'scontactsgraph 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 lackingcontacts;mode: "regenerate"replaces existing steps, refused while any step isplanConfidence: "manual"or statusDone. Persists a humantitleon every step viadescribeStep(@carbon/viewer) — real editable data, not just a render-time fallback. Seeds each step's materials from the component→BOM mappings (best-effort): auto-runsautoMatchAssemblyComponentsonce when the model has no mappings yet, and returnsunmappedComponentCount(distinct geometry groups with no BOM item) which the generate route surfaces as a "use Match BOM" nudgesyncAssemblyStepMaterialsFromMappings— adds mapped BOM items (assemblyComponentMapping) to steps' materials from theircomponentNodeIds(quantity = instance count in the step); additive + best-effort, never updates or removes rows; scopable bystepIds/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[]+ optionalitemId), authored from the BOM treeUnit 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-authoredassemblyUnitrows ("plan as one component" from the BOM tree), whichloadPlanUnits(@carbon/jobs) sends asoptions.units; the planner merges units for planning and expands them back to member leaves with a namedgroupsentry (→ one titled step). Detected groups are ALSO materialized asassemblyUnitrows 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, andloadPlanUnitsfeeds 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-bridgeread_step), so they plan like proper assemblies instead of one un-plannable blobAssembly 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 answersplanning: true),cancelAssemblyJob,convertAssemblyModel,reconvertAssemblyModel(model.invalidate),matchAssemblyBom(component-mappings.auto),mapAssemblyComponent,reassignAssemblyComponents,setAssemblyStepComponentsandsyncAssemblyToOperation. 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 pickersyncAssemblyInstructionToOperation— Assembly → job-operation re-sync (Kysely txn): copies an instruction's steps (any status) into ajobOperationasjobOperationSteprows (typed fields mirror 1:1), links per-step BOM parts viajobMaterialStep(itemId resolved against the operation's ownjobMaterial), refreshes slides on synced steps (delete + recreate: the instruction's 3D model leads as a model slide at sortOrder 0, then the step's authoredassemblyInstructionStepSliderows), syncs tools (ensures ajobOperationToolper distinct tool item — never deleted, quantity only ratchets up — and rebuildsjobOperationToolSteplinks on synced steps), and setsjobOperation.assemblyInstructionId. Synced steps are numbered AFTER the operation's own (procedure / hand-authored) steps — both sets start at 1, so keeping the instruction'ssortOrderinterleaved them;insertAssemblyDataForJobOperationin get-method does the same. Re-runnable via theassemblyInstructionStepIdprovenance marker (update matched / insert new / delete stale; hand-authored NULL-marker steps untouched; ON DELETE SET NULL demotes to hand-authored). Routex+/assembly+/$id.sync-bop.tsxcallssyncAssemblyToOperation(production_update, refuses a locked job); UI = "Sync Assembly Steps" on an Assembly operation inJobBillOfProcess(AssemblyStepsSyncModal), mirroring the "Sync Procedure" flow. Method/quote operations only store theassemblyInstructionIdpointer — 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 andAssemblyViewmounts the@carbon/viewerAssemblyPlayerpinned to the operator's current stepcreateJobDocumentUploadUrl— MCP file upload (step 1): presigned URL for a job document (job/{jobId}folder); pair withdocuments_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.salesOrderLineIdlinks back - items —
job.itemIdreferences 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
fixedAssetrows instead of stock (.claude/rules/fixed-asset-lifecycle.md); the fleet register's Build for Fleet opensx+/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