Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
MES: job due dates, need-by targets, and schedule urgency (#1852)
Brad Barbin4604fc87d72d
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 7b9aae7c28..da0439ff68 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -3060,3 +3060,14 @@ And a delete whose failure the caller ignores is not a delete: return the error.**Rule:** Do not call `plural()` (or `select()`) from `@lingui/core/macro` inside a component passed inline to `memo(…)` or any other call. Use `<Plural>` in JSX. For a string (a toast), either build it in a function-declaration hook (`function useX() { const { t } = useLingui(); return (n: number) => t`${plural(n, …)}`; }`), or choose between two whole `t` phrases (``n === 1 ? t`Released 1 job` : t`Released ${n} jobs` ``) — both phrases are extracted and translated, but a locale with more plural forms gets only two. When in doubt, read the compiled module (Vite `transformRequest` on the file) and check for an import of `i18n` from `@lingui/core`.**Applies to:** every `memo(…)` component in `apps/{erp,mes}/app` and `packages/{react,form}/src` (most ERP tables); any new use of `plural` / `select` from `@lingui/core/macro`.+++## A row stayed off a screen only because a column happened to be null++**Context:** The MES Work Centers board, the ERP Priority board and the API read `get_active_job_operations_by_location`. Both boards group operations into work-center columns.++**Problem:** An Outside Processing operation showed up on the MES board for an operator to start (2026-10-05). The function never filtered on `operationType`; subcontracted operations stayed off the boards only because they usually have no work center, so they had no column. The work center came back two ways. The operation forms hide the Work Center field for Outside Processing, and a hidden field is omitted from the submit, not cleared, so an update left the work center from the operation's earlier in-house type. Batching was the second way: `get_batchable_operations` offered outside operations, and releasing a batch writes the batch's work center onto every member.++**Rule:** Filter on the fact that decides whether a row belongs, never on a column that only usually agrees with it. When a type makes a field meaningless, clear the field in the one function every writer goes through (`normalizeOperationSourceIds`), because hiding the input does not clear it. Hiding a row from a list is not a gate: refuse it in the routes that open and start it too.++**Applies to:** `get_active_job_operations_by_location`; `get_batchable_operations` and the `batch-operations` `assertEligible`; the MES operation, start and event routes; any form that hides a field by type; any list whose visibility rests on a NULL.diff --git a/.claude/rules/mes-job-operation-ui.md b/.claude/rules/mes-job-operation-ui.mdindex 5e5548269b..3d412fad41 100644--- a/.claude/rules/mes-job-operation-ui.md+++ b/.claude/rules/mes-job-operation-ui.md@@ -83,6 +83,14 @@ member jobs via a two-step `.or(status.in…, id.in…)` (quoted statuses — "IProgress" has a space). List visibility alone was the leak: nothing else gateda direct operation URL.+**Outside Processing never runs on the floor.** Subcontracted work runs at the+supplier: `get_active_job_operations_by_location` filters it by type (not by a+null `workCenterId`, which a stale value defeats), and the operation loader, the+`start.$operationId.tsx` loader (before its timer re-open) and `event.tsx`'s+Start branch all refuse it with `OUTSIDE_PROCESSING_REFUSAL`+(`utils/operationView.ts`). `resolveOperationView` still maps it to the Operation+view so the resolver stays total; the refusal is the routes' job.+There is **no separate batch page** — the operation view IS the batch UI. Inbatch mode the job heading is replaced by ONE scope switcher — an outlineddiff --git a/.claude/rules/scheduling-data-structures.md b/.claude/rules/scheduling-data-structures.mdindex 7ebfc0d90a..340704d4f3 100644--- a/.claude/rules/scheduling-data-structures.md+++ b/.claude/rules/scheduling-data-structures.md@@ -293,8 +293,11 @@ only; its output is read by nothing in the placement path (spec`job.dueDate` (null due date ⇒ all-null targets); leaves are due on the job duedate; an op with dependents is due at the earliest dependent constraint — thedependent's need-by START minus that dependent's `operationLeadTime` working- days, minus this op's `assemblyLeadTime` at assembly edges (a sub-make-method- feeding its parent); "With Previous" ops copy their partner's target dates; a+ days. An assembly edge (a sub-make-method feeding its parent) subtracts NO+ item lead time: the subassembly's own ops are in the walk, so adding+ `itemReplenishment.leadTime` (default 7) counted the build twice per BOM+ level and put targets weeks before the job's start. "With Previous" ops copy+ their partner's target dates; apinned op's stored `dueDate` is taken as-is AND propagates upstream. Day mathruns on real calendars via `calendarAdapters` over the SAME availability-ladderwindows placement uses (one shared `loadAvailabilityWindows()` fetch):@@ -462,14 +465,22 @@ the "conflict" count.)## Read RPCs (display only; do not compute schedules)### `get_active_job_operations_by_location(location_id, work_center_ids[])`-Newest: `20260818031629_dual-dates.sql` (forked from `20260720121629_capacity-planning.sql`-+ a `projectedCompletionAt TIMESTAMPTZ` output column; prior revisions:-capacity-planning added `hasConflict`/`conflictReason`,-`20260531084723_rework-serial-flow.sql`+Newest: `20261006021134_mes-hide-outside-processing.sql` (excludes+`operationType = 'Outside Processing'`; prior revisions:+`20260905132037_job-operation-batching.sql` added the batch columns and the+membership-handoff floor rule, `20260818031629_dual-dates.sql` added+`projectedCompletionAt TIMESTAMPTZ`, `20260720121629_capacity-planning.sql` added+`hasConflict`/`conflictReason`, `20260531084723_rework-serial-flow.sql`added `quantityReworked`/`reworkId`, `20260304000000` added `operationDueDate`).+It feeds the MES Work Centers board, the ERP Priority board and the API tool+`production_getActiveJobOperationsByLocation`. Outside Processing is filtered by+TYPE, not by a null `workCenterId`: both boards' columns are work centers, so an+outside operation holding a stale work center (left over from an in-house type)+otherwise lands in that column for an operator to start. Pinned by+`supabase/tests/outside-processing-off-the-floor.test.sql`.TS wrappers (identical): `apps/mes/app/services/operations.service.ts``getActiveJobOperationsByLocation` and-`apps/erp/app/modules/production/production.service.ts`. Returns 41 cols incl.:+`apps/erp/app/modules/production/production.service.ts`. Returns 44 cols incl.:`id, jobId, jobMakeMethodId, operationOrder` (← `jo."order"`)`, priority, processId,workCenterId, description, setup/labor/machineTime+Unit, operationOrderType` (←`jo."operationOrder"`, serial/parallel enum)`, jobReadableId, jobStatus, jobDueDate,@@ -480,8 +491,8 @@ salesOrderId/LineId/ReadableId, assignee, tags, thumbnailPath, operationDueDate`(← `jo."dueDate"`, the need-by target)`,reworkId, hasConflict` (COALESCEd, never null)`, conflictReason,projectedCompletionAt` (← `jo."projectedCompletionAt"`, the projected finish-instant). The ERP ops board-(`schedule+/operations.tsx` → `ItemCard`) and MES schedule loader map+instant)`, processBatchable, jobOperationBatchId, batchReadableId`. The ERP ops board+(`priority+/operations.tsx` → `ItemCard`) and MES schedule loader map`hasConflict`/`conflictReason` onto Kanban items (red border + triangle tooltip onthe ERP card); the dual dates drive the amber behind-target state (projected day >need-by). The same dual-dates migration also forks `get_job_operation_by_id`@@ -545,10 +556,23 @@ capacity-planning migration and drive the dates board's forecast/stale surfaces.`jobOperation.dueDate` is the backward demand-anchored need-by target (DATE, stable— changes only when the job due date, routing, or lead times change; a pinned op'sis human-owned). The job-level forecast finish is `job.projectedCompletionAt`.- Consumers that key urgency on op `dueDate` (MES queue sort + overdue flags,+ Consumers that key urgency on op `dueDate` (MES queue sort,the People Capacity view's Demand buckets, `get_picking_schedule` ordering) aredeliberately unchanged — they now honestly read "when work is needed", not the- sim's last forecast. `getJobPromiseDate` returns `job.projectedCompletionAt` or+ sim's last forecast. The MES operation view's "Due" header, Due Date card and+ overdue flag read the JOB's `jobDueDate`; the op target is shown under it as+ "Operation needed by …" and only drives the behind-target projection badge.+ Labelling the op target "Due" with the job's deadline icon read as the job+ being due weeks early. The MES Work Centers board cards follow the same rule:+ `Item.dueDate` is `jobDueDate`, so the "Due …" line, the overdue flag, the+ urgency border (`getDueUrgency`) and a collapsed batch's earliest member+ deadline all read the job's date, against the location's `today` from the+ loader rather than the device's day. The ERP Priority board still maps+ `operationDueDate`, since its card carries the behind-target badge. The+ urgency classifiers and both boards' batch reductions ignore an ASAP or No+ Deadline due date — only Hard and Soft Deadline carry one+ (`deadlineRequiresDueDate`), but an ASAP job can still hold a stale date.+ `getJobPromiseDate` returns `job.projectedCompletionAt` ornull (its old max-op-dueDate fallback would now just echo the job due date andwas removed).- Editing the ERP ops board (`operations.update.tsx`) does NOT re-run the engine and doesdiff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex 24f2da69f6..6fa88d0c4a 100644--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@ -10,7 +10,7 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced- **Job Material** — BOM line within a make method. Each has a `methodType` (Pull from Inventory, Purchase to Order, Make to Order) that drives procurement.- **Production Event** — time tracking (Labor/Machine/Setup) against an operation.- **Production Quantity** — output recording (Production/Scrap/Rework) against an operation with optional `scrapReason`.-- **Operation Batch** (`jobOperationBatch`) — N job operations sharing one run on a **batchable process** (`process.batchable`: laser table, furnace, plating; `process.batchType` `Sequential`/`Simultaneous` = the s-batch/p-batch physics — serial queue vs parallel load — driving the batch's planned duration `setup(max) + Σ|max(run)` via `@carbon/utils` `batchDuration`). Jobs are never merged and the BOM is never modified; each member stays a first-class `jobOperation`. Time/cost split **proportional to `operationQuantity`**, materialized at completion as per-member `productionEvent` slices, so job costing/GL post per job with no special-casing. Status **`Planned → Active → Completing → Completed`** (no `Cancelled` — dissolve deletes a pre-start batch instead). `Planned` is the pre-floor state: composed in the builder from ANY live job's unstarted ops (the planner RPC no longer requires released jobs), fully editable (add/remove/work-center widened to Planned+Active pre-event), invisible to MES. **`Active` displays as "Released"** (exactly like job `Ready`); the `release` server-function intent (`Planned → Active`, requires ≥1 member — NO work center: the scheduler pre-pass auto-selects earliest-finish among the process's work centers and persists it to batch + members) puts members on the floor, and releasing it RELEASES its Draft/Planned member jobs through the job page's own path — `releaseBatchMemberJobs` → `releaseJobs` (`production.server.ts`: recalc, MRP, status Ready, outside-operation POs via `create` `purchaseOrderFromJob`, releasedDate) after `getJobReleaseReadiness` validates EVERY such job (assemblies without operations, manufacturing blocked, or an outside operation whose supplier can't be resolved — `resolveOperationSupplier`: its own supplier process, else the process's only supplier — refuse the whole batch untouched; there is no per-operation supplier picker on batch release); a supplier's first new PO is reused for the later jobs so a batch lands on one PO per supplier. The `BatchReleaseModal` (drawer, table row action, builder Create & Release) shows the checks and the per-supplier PO choice; bulk `batches/release` passes no choice, so a batch needing a fix or with Draft POs to choose from is skipped and named. Then it notifies the scheduler; `unrelease` (`Active → Planned`) is allowed only before the first production event. **Membership-handoff floor rule**: an op in a batch is floor-visible iff its BATCH is Released (`Active`/`Completing`) — even when its job is Draft/Planned; an op in no batch follows its JOB's release (the pre-batching rule — a released job's un-batched batchable op always remains runnable, never blocked; removing it from a batch is the escape hatch). Enforced in `get_active_job_operations_by_location`, MES `getOpenJobs`, AND server-side in the MES operation loader + start route (list visibility alone was the leak). **Scheduling**: a Released batch is ONE scheduling unit — the batch pre-pass (`packages/planning/src/scheduling/batch-scheduler.ts`, run by `runLocationSchedule` before the per-job passes) writes a single coalesced `capacityReservation` tagged `jobOperationBatchId` (NOT NULL `operationId`/`jobId` anchored on the min member op), members pin to the window in the selector (generalized pinned-OSP path, no per-member reservation), downstream ops chain after the batch end, and the anchor comes from persisted predecessor forecasts (overruns flag a conflict and converge next wave); a batch whose open members all carry zero time standards still surfaces — a flagged 1h placeholder (`workHours` 0, never blocks) with a conflict naming the data gap, instead of silently vanishing from the reservation-driven forecast; Planned batches still schedule per-op. Completion is **two-phase and resumable** — Phase 1 (one txn) slices events + records quantities + flips `Active → Completing`; Phase 2 (idempotent, server-function-owned) issues each member's BOM, flips members `Done`, posts GL, then `Completing → Completed`. A Phase-2 failure leaves the batch `Completing` and re-invoking resumes (no double issue/GL). A retry MUST resubmit the quantities Phase 1 recorded — a changed quantity is rejected, not silently applied. Proportional split logic lives in `@carbon/utils` `batch-time-split`. Distinct from lot/batch tracking (`trackedEntity`/`batchNumber`). Mutations go through the `batch-operations` server function (create/add/remove/update/dissolve/complete); payload record ids are re-read under `companyId` (`assertCompanyRecord` for location/work center) and the batch table's location/process/workCenter FKs are composite `(<col>, "companyId")` (`20260905132037_job-operation-batching.sql` (the consolidated branch migration)), so a cross-tenant id is refused by the fn AND rejected by the schema. Batch COMPOSITION happens ONLY in the batch builder (below) — the operations priority board's select-to-batch flow (checkboxes on cards, `BatchSelectionProvider`, the floating create bar, and the `BatchOpportunity` banner/column hints) was removed 2026-09-01 at Sid's direction, after the dedicated drag-and-drop batching board went the same way 2026-08-21. The board still SHOWS batches: each live batch collapses to one `BatchItemCard` in its work-center column (drag across columns reassigns the batch work center via `priorityBatchingUpdate`; Completing cards are read-only). The one composition surface — a guided **batch builder** — launches from the Batches list (`New Batch`) and an Active batch's drawer (`Add operations` → add-mode): a full-screen three-step drawer wizard (`ui/Batches/BatchBuilder.tsx`) that picks a location + batchable process (deep-linkable via `?location=&process=`; the last scope/view is remembered in localStorage), fetches candidates from `api/production/batchable-operations` (the revived `getBatchableOperations` RPC wrapper, enriched with each op's setup/labor/machine time, due date, and item thumbnail, plus per-work-center queue load and a hidden-ops count), and offers local search, a due-window quick filter (7/14/30d, due-date-sorted), a dynamic local-state "+ Filter" facet picker over the dimensions the candidates' BOMs actually contain (the material ITEM itself plus substance/grade/dimension/form/finish where populated — ANY BOM line matches ALL active facets; active facets render as removable/editable chips), two list views (polished table or group-by-material-signature sections with per-group select-all and setup-saving chips — a line's signature falls back to its BOM item's readable id when no normalized properties exist, so property-less BOMs still group by what they consume; an operation with NO op-linked BOM lines takes the JOB's unassigned (`jobOperationId IS NULL`) lines — BOMs are routinely authored without per-operation assignment, and without the fallback every such op read "No materials", emptied the facet picker, and degraded grouping to the produced item), a prominent scored suggestions banner at the top of the operations list — groups ranked by `rankSuggestions` (blended, normalised score: setup saved + due urgency + capacity fit + dimension specificity; each signature group is first split into due-date clusters no wider than `SUGGESTION_DUE_WINDOW_DAYS` = 7 via `splitByDueWindow`, so a suggestion never spans weeks — same material next month is next month's batch), each row a one-click apply with a reason chip (due now / fills a run); grouping uses `groupingKey` (material signature, falling back to the produced item for material-less assembly ops) while the mixed-materials warning uses the materials-only `materialSignature`, so the fallback never fakes a material clash. The pure logic (signatures, value sets, duration math, scoring) lives in `ui/Batches/batch-builder-logic.ts` — no JSX/lingui, unit-tested by `apps/erp/test/batch-suggestions.test.ts`, and a live preview (count · quantity · estimated run time, setup-saving + due-spread chips, plus a non-blocking "mixing materials" warning — material compatibility guides but never blocks, per the locked spec decision). Create-mode can attach a work center (picker shows each center's queue depth) and optional notes (additive `notes` field on the server function's create payload), and — instead of creating a duplicate — offers a searchable **"Add to batch"** footer popover (`AddToBatchButton`: a `Command` list over the compatible Active same-process batches from `deriveAddTargets`, each row `readableId · N ops`, on-select → the same `add` submit) rather than one button per batch, so it scales to hundreds of open batches. When the chosen work center has a `batchCapacity` set, a fill bar under the picker shows selected qty vs capacity ("fits in one run" / "over capacity — N loads") plus a `minimumBatchQuantity` met/short line — purely ADVISORY, Create never blocks (`resources.workCenter.batchCapacity`/`minimumBatchQuantity`). The scoped process's `batchRules` (`process.batchRules`, threaded through `getBatchableProcesses`) drives compatibility: the candidate signature/facets/mixed-material warning use every non-"ignore" dimension (default substance/grade/dimension, with the material item as a fallback for property-less BOMs), a "guide" mismatch versus the current selection shows a quiet amber tag on the row, and a "must" mismatch renders the row visible-but-LOCKED (grey lock tag, checkbox no-op, excluded from suggestions/select-all — clears when the selection empties). All resolution/enforcement is the shared `@carbon/utils` `batch-compatibility` module (`resolveBatchRules`/`mustViolations`); the client uses names and the server function uses ids through the same value-agnostic fold, so they always agree. The server function's `assertMaterialCompatible` re-checks the WHOLE membership (create: incoming set; add: existing members + incoming) after `assertEligible` and rejects a must-violating batch naming the dimension — the LOCK in the UI is advisory-fast; the server function is the real gate. It submits `create`/`add` to the same `batching.update` action + `batch-operations` server function — no new mutation path. Completion (MES modal → `complete`) can mark a member "not in this run" (`excluded`): it detaches back to the schedule un-run inside the Phase-1 txn instead of flipping Done; excluded members carry no quantities, all-excluded is rejected (dissolve instead), and a resume drops already-applied exclusions but rejects new ones. Batches LIST at `/x/production/batches` (nav: Production → Batches; `getJobOperationBatches` + `getJobOperationBatchMemberStats` + `getJobOperationBatchMembers`); rows are **expandable** (`renderExpandedRow`/`canExpandRow` on the shared `Table`, same mechanism as the ECO change-notices table) to reveal each member operation (job link, item thumbnail + readable id, completed/qty + scrap); clicking a batch opens a FULL-SIZE detail drawer (`ui/Batches/BatchDetailDrawer.tsx`): header meta (status/process/WC/location/created-by/notes), an enriched member table (thumbnails, completed/qty + scrap, status badges), and a Run card — per-type actual-vs-plan progress (per-type plan buckets = max member setup + Σ|max labor/machine by `process.batchType`; the "Planned time" total = shared setup + Σ|max of each member's run `max(labor, machine)`, matching the scheduler's reservation and MES batch mode via `@carbon/utils` `batchPlanBreakdown`) with a pulsing timer-running badge and the batch's production-event history (`getJobOperationBatchWithMembers` + `getJobOperationBatchEvents`; completed batches show the per-member slices, which keep the batch tag). The Batches list also bulk-RELEASES via selectable rows → a "Release N batches" bulk action posting the selected **Planned** ids to the `batches/release` route (one release per id, mirroring the single-batch `batching.update` release branch: `releaseBatchMemberJobs` → `releaseJobOperationBatch` → `notifyScheduleInputsChanged`; per-batch server-function refusals land in the toast summary's `failed` list, the rest still release; a non-Planned id from a stale selection is skipped). Deleting from ERP = the server function's `dissolve`: single via the `batches/delete/:batchId` ConfirmDelete route (destructive "Dissolve Batch" in the table's row context menu + a destructive Dissolve button on the detail drawer, Active only), and bulk via selectable rows → a "Dissolve N batches" bulk action posting the selected Active ids to the `batches/dissolve` route (one server-function dissolve per id; the server's per-batch refusal for started batches lands in the toast summary's `failed` list, the rest still dissolve), and a printable **batch list** serves at `/file/batch/:id.pdf` (`BatchListPDF` in `@carbon/documents`; menu entries on the batch card and MES batch chip). **Materials and output lots (2026-09-16):** the MES batch-mode materials panel shows each item's summed BATCH requirement alongside the member's own (`getBatchMaterialTotals`), and ONE pick covers the whole batch — `issue` case `trackedEntitiesToBatch` splits the picked lot(s) **pro-rata by each member's REMAINING requirement** (`splitPickAcrossMembers` in `@carbon/utils` `batch-pick-split`, largest-remainder so shares sum exactly) and records each member's own consumption against its own WIP entity, so cost and lot genealogy stay per job while the operator acts once; the pick modal's default quantity is the batch remaining, NOT the member's share (defaulting to one member's share splits it again across all of them and satisfies none). Completion finalizes each member's produced lot via the lean `issue` case `jobOperationBatchOutput` (the `Produce` activity + entity flip EXTRACTED from `jobOperationBatchComplete`, WITHOUT that case's `productionQuantity` insert and backflush — Phase 1 and the Phase-2 issue step already did both), under lot numbers PLANNED AT CREATION — the builder's Output section (`ui/Batches/BatchOutputLots.tsx`) either sets each member's lot (written to its WIP `trackedEntity.readableId` by the `batch-operations` create) or, when every member makes the same batch-tracked item, "Combine output into one lot" (`jobOperationBatch.mergeOutput` + `outputLotNumber`, migration `20260918094217_batch-output-lot-at-creation.sql`); the operator never edits lots at completion. A merged batch's member lots are combined right after completion (and the batch drawer's "Merge output lots" covers a Completed batch kept separate) into ONE lot via `issue` `mergeTrackedEntities` — genealogy keeps every source job, so the merged lot is strictly more traceable than a single directly-produced one. Both entry points derive the parent ids SERVER-SIDE from the batch's membership and call the `issue` server function. Eligibility gained a `producedItem` dimension in `BATCH_RULE_DIMENSIONS` (default `ignore`) so a process can require members to make the same item. Serial-tracked members are unchanged — batch mode still disables tracked activity for them. Job surfaces show live-batch membership: a Batches column on the jobs table (loader-side lookup), a badge on the `JobBillOfProcess` operation row (`jobOperationBatch` embed), and a chip on the MES job DAG node.+- **Operation Batch** (`jobOperationBatch`) — N job operations sharing one run on a **batchable process** (`process.batchable`: laser table, furnace, plating; `process.batchType` `Sequential`/`Simultaneous` = the s-batch/p-batch physics — serial queue vs parallel load — driving the batch's planned duration `setup(max) + Σ|max(run)` via `@carbon/utils` `batchDuration`). Jobs are never merged and the BOM is never modified; each member stays a first-class `jobOperation`. Time/cost split **proportional to `operationQuantity`**, materialized at completion as per-member `productionEvent` slices, so job costing/GL post per job with no special-casing. Status **`Planned → Active → Completing → Completed`** (no `Cancelled` — dissolve deletes a pre-start batch instead). `Planned` is the pre-floor state: composed in the builder from ANY live job's unstarted ops (the planner RPC no longer requires released jobs), fully editable (add/remove/work-center widened to Planned+Active pre-event), invisible to MES. **`Active` displays as "Released"** (exactly like job `Ready`); the `release` server-function intent (`Planned → Active`, requires ≥1 member — NO work center: the scheduler pre-pass auto-selects earliest-finish among the process's work centers and persists it to batch + members) puts members on the floor, and releasing it RELEASES its Draft/Planned member jobs through the job page's own path — `releaseBatchMemberJobs` → `releaseJobs` (`production.server.ts`: recalc, MRP, status Ready, outside-operation POs via `create` `purchaseOrderFromJob`, releasedDate) after `getJobReleaseReadiness` validates EVERY such job (assemblies without operations, manufacturing blocked, or an outside operation whose supplier can't be resolved — `resolveOperationSupplier`: its own supplier process, else the process's only supplier — refuse the whole batch untouched; there is no per-operation supplier picker on batch release); a supplier's first new PO is reused for the later jobs so a batch lands on one PO per supplier. The `BatchReleaseModal` (drawer, table row action, builder Create & Release) shows the checks and the per-supplier PO choice; bulk `batches/release` passes no choice, so a batch needing a fix or with Draft POs to choose from is skipped and named. Then it notifies the scheduler; `unrelease` (`Active → Planned`) is allowed only before the first production event. **Membership-handoff floor rule**: an op in a batch is floor-visible iff its BATCH is Released (`Active`/`Completing`) — even when its job is Draft/Planned; an op in no batch follows its JOB's release (the pre-batching rule — a released job's un-batched batchable op always remains runnable, never blocked; removing it from a batch is the escape hatch). Enforced in `get_active_job_operations_by_location`, MES `getOpenJobs`, AND server-side in the MES operation loader + start route (list visibility alone was the leak). **Scheduling**: a Released batch is ONE scheduling unit — the batch pre-pass (`packages/planning/src/scheduling/batch-scheduler.ts`, run by `runLocationSchedule` before the per-job passes) writes a single coalesced `capacityReservation` tagged `jobOperationBatchId` (NOT NULL `operationId`/`jobId` anchored on the min member op), members pin to the window in the selector (generalized pinned-OSP path, no per-member reservation), downstream ops chain after the batch end, and the anchor comes from persisted predecessor forecasts (overruns flag a conflict and converge next wave); a batch whose open members all carry zero time standards still surfaces — a flagged 1h placeholder (`workHours` 0, never blocks) with a conflict naming the data gap, instead of silently vanishing from the reservation-driven forecast; Planned batches still schedule per-op. Completion is **two-phase and resumable** — Phase 1 (one txn) slices events + records quantities + flips `Active → Completing`; Phase 2 (idempotent, server-function-owned) issues each member's BOM, flips members `Done`, posts GL, then `Completing → Completed`. A Phase-2 failure leaves the batch `Completing` and re-invoking resumes (no double issue/GL). A retry MUST resubmit the quantities Phase 1 recorded — a changed quantity is rejected, not silently applied. Proportional split logic lives in `@carbon/utils` `batch-time-split`. Distinct from lot/batch tracking (`trackedEntity`/`batchNumber`). Outside Processing operations are never batchable — a batch is one run on one of our work centers, and joining one would stamp its work center onto subcontracted work: `get_batchable_operations` leaves them out of the candidates and `assertEligible` refuses them. Mutations go through the `batch-operations` server function (create/add/remove/update/dissolve/complete); payload record ids are re-read under `companyId` (`assertCompanyRecord` for location/work center) and the batch table's location/process/workCenter FKs are composite `(<col>, "companyId")` (`20260905132037_job-operation-batching.sql` (the consolidated branch migration)), so a cross-tenant id is refused by the fn AND rejected by the schema. Batch COMPOSITION happens ONLY in the batch builder (below) — the operations priority board's select-to-batch flow (checkboxes on cards, `BatchSelectionProvider`, the floating create bar, and the `BatchOpportunity` banner/column hints) was removed 2026-09-01 at Sid's direction, after the dedicated drag-and-drop batching board went the same way 2026-08-21. The board still SHOWS batches: each live batch collapses to one `BatchItemCard` in its work-center column (drag across columns reassigns the batch work center via `priorityBatchingUpdate`; Completing cards are read-only). The one composition surface — a guided **batch builder** — launches from the Batches list (`New Batch`) and an Active batch's drawer (`Add operations` → add-mode): a full-screen three-step drawer wizard (`ui/Batches/BatchBuilder.tsx`) that picks a location + batchable process (deep-linkable via `?location=&process=`; the last scope/view is remembered in localStorage), fetches candidates from `api/production/batchable-operations` (the revived `getBatchableOperations` RPC wrapper, enriched with each op's setup/labor/machine time, due date, and item thumbnail, plus per-work-center queue load and a hidden-ops count), and offers local search, a due-window quick filter (7/14/30d, due-date-sorted), a dynamic local-state "+ Filter" facet picker over the dimensions the candidates' BOMs actually contain (the material ITEM itself plus substance/grade/dimension/form/finish where populated — ANY BOM line matches ALL active facets; active facets render as removable/editable chips), two list views (polished table or group-by-material-signature sections with per-group select-all and setup-saving chips — a line's signature falls back to its BOM item's readable id when no normalized properties exist, so property-less BOMs still group by what they consume; an operation with NO op-linked BOM lines takes the JOB's unassigned (`jobOperationId IS NULL`) lines — BOMs are routinely authored without per-operation assignment, and without the fallback every such op read "No materials", emptied the facet picker, and degraded grouping to the produced item), a prominent scored suggestions banner at the top of the operations list — groups ranked by `rankSuggestions` (blended, normalised score: setup saved + due urgency + capacity fit + dimension specificity; each signature group is first split into due-date clusters no wider than `SUGGESTION_DUE_WINDOW_DAYS` = 7 via `splitByDueWindow`, so a suggestion never spans weeks — same material next month is next month's batch), each row a one-click apply with a reason chip (due now / fills a run); grouping uses `groupingKey` (material signature, falling back to the produced item for material-less assembly ops) while the mixed-materials warning uses the materials-only `materialSignature`, so the fallback never fakes a material clash. The pure logic (signatures, value sets, duration math, scoring) lives in `ui/Batches/batch-builder-logic.ts` — no JSX/lingui, unit-tested by `apps/erp/test/batch-suggestions.test.ts`, and a live preview (count · quantity · estimated run time, setup-saving + due-spread chips, plus a non-blocking "mixing materials" warning — material compatibility guides but never blocks, per the locked spec decision). Create-mode can attach a work center (picker shows each center's queue depth) and optional notes (additive `notes` field on the server function's create payload), and — instead of creating a duplicate — offers a searchable **"Add to batch"** footer popover (`AddToBatchButton`: a `Command` list over the compatible Active same-process batches from `deriveAddTargets`, each row `readableId · N ops`, on-select → the same `add` submit) rather than one button per batch, so it scales to hundreds of open batches. When the chosen work center has a `batchCapacity` set, a fill bar under the picker shows selected qty vs capacity ("fits in one run" / "over capacity — N loads") plus a `minimumBatchQuantity` met/short line — purely ADVISORY, Create never blocks (`resources.workCenter.batchCapacity`/`minimumBatchQuantity`). The scoped process's `batchRules` (`process.batchRules`, threaded through `getBatchableProcesses`) drives compatibility: the candidate signature/facets/mixed-material warning use every non-"ignore" dimension (default substance/grade/dimension, with the material item as a fallback for property-less BOMs), a "guide" mismatch versus the current selection shows a quiet amber tag on the row, and a "must" mismatch renders the row visible-but-LOCKED (grey lock tag, checkbox no-op, excluded from suggestions/select-all — clears when the selection empties). All resolution/enforcement is the shared `@carbon/utils` `batch-compatibility` module (`resolveBatchRules`/`mustViolations`); the client uses names and the server function uses ids through the same value-agnostic fold, so they always agree. The server function's `assertMaterialCompatible` re-checks the WHOLE membership (create: incoming set; add: existing members + incoming) after `assertEligible` and rejects a must-violating batch naming the dimension — the LOCK in the UI is advisory-fast; the server function is the real gate. It submits `create`/`add` to the same `batching.update` action + `batch-operations` server function — no new mutation path. Completion (MES modal → `complete`) can mark a member "not in this run" (`excluded`): it detaches back to the schedule un-run inside the Phase-1 txn instead of flipping Done; excluded members carry no quantities, all-excluded is rejected (dissolve instead), and a resume drops already-applied exclusions but rejects new ones. Batches LIST at `/x/production/batches` (nav: Production → Batches; `getJobOperationBatches` + `getJobOperationBatchMemberStats` + `getJobOperationBatchMembers`); rows are **expandable** (`renderExpandedRow`/`canExpandRow` on the shared `Table`, same mechanism as the ECO change-notices table) to reveal each member operation (job link, item thumbnail + readable id, completed/qty + scrap); clicking a batch opens a FULL-SIZE detail drawer (`ui/Batches/BatchDetailDrawer.tsx`): header meta (status/process/WC/location/created-by/notes), an enriched member table (thumbnails, completed/qty + scrap, status badges), and a Run card — per-type actual-vs-plan progress (per-type plan buckets = max member setup + Σ|max labor/machine by `process.batchType`; the "Planned time" total = shared setup + Σ|max of each member's run `max(labor, machine)`, matching the scheduler's reservation and MES batch mode via `@carbon/utils` `batchPlanBreakdown`) with a pulsing timer-running badge and the batch's production-event history (`getJobOperationBatchWithMembers` + `getJobOperationBatchEvents`; completed batches show the per-member slices, which keep the batch tag). The Batches list also bulk-RELEASES via selectable rows → a "Release N batches" bulk action posting the selected **Planned** ids to the `batches/release` route (one release per id, mirroring the single-batch `batching.update` release branch: `releaseBatchMemberJobs` → `releaseJobOperationBatch` → `notifyScheduleInputsChanged`; per-batch server-function refusals land in the toast summary's `failed` list, the rest still release; a non-Planned id from a stale selection is skipped). Deleting from ERP = the server function's `dissolve`: single via the `batches/delete/:batchId` ConfirmDelete route (destructive "Dissolve Batch" in the table's row context menu + a destructive Dissolve button on the detail drawer, Active only), and bulk via selectable rows → a "Dissolve N batches" bulk action posting the selected Active ids to the `batches/dissolve` route (one server-function dissolve per id; the server's per-batch refusal for started batches lands in the toast summary's `failed` list, the rest still dissolve), and a printable **batch list** serves at `/file/batch/:id.pdf` (`BatchListPDF` in `@carbon/documents`; menu entries on the batch card and MES batch chip). **Materials and output lots (2026-09-16):** the MES batch-mode materials panel shows each item's summed BATCH requirement alongside the member's own (`getBatchMaterialTotals`), and ONE pick covers the whole batch — `issue` case `trackedEntitiesToBatch` splits the picked lot(s) **pro-rata by each member's REMAINING requirement** (`splitPickAcrossMembers` in `@carbon/utils` `batch-pick-split`, largest-remainder so shares sum exactly) and records each member's own consumption against its own WIP entity, so cost and lot genealogy stay per job while the operator acts once; the pick modal's default quantity is the batch remaining, NOT the member's share (defaulting to one member's share splits it again across all of them and satisfies none). Completion finalizes each member's produced lot via the lean `issue` case `jobOperationBatchOutput` (the `Produce` activity + entity flip EXTRACTED from `jobOperationBatchComplete`, WITHOUT that case's `productionQuantity` insert and backflush — Phase 1 and the Phase-2 issue step already did both), under lot numbers PLANNED AT CREATION — the builder's Output section (`ui/Batches/BatchOutputLots.tsx`) either sets each member's lot (written to its WIP `trackedEntity.readableId` by the `batch-operations` create) or, when every member makes the same batch-tracked item, "Combine output into one lot" (`jobOperationBatch.mergeOutput` + `outputLotNumber`, migration `20260918094217_batch-output-lot-at-creation.sql`); the operator never edits lots at completion. A merged batch's member lots are combined right after completion (and the batch drawer's "Merge output lots" covers a Completed batch kept separate) into ONE lot via `issue` `mergeTrackedEntities` — genealogy keeps every source job, so the merged lot is strictly more traceable than a single directly-produced one. Both entry points derive the parent ids SERVER-SIDE from the batch's membership and call the `issue` server function. Eligibility gained a `producedItem` dimension in `BATCH_RULE_DIMENSIONS` (default `ignore`) so a process can require members to make the same item. Serial-tracked members are unchanged — batch mode still disables tracked activity for them. Job surfaces show live-batch membership: a Batches column on the jobs table (loader-side lookup), a badge on the `JobBillOfProcess` operation row (`jobOperationBatch` embed), and a chip on the MES job DAG node.- **Procedure** — versioned work instructions linked to operations via `processId`. Statuses: Draft/Active/Archived.- **Assembly Instructions** — 3D animated work instructions, available to all users. (Previously gated to Carbon-internal emails via `requireAssembliesInternal` / `useFlags().isInternal`; that gate was removed to ship publicly.) **Versioned** (Draft/Published/Archived) as **row-per-version**, not an in-place counter: sibling versions are grouped by a self-referential `assemblyInstruction.rootInstructionId` (NULL = "I am the root"; group root = `rootInstructionId ?? id`, siblings = `id = root OR rootInstructionId = root`). `copyAssemblyInstructionAsVersion` spins a new editable **Draft** as a perfect copy (`version = max+1`, deep-copies steps with `parentStepId` remapped + each step's materials/slides/tools). `activateAssemblyInstructionVersion` makes a version active: publishes it, **archives the prior Published sibling**, and repoints `jobOperation.assemblyInstructionId` from other group versions to it — but only for active operations (status ≠ Done/Canceled) on active jobs (`!isJobLocked`). Only Draft is editable; the header exposes a "Versions" switcher + Make Active / New Version. `updateAssemblyInstructionStatus` no longer bumps `version`. The **list** (`getAssemblyInstructions`) reads the `assemblyInstructions` **view** (not the base table): it collapses each group to its latest version (`WHERE version = MAX(version)` per `rootInstructionId ?? id`) and rolls every sibling into a `versions` jsonb array, mirroring the `procedures` view — the table shows a `Version N` subtitle on the name plus a "Versions" hover card. Migration `20260730153412_assembly-instructions-view.sql`.- **Sub-assemblies** — a header row (`assemblyInstructionStep.isSubAssembly`, no parts of its own) plus the steps whose `parentStepId` is that header, stored directly BEFORE it in `sortOrder` (play order); the header's `usedInStepId` is the later step that fits the finished unit (NULL = it joins the main build at the header). One level only. Every structural write (`makeAssemblySubAssembly`, `insertAssemblyInstructionStep`, `updateAssemblySubAssembly`, `ungroupAssemblySubAssembly`, `deleteAssemblySubAssembly`, `updateAssemblyInstructionStepOrder`) is a Kysely transaction that locks the instruction, applies the change in memory, checks `validateSubAssemblies` and writes the new order — never a partial update. Header rows are never copied into job steps. The step that uses a sub-assembly never re-lists its parts, so BOM materials are seeded once. Viewer side: `packages/viewer/src/subassembly.ts`.@@ -94,7 +94,7 @@ pnpm --filter @carbon/erp test- `runMRP(client, db, params)` — triggers Material Requirements Planning **in-process** via `runMrp` from `@carbon/planning`; the route action passes the Kysely handle (`getDatabaseClient()` from `~/services/database.server`) — it is NEVER constructed in this service file (which is bundled for the browser via the module barrel; enforced by the `no-db-client-in-service` conformance check). `recalculateJobOperationDependencies(client, db, params)` and `getJobExpediteForecast(client, db, …)` take the handle the same way. Returns the `{ data, error }` shape- `calculateJobPriority` — computes priority from deadline type and due date- `getJobReceiptSnapshot(db, jobId, companyId)` — a job's `quantityReceivedToInventory` plus the `trackedEntity` ids its `Job Receipt` ledger rows already posted, in ONE statement so the two can never come from different moments. Kysely because `itemLedger` is RLS-hidden from users without inventory/accounting view. Served by `api/production/job/:jobId/receipts`, read when the Complete dialog opens-- `getActiveJobOperationsByLocation` — schedule board data (RPC `get_active_job_operations_by_location`, now also returns `processBatchable`/`jobOperationBatchId`/`batchReadableId`)+- `getActiveJobOperationsByLocation` — schedule board data (RPC `get_active_job_operations_by_location`, now also returns `processBatchable`/`jobOperationBatchId`/`batchReadableId`; never lists an Outside Processing operation, even one holding a stale work center)- `getBatchableOperations` / `getBatchableProcesses` — batch builder candidate data (RPC `get_batchable_operations` with per-op BOM material properties), served via `api/production/batchable-operations`. `getBatchableProcesses` also selects `batchRules` so the builder can resolve per-process compatibility rules- `createJobOperationBatch` / `updateJobOperationBatch` — operation batch mutations (call the `batch-operations` server function: create/add/remove/update/dissolve)- `getBatchOutputLots` — a completed batch's MERGEABLE output lots: each member's WIP `trackedEntity` (by `attributes->>Job Make Method`), narrowed in-query to `Available` with stock. Drives the drawer's "Merge output lots"; a merged batch returns none (parents `Consumed`). The merge itself is `inventory`'s `mergeTrackedEntities` wrapper over `issue` `mergeTrackedEntities`diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsxindex c75e0630c5..5c26726e2b 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx@@ -87,6 +87,7 @@ import {LuRefreshCcw,LuSend,LuShieldX,+ LuSquareChartGantt,LuTriangleAlert} from "react-icons/lu";import { Link, useFetcher, useFetchers, useParams } from "react-router";@@ -341,8 +342,9 @@ function makeItem((behindDays > 0 ? (<Tooltip><TooltipTrigger asChild>- <Badge variant="red">- <Trans>Projected {formatDate(projectedDate)}</Trans>+ <Badge variant="red" className="gap-1">+ <LuSquareChartGantt className="size-3 shrink-0" />+ {formatDate(projectedDate)}</Badge></TooltipTrigger><TooltipContent>@@ -352,8 +354,9 @@ function makeItem(</TooltipContent></Tooltip>) : (- <span className="text-xs text-muted-foreground whitespace-nowrap">- <Trans>Projected {formatDate(projectedDate)}</Trans>+ <span className="inline-flex items-center gap-1 text-xs text-muted-foreground whitespace-nowrap">+ <LuSquareChartGantt className="size-3 shrink-0" />+ {formatDate(projectedDate)}</span>))}<OperationDueDatePickerdiff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/BatchItemCard.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/BatchItemCard.tsxindex 208dcddfd3..4015eeeabb 100644--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/BatchItemCard.tsx+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/BatchItemCard.tsx@@ -16,7 +16,10 @@ import {DropdownMenuTrigger,HStack,IconButton,- MENU_ITEM_SHORTCUTS+ MENU_ITEM_SHORTCUTS,+ Tooltip,+ TooltipContent,+ TooltipTrigger} from "@carbon/react";import { useSortable } from "@dnd-kit/sortable";import { useLingui } from "@lingui/react/macro";@@ -30,6 +33,7 @@ import {LuPrinter,LuSquareUser,LuTrash,+ LuTriangleAlert,LuUsers,LuX} from "react-icons/lu";@@ -44,6 +48,7 @@ import {sortableCardProps} from "../cardShell";import { useKanban } from "../context/KanbanContext";+import { DUE_URGENCY_BORDER, getBatchDueUrgency } from "../dueUrgency";import type { BatchItem, OperationItem } from "../types";import { CardMaterialChips, CardSummaryRows } from "./CardSummaryRows";@@ -139,16 +144,28 @@ const BatchItemCardBody = memo(function BatchItemCardBody({0);const totalDuration = members.reduce((sum, m) => sum + (m.duration ?? 0), 0);- // The earliest member due date is the batch's binding constraint.+ // The earliest dated member deadline is the batch's binding constraint. Only+ // Hard and Soft Deadline carry a due date; an ASAP or No Deadline member can+ // still hold a stale one. With no dated member, show the first member's type.const earliest = members.reduce<OperationItem | undefined>((acc, m) => {- if (!m.dueDate) return acc;+ if (+ !m.dueDate ||+ m.deadlineType === "ASAP" ||+ m.deadlineType === "No Deadline"+ )+ return acc;if (!acc?.dueDate || m.dueDate < acc.dueDate) return m;return acc;}, undefined);- const isOverdue =- earliest?.deadlineType !== "No Deadline" && earliest?.dueDate- ? earliest.dueDate < scheduleToday- : false;+ const deadline = earliest ?? members[0];+ const isOverdue = earliest?.dueDate+ ? earliest.dueDate < scheduleToday+ : false;+ // The batch runs as one, so any member the scheduler projects late makes the+ // whole run late — flag it the way the operation card does.+ const conflictedMembers = members.filter((m) => m.hasConflict);+ const hasConflict = conflictedMembers.length > 0;+ const urgency = getBatchDueUrgency(members, scheduleToday);const distinctCustomers = [...new Set(members.map((m) => m.customerId).filter(Boolean))] as string[];@@ -175,6 +192,7 @@ const BatchItemCardBody = memo(function BatchItemCardBody({className={cn("max-w-[330px]",KANBAN_CARD_SHELL,+ urgency && DUE_URGENCY_BORDER[urgency],isPlanned && "border-dashed",isOverlay && "ring-2 ring-primary",isDragging && "ring-2 ring-primary opacity-30"@@ -192,6 +210,21 @@ const BatchItemCardBody = memo(function BatchItemCardBody({</span></HStack><HStack spacing={1} className="flex-shrink-0 -mr-2">+ {hasConflict && (+ <Tooltip>+ <TooltipTrigger>+ <LuTriangleAlert className="h-4 w-4 text-red-500 flex-shrink-0" />+ </TooltipTrigger>+ <TooltipContent>+ {conflictedMembers.map((m) => (+ <div key={m.id}>+ {m.jobReadableId}:{" "}+ {m.conflictReason ?? t`Scheduling conflict`}+ </div>+ ))}+ </TooltipContent>+ </Tooltip>+ )}{!isCompleting && (<IconButtonaria-label={t`Move batch`}@@ -288,8 +321,8 @@ const BatchItemCardBody = memo(function BatchItemCardBody({showDuration={displaySettings.showDuration && totalDuration > 0}duration={totalDuration}showDueDate={displaySettings.showDueDate}- deadlineType={earliest?.deadlineType}- dueDate={earliest?.dueDate}+ deadlineType={deadline?.deadlineType}+ dueDate={deadline?.dueDate}isOverdue={isOverdue}formatRelativeTime={formatRelativeTime}/>diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsxindex 0bbd4edcc8..445cc750e5 100644--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx@@ -31,7 +31,6 @@ import { useLingui } from "@lingui/react/macro";import { cva } from "class-variance-authority";import { memo } from "react";import {- LuCalendarClock,LuCircleCheck,LuCirclePlay,LuClipboardCheck,@@ -41,6 +40,7 @@ import {LuGripVertical,LuPencil,LuPlay,+ LuSquareChartGantt,LuSquareUser,LuTimer,LuTrash,@@ -58,6 +58,7 @@ import { JobOperationStatus } from "~/modules/production/ui/Jobs/JobOperationStaimport { getPrivateUrl, path } from "~/utils/path";import { KANBAN_CARD_SHELL } from "../cardShell";import { useKanban } from "../context/KanbanContext";+import { DUE_URGENCY_BORDER, getDueUrgency } from "../dueUrgency";import type { Item, OperationItem } from "../types";import { isBatchItem } from "../types";import { CardMaterialChips, CardSummaryRows } from "./CardSummaryRows";@@ -117,7 +118,7 @@ function OperationCard({isOverlay?: boolean;progressByItemId: Record<string, Progress>;}) {- const { selectedGroup } = useKanban();+ const { selectedGroup, scheduleToday } = useKanban();const {setNodeRef,attributes,@@ -144,6 +145,7 @@ function OperationCard({transition,transform: CSS.Translate.toString(transform)};+ const urgency = getDueUrgency({ ...item, status }, scheduleToday);// This shell re-renders whenever the drop target changes; the body does// not. It is the expensive part (a form, avatars and menus per card), and@@ -154,13 +156,13 @@ function OperationCard({style={style}className={cn("group/card max-w-[330px]",- item.hasConflict && "border-red-500 border-2",cardVariants({dragging: isOverlay ? "overlay" : isDragging ? "over" : undefined,// @ts-expect-error TS2322 - TODO: fix typestatus: status,highlighted: isHighlighted- })+ }),+ urgency && DUE_URGENCY_BORDER[urgency])}><OperationCardBody@@ -193,9 +195,10 @@ const OperationCardBody = memo(function OperationCardBody({useKanban();const isOverdue =- item.deadlineType !== "No Deadline" && item.dueDate- ? item.dueDate < scheduleToday- : false;+ item.deadlineType !== "ASAP" &&+ item.deadlineType !== "No Deadline" &&+ !!item.dueDate &&+ item.dueDate < scheduleToday;const projectedCompletionDate = item.projectedCompletionAt? item.projectedCompletionAt.slice(0, 10)@@ -401,12 +404,12 @@ const OperationCardBody = memo(function OperationCardBody({/>{displaySettings.showDueDate && projectedCompletionDate && (<HStack className="justify-start space-x-2">- <LuCalendarClock className="text-muted-foreground" />+ <LuSquareChartGantt className="text-muted-foreground" />{isBehindTarget ? (<Tooltip><TooltipTrigger asChild><Badge variant="red">- {t`Proj. ${formatDate(projectedCompletionDate)}`}+ {formatDate(projectedCompletionDate)}</Badge></TooltipTrigger><TooltipContent side="right">@@ -415,7 +418,7 @@ const OperationCardBody = memo(function OperationCardBody({</Tooltip>) : (<span className="text-sm text-muted-foreground">- {t`Proj. ${formatDate(projectedCompletionDate)}`}+ {formatDate(projectedCompletionDate)}</span>)}</HStack>diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/dueUrgency.test.ts b/apps/erp/app/modules/production/ui/Schedule/Kanban/dueUrgency.test.tsnew file mode 100644index 0000000000..3024f987fd--- /dev/null+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/dueUrgency.test.ts@@ -0,0 +1,90 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { getBatchDueUrgency, getDueUrgency } from "./dueUrgency";++const TODAY = "2026-10-05";++describe("getDueUrgency", () => {+ it("is late when the scheduler flagged a conflict, whatever the date", () => {+ expect(+ getDueUrgency({ hasConflict: true, dueDate: "2026-12-01" }, TODAY)+ ).toBe("late");+ });++ it("is late once the due date has passed, even without a conflict", () => {+ expect(getDueUrgency({ dueDate: "2026-10-04" }, TODAY)).toBe("late");+ expect(getDueUrgency({ dueDate: "2026-09-21" }, TODAY)).toBe("late");+ });++ it("is due soon for today and tomorrow", () => {+ expect(getDueUrgency({ dueDate: "2026-10-05" }, TODAY)).toBe("dueSoon");+ expect(getDueUrgency({ dueDate: "2026-10-06" }, TODAY)).toBe("dueSoon");+ });++ it("is nothing two days out, without a deadline, or once finished", () => {+ expect(getDueUrgency({ dueDate: "2026-10-07" }, TODAY)).toBeNull();+ expect(+ getDueUrgency(+ { dueDate: "2026-10-05", deadlineType: "No Deadline" },+ TODAY+ )+ ).toBeNull();+ expect(+ getDueUrgency({ dueDate: "2026-10-05", status: "Done" }, TODAY)+ ).toBeNull();+ expect(+ getDueUrgency({ dueDate: "2026-09-21", status: "Done" }, TODAY)+ ).toBeNull();+ expect(getDueUrgency({ dueDate: null }, TODAY)).toBeNull();+ });++ it("ignores a due date left on an ASAP job", () => {+ // Only Hard and Soft Deadline carry a due date (deadlineRequiresDueDate);+ // an ASAP job can still hold a stale one.+ expect(+ getDueUrgency({ dueDate: "2026-09-21", deadlineType: "ASAP" }, TODAY)+ ).toBeNull();+ expect(+ getDueUrgency({ dueDate: "2026-10-05", deadlineType: "ASAP" }, TODAY)+ ).toBeNull();+ expect(+ getDueUrgency(+ { hasConflict: true, dueDate: "2026-09-21", deadlineType: "ASAP" },+ TODAY+ )+ ).toBe("late");+ });++ it("crosses a month boundary", () => {+ expect(getDueUrgency({ dueDate: "2026-11-01" }, "2026-10-31")).toBe(+ "dueSoon"+ );+ });+});++describe("getBatchDueUrgency", () => {+ it("takes the most urgent member", () => {+ expect(+ getBatchDueUrgency(+ [{ dueDate: "2026-12-01" }, { dueDate: "2026-10-06" }],+ TODAY+ )+ ).toBe("dueSoon");+ expect(+ getBatchDueUrgency(+ [{ dueDate: "2026-10-06" }, { hasConflict: true }],+ TODAY+ )+ ).toBe("late");+ expect(+ getBatchDueUrgency(+ [{ dueDate: "2026-10-06" }, { dueDate: "2026-09-21" }],+ TODAY+ )+ ).toBe("late");+ expect(getBatchDueUrgency([{ dueDate: "2026-12-01" }], TODAY)).toBeNull();+ });+});diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/dueUrgency.ts b/apps/erp/app/modules/production/ui/Schedule/Kanban/dueUrgency.tsnew file mode 100644index 0000000000..67c3d748af--- /dev/null+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/dueUrgency.ts@@ -0,0 +1,62 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { parseDate } from "@internationalized/date";++export type DueUrgency = "late" | "dueSoon";++type UrgencyInput = {+ hasConflict?: boolean | null;+ dueDate?: string | null; // YYYY-MM-DD+ deadlineType?: string | null;+ status?: string | null;+};++const FINISHED_STATUSES = new Set(["Done", "Canceled", "Cancelled"]);++/**+ * How urgent a schedule card is. `late` = already past its due date, or the+ * scheduler projects it to finish after its job's due date; `dueSoon` = due+ * today or tomorrow. `today` is the location's `YYYY-MM-DD` — date-only+ * strings compare as strings.+ */+export function getDueUrgency(+ item: UrgencyInput,+ today: string+): DueUrgency | null {+ if (item.hasConflict) return "late";+ if (FINISHED_STATUSES.has(item.status ?? "")) return null;+ // Only Hard and Soft Deadline carry a due date; an ASAP job can still hold a+ // stale one (deadlineRequiresDueDate in production.models).+ if (+ !item.dueDate ||+ item.deadlineType === "ASAP" ||+ item.deadlineType === "No Deadline"+ )+ return null;+ if (item.dueDate < today) return "late";+ const tomorrow = parseDate(today).add({ days: 1 }).toString();+ return item.dueDate <= tomorrow ? "dueSoon" : null;+}++/** A batch runs as one: it is as urgent as its most urgent member. */+export function getBatchDueUrgency(+ members: UrgencyInput[],+ today: string+): DueUrgency | null {+ let result: DueUrgency | null = null;+ for (const member of members) {+ const urgency = getDueUrgency(member, today);+ if (urgency === "late") return "late";+ if (urgency) result = urgency;+ }+ return result;+}++// Last in `cn(...)` so it wins over the status variant's border colour, and+// solid in dark mode, where the card shell drops the border.+export const DUE_URGENCY_BORDER: Record<DueUrgency, string> = {+ late: "border-2 border-red-500 dark:border-solid",+ dueSoon: "border-2 border-orange-500 dark:border-solid"+};diff --git a/apps/erp/app/modules/shared/shared.models.test.ts b/apps/erp/app/modules/shared/shared.models.test.tsindex d1cbcd9d03..4411d954c8 100644--- a/apps/erp/app/modules/shared/shared.models.test.ts+++ b/apps/erp/app/modules/shared/shared.models.test.ts@@ -3,7 +3,11 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { describe, expect, it } from "vitest";-import { optionalTiptapDoc, toTiptapDoc } from "./shared.models";+import {+ normalizeOperationSourceIds,+ optionalTiptapDoc,+ toTiptapDoc+} from "./shared.models";// Rich-text columns are `json` and must hold a tiptap document OBJECT. A JSON// string scalar stored there later breaks every Kysely copy of the row@@ -80,3 +84,41 @@ describe("optionalTiptapDoc", () => {expect(optionalTiptapDoc.safeParse(null).success).toBe(false);});});++// Outside Processing is done at the supplier, so it has no work center. The+// form hides the field for that type and an update leaves an omitted column as+// it was, so a work center set while the operation was in-house survived the+// switch — and put the subcontracted operation on the MES Work Centers board.+describe("normalizeOperationSourceIds", () => {+ it("clears the work center of an Outside Processing operation", () => {+ expect(+ normalizeOperationSourceIds({+ operationType: "Outside Processing",+ workCenterId: "wc1"+ }).workCenterId+ ).toBeNull();+ });++ it("clears it even when the form omitted the field", () => {+ const normalized = normalizeOperationSourceIds<{+ operationType?: string;+ workCenterId?: string | null;+ }>({ operationType: "Outside Processing" });+ expect(normalized).toHaveProperty("workCenterId", null);+ });++ it("keeps the work center of an in-house operation", () => {+ expect(+ normalizeOperationSourceIds({+ operationType: "Process",+ workCenterId: "wc1"+ }).workCenterId+ ).toBe("wc1");+ });++ it("does not add a work center to an in-house operation that omitted it", () => {+ expect(+ normalizeOperationSourceIds({ operationType: "Process" })+ ).not.toHaveProperty("workCenterId");+ });+});diff --git a/apps/erp/app/modules/shared/shared.models.ts b/apps/erp/app/modules/shared/shared.models.tsindex 83e3e51358..79f7318643 100644--- a/apps/erp/app/modules/shared/shared.models.ts+++ b/apps/erp/app/modules/shared/shared.models.ts@@ -147,16 +147,23 @@ export type OperationType = (typeof operationTypes)[number];// inspectionDocumentId. Writes go through this so a stale pointer can't survive// a type change (sanitize() only nullifies present-undefined keys — it never// clears an omitted field). See .ai/specs/2026-07-21-operation-instruction-sources.md.+// The same holds for the work center: Outside Processing runs at the supplier,+// and a work center left over from an in-house type put the operation on the+// MES Work Centers board.export function normalizeOperationSourceIds<T extends {operationType?: string;procedureId?: string | null;assemblyInstructionId?: string | null;inspectionDocumentId?: string | null;+ workCenterId?: string | null;}>(operation: T): T {return {...operation,+ ...(operation.operationType === "Outside Processing"+ ? { workCenterId: null }+ : {}),procedureId:operation.operationType === "Process"? operation.procedureId || nulldiff --git a/apps/mes/app/components/AssemblyView.tsx b/apps/mes/app/components/AssemblyView.tsxindex 3bbd08f42b..d12be51c01 100644--- a/apps/mes/app/components/AssemblyView.tsx+++ b/apps/mes/app/components/AssemblyView.tsx@@ -2678,7 +2678,7 @@ export function AssemblyView({/><ActionSheetButtonicon={<LuCheck className="size-4 shrink-0" />}- label="Finish"+ label="Mark as Done"onClick={() => {actionsSheet.onClose();finishModal.onOpen();diff --git a/apps/mes/app/components/Inspection/InspectionView.tsx b/apps/mes/app/components/Inspection/InspectionView.tsxindex bc8e2e7b85..0f1953920e 100644--- a/apps/mes/app/components/Inspection/InspectionView.tsx+++ b/apps/mes/app/components/Inspection/InspectionView.tsx@@ -1025,7 +1025,7 @@ export function InspectionView({/><ActionSheetButtonicon={<LuCheck className="size-4 shrink-0" />}- label={t`Finish`}+ label={t`Mark as Done`}onClick={() => {actionsSheet.onClose();finishModal.onOpen();diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsxindex 007123749d..d7c3738d5b 100644--- a/apps/mes/app/components/JobOperation/JobOperation.tsx+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx@@ -72,7 +72,7 @@ import {import { ModelPreview } from "@carbon/viewer/model-preview";import { OptimizeProgress } from "@carbon/viewer/optimize-progress";import { useOptimizedModel } from "@carbon/viewer/use-optimized-model";-import { parseDate } from "@internationalized/date";+import { getLocalTimeZone, parseDate, today } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";import type { PostgrestSingleResponse } from "@supabase/supabase-js";import { Suspense, useCallback, useEffect, useMemo, useState } from "react";@@ -97,6 +97,7 @@ import {LuPackageCheck,LuPrinter,LuQrCode,+ LuSquareChartGantt,LuSquareUser,LuTimer,LuTriangleAlert,@@ -344,19 +345,19 @@ export const JobOperation = ({(m) =>m.job as {deadlineType?: string | null;+ dueDate?: string | null;customer?: { name?: string | null } | null;} | null);const unique = (values: (string | null | undefined)[]) => [...new Set(values.filter((v): v is string => !!v))];- const dueDates = members+ const dueDates = jobs.filter(- (m, i) =>- m.dueDate &&- !["ASAP", "No Deadline"].includes(jobs[i]?.deadlineType ?? "")+ (j) =>+ j?.dueDate && !["ASAP", "No Deadline"].includes(j.deadlineType ?? ""))- .map((m) => m.dueDate as string)+ .map((j) => (j?.dueDate as string).slice(0, 10)).sort();return {customers: unique(jobs.map((j) => j?.customer?.name)),@@ -371,9 +372,9 @@ export const JobOperation = ({: "No Deadline"};}, [batch]);- // Same instant comparison the job's own deadline uses (useOperation).+ // Same day comparison the job's own deadline uses (useOperation).const batchOverdue = batchFacts?.dueDate- ? new Date(batchFacts.dueDate) < new Date()+ ? parseDate(batchFacts.dueDate).compare(today(getLocalTimeZone())) < 0: false;const batchCompleteModal = useDisclosure();// The completion fetcher lives HERE, not in BatchCompleteModal: a successful@@ -963,7 +964,18 @@ export const JobOperation = ({)}{scope === "job" && (<DropdownMenuItem asChild>- <Link to={path.to.jobDetail(operation.jobId)}>+ <Link+ to={+ // A subassembly's operation opens its own make method,+ // not the job header.+ operation.parentMaterialId+ ? path.to.jobMakeMethodDetail(+ operation.jobId,+ operation.jobMakeMethodId+ )+ : path.to.jobDetail(operation.jobId)+ }+ ><DropdownMenuIcon icon={<LuCirclePlay />} /><Trans>Job Details</Trans></Link>@@ -1111,11 +1123,9 @@ export const JobOperation = ({>{["ASAP", "No Deadline"].includes(operation.jobDeadlineType)? operation.jobDeadlineType- : operation.operationDueDate+ : operation.jobDueDate? t`Due ${formatRelativeTime(- convertDateStringToIsoString(- operation.operationDueDate- )+ convertDateStringToIsoString(operation.jobDueDate))}`: "–"}</span>@@ -1313,30 +1323,38 @@ export const JobOperation = ({operation.jobDeadlineType)? operation.jobDeadlineType- : operation.operationDueDate+ : operation.jobDueDate? t`Due ${formatRelativeTime(convertDateStringToIsoString(- operation.operationDueDate+ operation.jobDueDate))}`: "–"}</Heading><span className="text-muted-foreground text-sm">- {operation.operationDueDate ? (+ {operation.jobDueDate ? (<DateTime- value={operation.operationDueDate}+ value={operation.jobDueDate}variant="date"/>) : null}</span>+ {operation.operationDueDate &&+ operation.operationDueDate.slice(0, 10) !==+ operation.jobDueDate?.slice(0, 10) && (+ <span className="text-muted-foreground text-sm">+ {t`Operation needed by ${formatDate(+ operation.operationDueDate+ )}`}+ </span>+ )}{projectedCompletionDate &&(isBehindTarget ? (<Tooltip><TooltipTrigger asChild>- <Badge variant="red">- {t`Proj. ${formatDate(- projectedCompletionDate- )}`}+ <Badge variant="red" className="gap-1">+ <LuSquareChartGantt className="size-3.5 shrink-0" />+ {formatDate(projectedCompletionDate)}</Badge></TooltipTrigger><TooltipContent>@@ -1344,8 +1362,9 @@ export const JobOperation = ({</TooltipContent></Tooltip>) : (- <span className="text-sm text-muted-foreground">- {t`Proj. ${formatDate(projectedCompletionDate)}`}+ <span className="inline-flex items-center gap-1 text-sm text-muted-foreground">+ <LuSquareChartGantt className="size-3.5 shrink-0" />+ {formatDate(projectedCompletionDate)}</span>))}</VStack>@@ -3200,7 +3219,7 @@ export const JobOperation = ({><LuCheck className="size-4 shrink-0 stroke-muted-foreground" /><span className="text-base/6 font-medium">- <Trans>Finish</Trans>+ <Trans>Mark as Done</Trans></span></button></>diff --git a/apps/mes/app/components/JobOperation/components/BatchOverview.tsx b/apps/mes/app/components/JobOperation/components/BatchOverview.tsxindex a6764d9257..cbb6d9a089 100644--- a/apps/mes/app/components/JobOperation/components/BatchOverview.tsx+++ b/apps/mes/app/components/JobOperation/components/BatchOverview.tsx@@ -500,6 +500,7 @@ export function BatchOverview({{members.map((m) => {const job = m.job as {deadlineType?: string | null;+ dueDate?: string | null;customer?: { name?: string | null } | null;} | null;const toRun = remaining(m);@@ -546,9 +547,9 @@ export function BatchOverview({>{["ASAP", "No Deadline"].includes(job?.deadlineType ?? ""- ) || !m.dueDate+ ) || !job?.dueDate? (job?.deadlineType ?? "—")- : formatDate(m.dueDate)}+ : formatDate(job.dueDate)}</Td>{showLots && (<Tddiff --git a/apps/mes/app/components/JobOperation/components/QuantityModal.tsx b/apps/mes/app/components/JobOperation/components/QuantityModal.tsxindex b9cbe87894..0a270fe28c 100644--- a/apps/mes/app/components/JobOperation/components/QuantityModal.tsx+++ b/apps/mes/app/components/JobOperation/components/QuantityModal.tsx@@ -105,7 +105,7 @@ export function QuantityModal({scrap: t`Log scrap for ${operation.itemReadableId}`,rework: t`Log rework for ${operation.itemReadableId}`,complete: t`Log completed for ${operation.itemReadableId}`,- finish: t`Finish ${operation.itemReadableId}`+ finish: t`Mark ${operation.itemReadableId} as Done`};// operationQuantity is Math.ceil'd upstream (recalculate/get-method), so a 1.5-unit@@ -119,7 +119,7 @@ export function QuantityModal({scrap: t`Select a scrap quantity and reason`,rework: t`Select a rework quantity`,complete: t`Select a completion quantity`,- finish: t`Are you sure you want to finish this operation? This will end all active production events for this operation.`+ finish: t`Are you sure you want to mark this operation as done? This will end all active production events for this operation.`};const actionMap = {@@ -133,7 +133,7 @@ export function QuantityModal({scrap: t`Log Scrap`,rework: t`Log Rework`,complete: t`Log Completed`,- finish: isOperationComplete ? t`Finish` : t`Finish Anyways`+ finish: isOperationComplete ? t`Mark as Done` : t`Mark as Done Anyways`};const validatorMap = {diff --git a/apps/mes/app/components/JobOperation/hooks/useOperation.tsx b/apps/mes/app/components/JobOperation/hooks/useOperation.tsxindex 02ac154234..709fbdbf94 100644--- a/apps/mes/app/components/JobOperation/hooks/useOperation.tsx+++ b/apps/mes/app/components/JobOperation/hooks/useOperation.tsx@@ -9,6 +9,8 @@ import {getLocalTimeZone,now,parseAbsolute,+ parseDate,+ today,toZoned} from "@internationalized/date";import { useCallback, useEffect, useMemo, useRef, useState } from "react";@@ -347,8 +349,12 @@ export function useOperation({finishModal,issueModal,serialModal,- isOverdue: operation.operationDueDate- ? new Date(operation.operationDueDate) < new Date()+ // The JOB's deadline. The operation's own `operationDueDate` is the+ // scheduler's need-by target for this step, shown separately.+ isOverdue: operation.jobDueDate+ ? parseDate(operation.jobDueDate.slice(0, 10)).compare(+ today(getLocalTimeZone())+ ) < 0: false,selectedMaterial,setSelectedMaterial,diff --git a/apps/mes/app/components/Kanban/components/ItemCard.tsx b/apps/mes/app/components/Kanban/components/ItemCard.tsxindex 1051b20342..288ad59d13 100644--- a/apps/mes/app/components/Kanban/components/ItemCard.tsx+++ b/apps/mes/app/components/Kanban/components/ItemCard.tsx@@ -21,6 +21,7 @@ import {convertDateStringToIsoString,formatDurationMilliseconds} from "@carbon/utils";+import { getLocalTimeZone, today } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";import { cva } from "class-variance-authority";import {@@ -41,6 +42,7 @@ import EmployeeAvatar from "~/components/EmployeeAvatar";import { DeadlineIcon } from "~/components/Icons";import { useDateFormatter } from "~/hooks";import { getPrivateUrl, path } from "~/utils/path";+import { DUE_URGENCY_BORDER, getDueUrgency } from "../dueUrgency";import type { DisplaySettings, Item } from "../types";interface Progress {@@ -91,16 +93,22 @@ export function ItemCard({const { formatRelativeTime } = useDateFormatter();const routeData = useRouteData<{customers: { id: string; name: string }[];+ today: string | null;}>("/x/operations");+ // The factory's calendar day from the loader (location time zone); the+ // device's own day only when there is no location.+ const scheduleToday =+ routeData?.today ?? today(getLocalTimeZone()).toString();const customer = showCustomer? routeData?.customers.find((c) => c.id === item.customerId): undefined;const isOverdue =- item.deadlineType !== "No Deadline" && item.dueDate- ? new Date(item.dueDate) < new Date()- : false;+ item.deadlineType !== "ASAP" &&+ item.deadlineType !== "No Deadline" &&+ !!item.dueDate &&+ item.dueDate < scheduleToday;const progress = progressByItemId?.[item.id]?.progress ?? item.progress ?? 0;const status = progressByItemId?.[item.id]?.active@@ -111,6 +119,7 @@ export function ItemCard({: undefined;const isBatch = (item.batchSize ?? 0) > 1 && !!item.batchId;+ const urgency = getDueUrgency({ ...item, status }, scheduleToday);return (<Link@@ -119,10 +128,10 @@ export function ItemCard({<CardclassName={cn("max-w-[330px]",- item.hasConflict && "border-red-500 border-2",cardVariants({status: status- })+ }),+ urgency && DUE_URGENCY_BORDER[urgency])}><CardHeader className="flex flex-col justify-between relative gap-2">@@ -145,7 +154,7 @@ export function ItemCard({<TooltipTrigger><LuTriangleAlert className="h-4 w-4 text-red-500 flex-shrink-0" /></TooltipTrigger>- <TooltipContent>+ <TooltipContent className="whitespace-pre-line">{item.conflictReason ?? t`Scheduling conflict`}</TooltipContent></Tooltip>diff --git a/apps/mes/app/components/Kanban/dueUrgency.ts b/apps/mes/app/components/Kanban/dueUrgency.tsnew file mode 100644index 0000000000..67c3d748af--- /dev/null+++ b/apps/mes/app/components/Kanban/dueUrgency.ts@@ -0,0 +1,62 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { parseDate } from "@internationalized/date";++export type DueUrgency = "late" | "dueSoon";++type UrgencyInput = {+ hasConflict?: boolean | null;+ dueDate?: string | null; // YYYY-MM-DD+ deadlineType?: string | null;+ status?: string | null;+};++const FINISHED_STATUSES = new Set(["Done", "Canceled", "Cancelled"]);++/**+ * How urgent a schedule card is. `late` = already past its due date, or the+ * scheduler projects it to finish after its job's due date; `dueSoon` = due+ * today or tomorrow. `today` is the location's `YYYY-MM-DD` — date-only+ * strings compare as strings.+ */+export function getDueUrgency(+ item: UrgencyInput,+ today: string+): DueUrgency | null {+ if (item.hasConflict) return "late";+ if (FINISHED_STATUSES.has(item.status ?? "")) return null;+ // Only Hard and Soft Deadline carry a due date; an ASAP job can still hold a+ // stale one (deadlineRequiresDueDate in production.models).+ if (+ !item.dueDate ||+ item.deadlineType === "ASAP" ||+ item.deadlineType === "No Deadline"+ )+ return null;+ if (item.dueDate < today) return "late";+ const tomorrow = parseDate(today).add({ days: 1 }).toString();+ return item.dueDate <= tomorrow ? "dueSoon" : null;+}++/** A batch runs as one: it is as urgent as its most urgent member. */+export function getBatchDueUrgency(+ members: UrgencyInput[],+ today: string+): DueUrgency | null {+ let result: DueUrgency | null = null;+ for (const member of members) {+ const urgency = getDueUrgency(member, today);+ if (urgency === "late") return "late";+ if (urgency) result = urgency;+ }+ return result;+}++// Last in `cn(...)` so it wins over the status variant's border colour, and+// solid in dark mode, where the card shell drops the border.+export const DUE_URGENCY_BORDER: Record<DueUrgency, string> = {+ late: "border-2 border-red-500 dark:border-solid",+ dueSoon: "border-2 border-orange-500 dark:border-solid"+};diff --git a/apps/mes/app/routes/x+/event.tsx b/apps/mes/app/routes/x+/event.tsxindex e1cbb02eec..e30115e4d6 100644--- a/apps/mes/app/routes/x+/event.tsx+++ b/apps/mes/app/routes/x+/event.tsx@@ -18,6 +18,7 @@ import {getOperationEligibility,startProductionEvent} from "~/services/operations.service";+import { OUTSIDE_PROCESSING_REFUSAL } from "~/utils/operationView";export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);@@ -46,6 +47,19 @@ export async function action({ request }: ActionFunctionArgs) {// qualification check must run on this path (not only in the// start.$operationId loader)const serviceRole = await getCarbonServiceRole();+ const operation = await serviceRole+ .from("jobOperation")+ .select("operationType")+ .eq("id", d.jobOperationId)+ .eq("companyId", companyId)+ .maybeSingle();+ if (operation.data?.operationType === "Outside Processing") {+ return data(+ {},+ await flash(request, error(null, OUTSIDE_PROCESSING_REFUSAL))+ );+ }+const eligibility = await getOperationEligibility(serviceRole, {operationId: d.jobOperationId,employeeId: userId,diff --git a/apps/mes/app/routes/x+/operation.$operationId.tsx b/apps/mes/app/routes/x+/operation.$operationId.tsxindex 21f50aff29..f641a32524 100644--- a/apps/mes/app/routes/x+/operation.$operationId.tsx+++ b/apps/mes/app/routes/x+/operation.$operationId.tsx@@ -42,7 +42,10 @@ type ExpiredEntityPolicy = "Warn" | "Block" | "BlockWithOverride";import { redirect } from "@carbon/utils";import { makeDurations } from "~/utils/durations";import type { Handle } from "~/utils/handle";-import { resolveOperationView } from "~/utils/operationView";+import {+ OUTSIDE_PROCESSING_REFUSAL,+ resolveOperationView+} from "~/utils/operationView";import { path } from "~/utils/path";export const handle: Handle = {@@ -159,6 +162,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const op = operation.data?.[0];+ // Subcontracted work runs at the supplier, never on the shop floor. The+ // boards hide it; this refuses a job-view or direct link too.+ if (op?.operationType === "Outside Processing") {+ throw redirect(+ path.to.operations,+ await flash(request, error(null, OUTSIDE_PROCESSING_REFUSAL))+ );+ }+// Redirect guard (ADR-0005): each view has its own route. Guards only// redirect kinds they don't serve, so no loop.if (resolveOperationView(op?.operationType) === "assembly") {diff --git a/apps/mes/app/routes/x+/operations.tsx b/apps/mes/app/routes/x+/operations.tsxindex 0086af7701..8cc0d0e548 100644--- a/apps/mes/app/routes/x+/operations.tsx+++ b/apps/mes/app/routes/x+/operations.tsx@@ -121,8 +121,33 @@ function collapseBatches(}for (const [batchId, members] of byBatch) {const total = batchTotals.get(batchId);+ // The batch runs as one, so any member projected late makes the run late.+ const conflicted = members.filter((m) => m.hasConflict);+ // The earliest dated member deadline is the batch's binding constraint.+ // Only Hard and Soft Deadline carry a due date; an ASAP job can still hold+ // a stale one.+ const earliest = members.reduce<Item | undefined>((acc, m) => {+ if (+ !m.dueDate ||+ m.deadlineType === "ASAP" ||+ m.deadlineType === "No Deadline"+ )+ return acc;+ if (!acc?.dueDate || m.dueDate < acc.dueDate) return m;+ return acc;+ }, undefined);result.push({...members[0],+ dueDate: earliest?.dueDate ?? members[0].dueDate,+ deadlineType: earliest?.deadlineType ?? members[0].deadlineType,+ hasConflict: conflicted.length > 0 || undefined,+ conflictReason: conflicted.length+ ? conflicted+ .map((m) =>+ m.conflictReason ? `${m.title}: ${m.conflictReason}` : m.title+ )+ .join("\n")+ : undefined,batchSize: total?.size ?? members.length,batchJobReadableIds:total?.jobReadableIds ?? members.map((m) => m.title).filter(Boolean),@@ -228,12 +253,16 @@ export async function loader({ context, request }: LoaderFunctionArgs) {// assignment for today and no explicit work-center filter (and hasn't// dismissed the default this session), open on their station.const effectiveUserId = context.get(userContext)?.effectiveUserId;+ // The factory's calendar day: card urgency and the people assignment both+ // read it, never the operator device's day.+ const today = locationId+ ? datetime+ .today(await getLocationTimeZone(serviceRole, locationId, companyId))+ .toString()+ : null;let peopleStation: { workCenterId: string; name: string } | null = null;let peopleDate: string | null = null;- if (selectedWorkCenterIds.length === 0 && effectiveUserId && locationId) {- const today = datetime- .today(await getLocationTimeZone(serviceRole, locationId, companyId))- .toString();+ if (selectedWorkCenterIds.length === 0 && effectiveUserId && today) {peopleDate = today;const dismissed = await getPeopleOverride(request);if (dismissed !== today) {@@ -363,6 +392,7 @@ export async function loader({ context, request }: LoaderFunctionArgs) {{peopleStation,peopleDate,+ today,columns: filteredWorkCenters.map((wc: any) => ({id: wc.id!,@@ -387,7 +417,9 @@ export async function loader({ context, request }: LoaderFunctionArgs) {title: op.jobReadableId,subtitle: op.itemReadableId,description: op.description,- dueDate: op.operationDueDate,+ // The JOB's due date, as on the operation view: the op's need-by+ // target labelled "Due" read as the job being due weeks early.+ dueDate: op.jobDueDate ?? undefined,duration:operation.setupDuration +Math.max(operation.laborDuration, operation.machineDuration),diff --git a/apps/mes/app/routes/x+/start.$operationId.tsx b/apps/mes/app/routes/x+/start.$operationId.tsxindex 608a58163c..00c5b74117 100644--- a/apps/mes/app/routes/x+/start.$operationId.tsx+++ b/apps/mes/app/routes/x+/start.$operationId.tsx@@ -19,6 +19,7 @@ import {getTrackedEntitiesByMakeMethodId,startProductionEvent} from "~/services/operations.service";+import { OUTSIDE_PROCESSING_REFUSAL } from "~/utils/operationView";import { path } from "~/utils/path";const logger = getLogger("mes", "start-operation");@@ -72,6 +73,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}+ // Subcontracted work runs at the supplier and is never startable here. Like+ // the floor rule below, this must run BEFORE the timer re-open.+ if (jobOperation.data.operationType === "Outside Processing") {+ throw redirect(+ path.to.operations,+ await flash(request, error(null, OUTSIDE_PROCESSING_REFUSAL))+ );+ }+// Floor rule: an operation is startable iff it is floor-visible — a batched// op needs its batch released (not Planned); an unbatched op needs its job// released (Ready/In Progress/Paused). These guards must run BEFORE thediff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex 4d704098f0..b809f3a328 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -128,7 +128,7 @@ export async function getJobOperationBatch(const operations = await client.from("jobOperation").select(- "id, description, operationQuantity, quantityComplete, quantityScrapped, setupTime, setupUnit, laborTime, laborUnit, machineTime, machineUnit, dueDate, jobMakeMethodId, jobMakeMethod(requiresBatchTracking, itemId, item(readableIdWithRevision, name, thumbnailPath, type)), job(jobId, status, deadlineType, customer(name))"+ "id, description, operationQuantity, quantityComplete, quantityScrapped, setupTime, setupUnit, laborTime, laborUnit, machineTime, machineUnit, jobMakeMethodId, jobMakeMethod(requiresBatchTracking, itemId, item(readableIdWithRevision, name, thumbnailPath, type)), job(jobId, status, deadlineType, dueDate, customer(name))").eq("jobOperationBatchId", batchId).eq("companyId", companyId)diff --git a/apps/mes/app/utils/operationView.ts b/apps/mes/app/utils/operationView.tsindex cd55843cb6..b01b96aa95 100644--- a/apps/mes/app/utils/operationView.ts+++ b/apps/mes/app/utils/operationView.ts@@ -22,9 +22,10 @@ export type OperationView = "operation" | "assembly" | "inspection";/*** Resolve the view for an operation type. Anything unrecognized — including- * `null`/`undefined`, the default `Process`, and `Outside Processing` (subcontracted- * work has no execution view of its own) — falls back to the Operation view, so the- * route is always safe to open (ADR-0001).+ * `null`/`undefined` and the default `Process` — falls back to the Operation view, so+ * the route is always safe to open (ADR-0001). `Outside Processing` maps there too,+ * but subcontracted work runs at the supplier: the operation and start routes refuse+ * it before any view renders.*/export function resolveOperationView(type: OperationType | null | undefined@@ -38,3 +39,11 @@ export function resolveOperationView(return "operation";}}++/**+ * Subcontracted work runs at the supplier, never on the shop floor. The boards+ * hide it (get_active_job_operations_by_location); the operation view, the start+ * route and the production-event Start action refuse it with this message.+ */+export const OUTSIDE_PROCESSING_REFUSAL =+ "Outside processing is done by the supplier and can't be run on the shop floor";diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.tsindex 58172d1074..e3bfac2ad3 100644--- a/apps/mes/app/utils/path.ts+++ b/apps/mes/app/utils/path.ts@@ -163,6 +163,8 @@ export const path = {`${getAppUrl()}${x}/${type.toLowerCase()}/${itemId}/details`,jobDag: (id: string) => generatePath(`${x}/job/${id}`),jobDetail: (id: string) => `${getAppUrl()}${x}/job/${id}/details`,+ jobMakeMethodDetail: (jobId: string, makeMethodId: string) =>+ `${getAppUrl()}${x}/job/${jobId}/make/${makeMethodId}`,jobs: `${x}/jobs`,kanbanComplete: (id: string) => `${ERP_URL}/api/kanban/complete/${id}`,location: `${x}/location`,diff --git a/packages/database/supabase/migrations/20261006021134_mes-hide-outside-processing.sql b/packages/database/supabase/migrations/20261006021134_mes-hide-outside-processing.sqlnew file mode 100644index 0000000000..fa7685360b--- /dev/null+++ b/packages/database/supabase/migrations/20261006021134_mes-hide-outside-processing.sql@@ -0,0 +1,163 @@+-- Keep Outside Processing operations off the MES Work Centers board.+--+-- The board (get_active_job_operations_by_location) had no operationType filter;+-- subcontracted operations stayed off it only because they usually have no work+-- center, and the board's columns are work centers. An Outside Processing+-- operation that carries a work center — e.g. a stale one left behind when an+-- operation is switched to Outside Processing, since the form hides the field+-- and the update leaves the column as it was — landed in that work center's+-- column for an operator to start.+--+-- Subcontract behaviour keys on operationType = 'Outside Processing' (see+-- 20260721004140_operation-type-consolidation.sql). The body below is the+-- 20260905132037_job-operation-batching.sql definition plus that one predicate.++CREATE OR REPLACE FUNCTION get_active_job_operations_by_location(+ location_id TEXT,+ work_center_ids TEXT[]+)+RETURNS TABLE (+ "id" TEXT,+ "jobId" TEXT,+ "jobMakeMethodId" TEXT,+ "operationOrder" DOUBLE PRECISION,+ "priority" DOUBLE PRECISION,+ "processId" TEXT,+ "workCenterId" TEXT,+ "description" TEXT,+ "setupTime" NUMERIC,+ "setupUnit" factor,+ "laborTime" NUMERIC,+ "laborUnit" factor,+ "machineTime" NUMERIC,+ "machineUnit" factor,+ "operationOrderType" "methodOperationOrder",+ "jobReadableId" TEXT,+ "jobStatus" "jobStatus",+ "jobDueDate" DATE,+ "jobDeadlineType" "deadlineType",+ "jobCustomerId" TEXT,+ "customerName" TEXT,+ "parentMaterialId" TEXT,+ "itemReadableId" TEXT,+ "itemDescription" TEXT,+ "operationStatus" "jobOperationStatus",+ "targetQuantity" NUMERIC,+ "operationQuantity" NUMERIC,+ "quantityComplete" NUMERIC,+ "quantityReworked" NUMERIC,+ "quantityScrapped" NUMERIC,+ "salesOrderId" TEXT,+ "salesOrderLineId" TEXT,+ "salesOrderReadableId" TEXT,+ "assignee" TEXT,+ "tags" TEXT[],+ "thumbnailPath" TEXT,+ "operationDueDate" DATE,+ "reworkId" TEXT,+ "hasConflict" BOOLEAN,+ "conflictReason" TEXT,+ "projectedCompletionAt" TIMESTAMP WITH TIME ZONE,+ "processBatchable" BOOLEAN,+ "jobOperationBatchId" TEXT,+ "batchReadableId" TEXT+)+SECURITY INVOKER+AS $$+BEGIN+ RETURN QUERY+ WITH relevant_jobs AS (+ SELECT *+ FROM "job"+ WHERE "locationId" = location_id+ AND (+ ("status" = 'Ready' OR "status" = 'In Progress' OR "status" = 'Paused')+ -- A Released batch pulls its members' jobs onto the floor even when the+ -- job itself is not yet released; the op-level handoff filter below+ -- keeps such a job's NON-batched operations hidden.+ OR "job"."id" IN (+ SELECT jo2."jobId"+ FROM "jobOperation" jo2+ JOIN "jobOperationBatch" b2+ ON b2."id" = jo2."jobOperationBatchId"+ AND b2."companyId" = jo2."companyId"+ WHERE b2."status" IN ('Active', 'Completing')+ )+ )+ )+ SELECT+ jo."id",+ jo."jobId",+ jo."jobMakeMethodId",+ jo."order" AS "operationOrder",+ jo."priority",+ jo."processId",+ jo."workCenterId",+ jo."description",+ jo."setupTime",+ jo."setupUnit",+ jo."laborTime",+ jo."laborUnit",+ jo."machineTime",+ jo."machineUnit",+ jo."operationOrder" AS "operationOrderType",+ rj."jobId" AS "jobReadableId",+ rj."status" AS "jobStatus",+ rj."dueDate" AS "jobDueDate",+ rj."deadlineType" AS "jobDeadlineType",+ rj."customerId" AS "jobCustomerId",+ c."name" AS "customerName",+ jmm."parentMaterialId",+ i."readableId" as "itemReadableId",+ i."name" as "itemDescription",+ CASE+ WHEN rj."status" = 'Paused' THEN 'Paused'+ ELSE jo."status"+ END AS "operationStatus",+ jo."targetQuantity"::NUMERIC,+ jo."operationQuantity",+ jo."quantityComplete",+ jo."quantityReworked",+ jo."quantityScrapped",+ rj."salesOrderId",+ rj."salesOrderLineId",+ so."salesOrderId" as "salesOrderReadableId",+ jo."assignee",+ jo."tags",+ COALESCE(mu."thumbnailPath", i."thumbnailPath") as "thumbnailPath",+ jo."dueDate" AS "operationDueDate",+ jo."reworkId",+ COALESCE(jo."hasConflict", FALSE) AS "hasConflict",+ jo."conflictReason",+ jo."projectedCompletionAt",+ p."batchable" AS "processBatchable",+ jo."jobOperationBatchId",+ b."readableId" AS "batchReadableId"+ FROM "jobOperation" jo+ JOIN relevant_jobs rj ON rj.id = jo."jobId"+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm.id+ LEFT JOIN "item" i ON jmm."itemId" = i.id+ LEFT JOIN "customer" c ON rj."customerId" = c.id+ LEFT JOIN "salesOrder" so ON rj."salesOrderId" = so.id+ LEFT JOIN "modelUpload" mu ON i."modelUploadId" = mu.id+ LEFT JOIN "process" p ON p."id" = jo."processId"+ LEFT JOIN "jobOperationBatch" b+ ON b."id" = jo."jobOperationBatchId" AND b."companyId" = jo."companyId"+ WHERE (CASE+ WHEN array_length(work_center_ids, 1) > 0 THEN+ jo."workCenterId" = ANY(work_center_ids) AND jo."status" != 'Done' AND jo."status" != 'Canceled'+ ELSE jo."status" != 'Done' AND jo."status" != 'Canceled'+ END)+ -- Membership handoff: a batched op is governed by its BATCH's release+ -- state; an unbatched op by its JOB's (the pre-batching rule).+ AND (+ (jo."jobOperationBatchId" IS NOT NULL AND b."status" IN ('Active', 'Completing'))+ OR+ (jo."jobOperationBatchId" IS NULL AND rj."status" IN ('Ready', 'In Progress', 'Paused'))+ )+ -- Subcontracted work is done at the supplier, not on the shop floor.+ AND jo."operationType" <> 'Outside Processing'+ ORDER BY jo."startDate", jo."priority";++END;+$$ LANGUAGE plpgsql;diff --git a/packages/database/supabase/migrations/20261006021541_clear-outside-processing-work-centers.sql b/packages/database/supabase/migrations/20261006021541_clear-outside-processing-work-centers.sqlnew file mode 100644index 0000000000..214ff026b7--- /dev/null+++ b/packages/database/supabase/migrations/20261006021541_clear-outside-processing-work-centers.sql@@ -0,0 +1,31 @@+-- Clear work centers left on Outside Processing operations.+--+-- Outside Processing runs at the supplier, so it has no work center: the+-- operation forms hide the field for that type. But the field was simply+-- omitted from the update, so a work center set while the operation was+-- in-house survived the switch to Outside Processing. The writers now clear it+-- (normalizeOperationSourceIds); this removes the ones already stored.+--+-- Method and quote operations are templates: a stale value there is copied+-- onto every job made from them, so all are cleared. Job operations are cleared+-- only while open — a finished one keeps the row as it was run (its production+-- events carry their own workCenterId either way) — and only outside a batch:+-- a batch member's workCenterId mirrors its batch header (batch-operations+-- keeps the two equal), so clearing the member alone would split them.++UPDATE "methodOperation"+SET "workCenterId" = NULL+WHERE "operationType" = 'Outside Processing'+ AND "workCenterId" IS NOT NULL;++UPDATE "quoteOperation"+SET "workCenterId" = NULL+WHERE "operationType" = 'Outside Processing'+ AND "workCenterId" IS NOT NULL;++UPDATE "jobOperation"+SET "workCenterId" = NULL+WHERE "operationType" = 'Outside Processing'+ AND "workCenterId" IS NOT NULL+ AND "status" NOT IN ('Done', 'Canceled')+ AND "jobOperationBatchId" IS NULL;diff --git a/packages/database/supabase/migrations/20261006023219_batchable-operations-exclude-outside-processing.sql b/packages/database/supabase/migrations/20261006023219_batchable-operations-exclude-outside-processing.sqlnew file mode 100644index 0000000000..503954edd4--- /dev/null+++ b/packages/database/supabase/migrations/20261006023219_batchable-operations-exclude-outside-processing.sql@@ -0,0 +1,129 @@+-- Outside Processing operations can't be batched.+--+-- A batch is one run on one of our work centers; subcontracted work runs at+-- the supplier. get_batchable_operations had no operationType filter, so an+-- outside operation on a batchable process (plating is a typical one) was+-- offered as a candidate, and releasing its batch stamped the batch's work+-- center onto it — which put it on the work centers boards. The batch-operations+-- server function refuses one too (assertEligible); this keeps it out of the+-- builder's candidate list. Members of existing batches still list with their+-- batch.+--+-- The body is the 20260921163512_batchable-operations-item-and-method-materials.sql+-- definition plus that one predicate in the candidate branch.++CREATE OR REPLACE FUNCTION get_batchable_operations(location_id TEXT, process_id TEXT)+RETURNS TABLE (+ "id" TEXT,+ "jobId" TEXT,+ "jobReadableId" TEXT,+ "jobDueDate" DATE,+ "jobStatus" "jobStatus",+ "itemId" TEXT,+ "itemReadableId" TEXT,+ "itemDescription" TEXT,+ "requiresBatchTracking" BOOLEAN,+ "trackedEntityId" TEXT,+ "lotNumber" TEXT,+ "description" TEXT,+ "operationQuantity" NUMERIC,+ "status" "jobOperationStatus",+ "workCenterId" TEXT,+ "jobOperationBatchId" TEXT,+ "batchReadableId" TEXT,+ "batchStatus" "jobOperationBatchStatus",+ "batchWorkCenterId" TEXT,+ "companyId" TEXT,+ "materials" JSONB+)+SECURITY INVOKER+LANGUAGE sql+STABLE+AS $$+ SELECT+ jo."id",+ j."id" AS "jobId",+ j."jobId" AS "jobReadableId",+ j."dueDate" AS "jobDueDate",+ j."status" AS "jobStatus",+ i."id" AS "itemId",+ i."readableId" AS "itemReadableId",+ i."name" AS "itemDescription",+ COALESCE(jmm."requiresBatchTracking", false) AS "requiresBatchTracking",+ wip."id" AS "trackedEntityId",+ wip."readableId" AS "lotNumber",+ jo."description",+ jo."operationQuantity",+ jo."status",+ jo."workCenterId",+ jo."jobOperationBatchId",+ b."readableId" AS "batchReadableId",+ b."status" AS "batchStatus",+ b."workCenterId" AS "batchWorkCenterId",+ jo."companyId",+ COALESCE(mats."materials", '[]'::jsonb) AS "materials"+ FROM "jobOperation" jo+ JOIN "job" j ON j."id" = jo."jobId"+ LEFT JOIN "jobMakeMethod" jmm+ ON jmm."id" = jo."jobMakeMethodId" AND jmm."companyId" = jo."companyId"+ -- The operation's produced item = its make method's item; fall back to the+ -- job's item only when the operation has no make method. (from #1686)+ JOIN "item" i ON i."id" = COALESCE(jmm."itemId", j."itemId")+ LEFT JOIN LATERAL (+ SELECT te."id", te."readableId"+ FROM "trackedEntity" te+ WHERE te."attributes"->>'Job Make Method' = jo."jobMakeMethodId"+ AND te."companyId" = jo."companyId"+ AND te."status" NOT IN ('Consumed', 'Scrapped', 'Rejected')+ ORDER BY te."createdAt"+ LIMIT 1+ ) wip ON jmm."requiresBatchTracking"+ LEFT JOIN "jobOperationBatch" b+ ON b."id" = jo."jobOperationBatchId" AND b."companyId" = jo."companyId"+ LEFT JOIN LATERAL (+ SELECT jsonb_agg(jsonb_build_object(+ 'itemReadableId', mi."readableId",+ 'description', jm."description",+ 'quantity', jm."quantity",+ 'formId', m."materialFormId", 'formName', mf."name",+ 'substanceId', m."materialSubstanceId", 'substanceName', ms."name",+ 'gradeId', m."gradeId", 'gradeName', mg."name",+ 'dimensionId', m."dimensionId", 'dimensionName', md."name",+ 'finishId', m."finishId", 'finishName', mfin."name"+ )) AS "materials"+ FROM "jobMaterial" jm+ JOIN "item" mi ON mi."id" = jm."itemId"+ LEFT JOIN "material" m ON m."id" = mi."readableId" AND m."companyId" = mi."companyId"+ LEFT JOIN "materialForm" mf ON mf."id" = m."materialFormId"+ LEFT JOIN "materialSubstance" ms ON ms."id" = m."materialSubstanceId"+ LEFT JOIN "materialGrade" mg ON mg."id" = m."gradeId"+ LEFT JOIN "materialDimension" md ON md."id" = m."dimensionId"+ LEFT JOIN "materialFinish" mfin ON mfin."id" = m."finishId"+ WHERE jm."companyId" = jo."companyId"+ AND (+ -- The operation's make method (sub-assembly) — its whole BOM,+ -- regardless of which operation each line is pinned to. (from #1689)+ (jo."jobMakeMethodId" IS NOT NULL+ AND jm."jobMakeMethodId" = jo."jobMakeMethodId")+ -- Defensive fallback for an operation with no make method: the job's+ -- own unpinned BOM lines.+ OR (jo."jobMakeMethodId" IS NULL+ AND jm."jobId" = jo."jobId"+ AND jm."jobOperationId" IS NULL)+ )+ ) mats ON TRUE+ WHERE j."locationId" = location_id+ AND jo."processId" = process_id+ AND (+ (jo."jobOperationBatchId" IS NULL+ AND jo."status" IN ('Todo', 'Ready', 'Waiting')+ AND jo."operationType" <> 'Outside Processing'+ AND j."status" NOT IN ('Completed', 'Closed', 'Cancelled')+ AND NOT EXISTS (+ SELECT 1 FROM "productionEvent" pe+ WHERE pe."jobOperationId" = jo."id"+ AND pe."companyId" = jo."companyId"+ ))+ OR b."status" IN ('Planned', 'Active', 'Completing')+ );+$$;diff --git a/packages/database/supabase/tests/outside-processing-off-the-floor.test.sql b/packages/database/supabase/tests/outside-processing-off-the-floor.test.sqlnew file mode 100644index 0000000000..58d3787b37--- /dev/null+++ b/packages/database/supabase/tests/outside-processing-off-the-floor.test.sql@@ -0,0 +1,89 @@+-- Outside Processing runs at the supplier, never on the shop floor.+-- 1. The work centers board (get_active_job_operations_by_location — MES board,+-- ERP Priority board, API) never lists one, even one that carries a work+-- center. The board's columns are work centers, so an outside operation used+-- to stay off it only while its work center was null; a stale one (left over+-- from an in-house type) put it in that column for an operator to start.+-- 2. The batch builder (get_batchable_operations) never offers one: releasing a+-- batch stamps its work center onto every member.+-- Isolated fixture company; no existing business data is read or edited. Always rolls back.+-- Run: pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -f packages/database/supabase/tests/outside-processing-off-the-floor.test.sql+\set ON_ERROR_STOP on+BEGIN;+SET LOCAL statement_timeout = '60s';++CREATE FUNCTION pg_temp.add_operation(+ p_job_id text, p_company_id text, p_process_id text, p_work_center_id text,+ p_operation_type "operationType", p_order int+) RETURNS text LANGUAGE plpgsql AS $fn$+DECLARE v_operation text;+BEGIN+ INSERT INTO "jobOperation" ("jobId", "jobMakeMethodId", "processId", "workCenterId",+ "operationType", "operationQuantity", "targetQuantity", "order", status, "companyId", "createdBy")+ VALUES (p_job_id,+ (SELECT id FROM "jobMakeMethod" WHERE "jobId" = p_job_id AND "parentMaterialId" IS NULL),+ p_process_id, p_work_center_id, p_operation_type, 1, 1, p_order, 'Ready', p_company_id, 'system')+ RETURNING id INTO v_operation;+ RETURN v_operation;+END;+$fn$;++CREATE FUNCTION pg_temp.on_board(p_location_id text, p_operation_id text) RETURNS boolean+LANGUAGE sql AS $fn$+ SELECT EXISTS (+ SELECT 1 FROM get_active_job_operations_by_location(p_location_id, ARRAY[]::text[])+ WHERE id = p_operation_id+ );+$fn$;++DO $cases$+DECLARE+ v_group_id text; v_company_id text; v_location_id text; v_item text;+ v_process text; v_work_center text; v_job text; v_inside text; v_outside text;+BEGIN+ INSERT INTO "companyGroup" (name, "createdBy") VALUES ('Board outside processing test', 'system') RETURNING id INTO v_group_id;+ INSERT INTO company (name, "companyGroupId", "baseCurrencyCode", timezone)+ VALUES ('Board outside processing test', v_group_id, 'USD', 'UTC') RETURNING id INTO v_company_id;+ INSERT INTO location (name, "addressLine1", city, "postalCode", "companyId", "createdBy", timezone)+ VALUES ('Plant', '1 Test Way', 'Testville', '00000', v_company_id, 'system', 'UTC') RETURNING id INTO v_location_id;+ INSERT INTO "unitOfMeasure" (code, name, "companyId", "createdBy")+ VALUES ('EA', 'Each', v_company_id, 'system') ON CONFLICT DO NOTHING;+ INSERT INTO item ("readableId", name, type, "replenishmentSystem", "itemTrackingType", "unitOfMeasureCode", "companyId", "createdBy")+ VALUES ('T-BRACKET', 'Bracket', 'Part', 'Make', 'Inventory', 'EA', v_company_id, 'system') RETURNING id INTO v_item;+ INSERT INTO process (name, "processType", "defaultStandardFactor", "companyId", "createdBy")+ VALUES ('Plating', 'Process', 'Hours/Piece', v_company_id, 'system') RETURNING id INTO v_process;+ UPDATE process SET batchable = TRUE WHERE id = v_process;+ INSERT INTO "workCenter" (name, "locationId", "laborRate", "machineRate", "overheadRate", "defaultStandardFactor", "companyId", "createdBy")+ VALUES ('Plating line', v_location_id, 0, 0, 0, 'Hours/Piece', v_company_id, 'system') RETURNING id INTO v_work_center;++ INSERT INTO job ("jobId", "itemId", quantity, "locationId", "companyId", "createdBy", "unitOfMeasureCode")+ VALUES ('BOARD-1', v_item, 1, v_location_id, v_company_id, 'system', 'EA') RETURNING id INTO v_job;+ v_inside := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 'Process', 1);+ -- The stale shape: an outside operation still holding the work center it had in-house.+ v_outside := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 'Outside Processing', 2);+ UPDATE job SET status = 'Ready' WHERE id = v_job;++ ASSERT pg_temp.on_board(v_location_id, v_inside),+ 'An in-house operation with a work center on a released job must be on the board';+ ASSERT NOT pg_temp.on_board(v_location_id, v_outside),+ 'An Outside Processing operation must stay off the board even with a work center';++ -- Filtering the board to that work center must not bring it back either.+ ASSERT NOT EXISTS (+ SELECT 1 FROM get_active_job_operations_by_location(v_location_id, ARRAY[v_work_center])+ WHERE id = v_outside+ ), 'An Outside Processing operation must stay off a work-center-filtered board';++ -- The batch builder offers the in-house operation, never the outside one.+ ASSERT EXISTS (+ SELECT 1 FROM get_batchable_operations(v_location_id, v_process) WHERE id = v_inside+ ), 'An unstarted in-house operation on a batchable process must be a batch candidate';+ ASSERT NOT EXISTS (+ SELECT 1 FROM get_batchable_operations(v_location_id, v_process) WHERE id = v_outside+ ), 'An Outside Processing operation must never be a batch candidate';++ RAISE NOTICE 'ALL OUTSIDE-PROCESSING CASES PASSED (in-house listed, outside hidden, outside hidden under a work-center filter, outside never a batch candidate)';+END;+$cases$;++ROLLBACK;diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 31545a5199..5370f78010 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -13965,10 +13965,6 @@ msgstr "Gewinnprozent"msgid "Progress"msgstr "Fortschritt"-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Proj. {0}"-msgid "Project"msgstr "Projekt"@@ -13984,10 +13980,6 @@ msgstr "Projektplan"msgid "Project start"msgstr "Projektstart"-#. placeholder {0}: formatDate(projectedDate)-msgid "Projected {0}"-msgstr "Geplant {0}"-msgid "Projected completion"msgstr "Geplante Fertigstellung"diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.poindex fa9bc83f65..01cd3d283f 100644--- a/packages/locale/locales/de/mes.po+++ b/packages/locale/locales/de/mes.po@@ -188,12 +188,12 @@ msgstr "Möchten Sie diese Zeitkarte wirklich löschen? Dies kann nicht rückgämsgid "Are you sure you want to end all production events? This will end all active operations without completing or finishing them."msgstr "Möchten Sie wirklich alle Produktionsereignisse beenden? Dadurch werden alle aktiven Arbeitsgänge beendet, ohne sie abzuschließen."-msgid "Are you sure you want to finish this operation? This will end all active production events for this operation."-msgstr "Sind Sie sicher, dass Sie diesen Arbeitsgang beenden möchten? Dies beendet alle aktiven Produktionsereignisse für diesen Arbeitsgang."-msgid "Are you sure you want to leave this page?"msgstr "Möchten Sie diese Seite wirklich verlassen?"+msgid "Are you sure you want to mark this operation as done? This will end all active production events for this operation."+msgstr "Möchten Sie diesen Arbeitsgang wirklich als erledigt markieren? Dies beendet alle aktiven Produktionsereignisse für diesen Arbeitsgang."+msgid "Assembly steps"msgstr "Montageschritte"@@ -509,9 +509,9 @@ msgstr "Ziehen von {0} storniert."msgid "Due"msgstr "Fällig"-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.jobDueDate ) )#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )msgid "Due {0}"msgstr "Fällig {0}"@@ -658,13 +658,6 @@ msgstr "Nach Standort filtern"msgid "Finish"msgstr "Fertig"-#. placeholder {0}: operation.itemReadableId-msgid "Finish {0}"-msgstr "Beenden {0}"--msgid "Finish Anyways"-msgstr "Trotzdem beenden"-msgid "Finish setting up your account"msgstr "Beenden Sie die Einrichtung Ihres Kontos"@@ -904,6 +897,16 @@ msgstr "Artikel manuell zum Bestand hinzufügen"msgid "Manually remove items from inventory"msgstr "Artikel manuell aus dem Bestand entfernen"+#. placeholder {0}: operation.itemReadableId+msgid "Mark {0} as Done"+msgstr "{0} als erledigt markieren"++msgid "Mark as Done"+msgstr "Als erledigt markieren"++msgid "Mark as Done Anyways"+msgstr "Trotzdem als erledigt markieren"+msgid "Mark Short"msgstr "Als kurz markieren"@@ -1164,6 +1167,10 @@ msgstr "Offene Fertigungsaufträge"msgid "Open sub-assembly {0}: {1}"msgstr "Untergruppe {0} öffnen: {1}"+#. placeholder {0}: formatDate( operation.operationDueDate )+msgid "Operation needed by {0}"+msgstr "Arbeitsgang benötigt bis {0}"+msgid "Operations"msgstr "Arbeitsgänge"@@ -1312,11 +1319,6 @@ msgstr "Prozesse"msgid "Progress"msgstr "Fortschritt"-#. placeholder {0}: formatDate( projectedCompletionDate )-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Proj. {0}"-msgid "Quality Issue"msgstr "Qualitätsproblem"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 5b9062dbcd..1fbf5a1945 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -13965,10 +13965,6 @@ msgstr "Profit Percent"msgid "Progress"msgstr "Progress"-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Proj. {0}"-msgid "Project"msgstr "Project"@@ -13984,10 +13980,6 @@ msgstr "Project Plan"msgid "Project start"msgstr "Project start"-#. placeholder {0}: formatDate(projectedDate)-msgid "Projected {0}"-msgstr "Projected {0}"-msgid "Projected completion"msgstr "Projected completion"diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.poindex 2152f01434..2f32c4d330 100644--- a/packages/locale/locales/en/mes.po+++ b/packages/locale/locales/en/mes.po@@ -188,12 +188,12 @@ msgstr "Are you sure you want to delete this timecard? This cannot be undone."msgid "Are you sure you want to end all production events? This will end all active operations without completing or finishing them."msgstr "Are you sure you want to end all production events? This will end all active operations without completing or finishing them."-msgid "Are you sure you want to finish this operation? This will end all active production events for this operation."-msgstr "Are you sure you want to finish this operation? This will end all active production events for this operation."-msgid "Are you sure you want to leave this page?"msgstr "Are you sure you want to leave this page?"+msgid "Are you sure you want to mark this operation as done? This will end all active production events for this operation."+msgstr "Are you sure you want to mark this operation as done? This will end all active production events for this operation."+msgid "Assembly steps"msgstr "Assembly steps"@@ -509,9 +509,9 @@ msgstr "Dragging {0} cancelled."msgid "Due"msgstr "Due"-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.jobDueDate ) )#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )msgid "Due {0}"msgstr "Due {0}"@@ -658,13 +658,6 @@ msgstr "Filter by location"msgid "Finish"msgstr "Finish"-#. placeholder {0}: operation.itemReadableId-msgid "Finish {0}"-msgstr "Finish {0}"--msgid "Finish Anyways"-msgstr "Finish Anyways"-msgid "Finish setting up your account"msgstr "Finish setting up your account"@@ -904,6 +897,16 @@ msgstr "Manually add items to inventory"msgid "Manually remove items from inventory"msgstr "Manually remove items from inventory"+#. placeholder {0}: operation.itemReadableId+msgid "Mark {0} as Done"+msgstr "Mark {0} as Done"++msgid "Mark as Done"+msgstr "Mark as Done"++msgid "Mark as Done Anyways"+msgstr "Mark as Done Anyways"+msgid "Mark Short"msgstr "Mark Short"@@ -1164,6 +1167,10 @@ msgstr "Open Jobs"msgid "Open sub-assembly {0}: {1}"msgstr "Open sub-assembly {0}: {1}"+#. placeholder {0}: formatDate( operation.operationDueDate )+msgid "Operation needed by {0}"+msgstr "Operation needed by {0}"+msgid "Operations"msgstr "Operations"@@ -1312,11 +1319,6 @@ msgstr "Processes"msgid "Progress"msgstr "Progress"-#. placeholder {0}: formatDate( projectedCompletionDate )-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Proj. {0}"-msgid "Quality Issue"msgstr "Quality Issue"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex d75fee8698..2799f88815 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -13965,10 +13965,6 @@ msgstr "Porcentaje de Ganancia"msgid "Progress"msgstr "Progreso"-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Proy. {0}"-msgid "Project"msgstr "Proyecto"@@ -13984,10 +13980,6 @@ msgstr "Plan de Proyecto"msgid "Project start"msgstr "Inicio del proyecto"-#. placeholder {0}: formatDate(projectedDate)-msgid "Projected {0}"-msgstr "Proyectado {0}"-msgid "Projected completion"msgstr "Finalización proyectada"diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.poindex 4796181501..f61c3c979f 100644--- a/packages/locale/locales/es/mes.po+++ b/packages/locale/locales/es/mes.po@@ -188,12 +188,12 @@ msgstr "¿Está seguro de que desea eliminar esta tarjeta de tiempo? Esta acciómsgid "Are you sure you want to end all production events? This will end all active operations without completing or finishing them."msgstr "¿Está seguro de que desea finalizar todos los eventos de producción? Esto terminará todas las operaciones activas sin completarlas ni finalizarlas."-msgid "Are you sure you want to finish this operation? This will end all active production events for this operation."-msgstr "¿Está seguro de que desea finalizar esta operación? Esto terminará todos los eventos de producción activos para esta operación."-msgid "Are you sure you want to leave this page?"msgstr "¿Estás seguro de que quieres salir de esta página?"+msgid "Are you sure you want to mark this operation as done? This will end all active production events for this operation."+msgstr "¿Está seguro de que desea marcar esta operación como hecha? Esto terminará todos los eventos de producción activos para esta operación."+msgid "Assembly steps"msgstr "Pasos de montaje"@@ -509,9 +509,9 @@ msgstr "Se canceló el arrastre de {0}."msgid "Due"msgstr "Vencimiento"-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.jobDueDate ) )#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )msgid "Due {0}"msgstr "Vence {0}"@@ -658,13 +658,6 @@ msgstr "Filtrar por ubicación"msgid "Finish"msgstr "Finalizar"-#. placeholder {0}: operation.itemReadableId-msgid "Finish {0}"-msgstr "Finalizar {0}"--msgid "Finish Anyways"-msgstr "Finalizar de todas formas"-msgid "Finish setting up your account"msgstr "Finalizar la configuración de su cuenta"@@ -904,6 +897,16 @@ msgstr "Agregar artículos al inventario manualmente"msgid "Manually remove items from inventory"msgstr "Quitar manualmente artículos del inventario"+#. placeholder {0}: operation.itemReadableId+msgid "Mark {0} as Done"+msgstr "Marcar {0} como hecho"++msgid "Mark as Done"+msgstr "Marcar como hecho"++msgid "Mark as Done Anyways"+msgstr "Marcar como hecho de todas formas"+msgid "Mark Short"msgstr "Marcar como faltante"@@ -1164,6 +1167,10 @@ msgstr "Órdenes de trabajo abiertas"msgid "Open sub-assembly {0}: {1}"msgstr "Abrir subconjunto {0}: {1}"+#. placeholder {0}: formatDate( operation.operationDueDate )+msgid "Operation needed by {0}"+msgstr "Operación necesaria antes del {0}"+msgid "Operations"msgstr "Operaciones"@@ -1312,11 +1319,6 @@ msgstr "Procesos"msgid "Progress"msgstr "Progreso"-#. placeholder {0}: formatDate( projectedCompletionDate )-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Proy. {0}"-msgid "Quality Issue"msgstr "Problema de Calidad"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex a20548bb6d..196f2a3045 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -13965,10 +13965,6 @@ msgstr "Pourcentage de profit"msgid "Progress"msgstr "Progression"-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Proj. {0}"-msgid "Project"msgstr "Projet"@@ -13984,10 +13980,6 @@ msgstr "Plan de projet"msgid "Project start"msgstr "Démarrage du projet"-#. placeholder {0}: formatDate(projectedDate)-msgid "Projected {0}"-msgstr "Projeté {0}"-msgid "Projected completion"msgstr "Achèvement projeté"diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.poindex 0b4b32e1fd..29c4fb3f51 100644--- a/packages/locale/locales/fr/mes.po+++ b/packages/locale/locales/fr/mes.po@@ -188,12 +188,12 @@ msgstr "Êtes-vous sûr de vouloir supprimer cette fiche de temps ? Cette actionmsgid "Are you sure you want to end all production events? This will end all active operations without completing or finishing them."msgstr "Êtes-vous sûr de vouloir mettre fin à tous les événements de production ? Cela arrêtera toutes les opérations actives sans les terminer ni les achever."-msgid "Are you sure you want to finish this operation? This will end all active production events for this operation."-msgstr "Êtes-vous sûr de vouloir terminer cette opération ? Cela mettra fin à tous les événements de production actifs pour cette opération."-msgid "Are you sure you want to leave this page?"msgstr "Êtes-vous sûr de vouloir quitter cette page ?"+msgid "Are you sure you want to mark this operation as done? This will end all active production events for this operation."+msgstr "Êtes-vous sûr de vouloir marquer cette opération comme terminée ? Cela mettra fin à tous les événements de production actifs pour cette opération."+msgid "Assembly steps"msgstr "Étapes d'assemblage"@@ -509,9 +509,9 @@ msgstr "Déplacement de {0} annulé."msgid "Due"msgstr "Échéance"-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.jobDueDate ) )#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )msgid "Due {0}"msgstr "Échéance {0}"@@ -658,13 +658,6 @@ msgstr "Filtrer par emplacement"msgid "Finish"msgstr "Terminer"-#. placeholder {0}: operation.itemReadableId-msgid "Finish {0}"-msgstr "Terminer {0}"--msgid "Finish Anyways"-msgstr "Terminer quand même"-msgid "Finish setting up your account"msgstr "Terminez la configuration de votre compte"@@ -904,6 +897,16 @@ msgstr "Ajouter manuellement des articles au stock"msgid "Manually remove items from inventory"msgstr "Retirer manuellement des articles du stock"+#. placeholder {0}: operation.itemReadableId+msgid "Mark {0} as Done"+msgstr "Marquer {0} comme terminé"++msgid "Mark as Done"+msgstr "Marquer comme terminé"++msgid "Mark as Done Anyways"+msgstr "Marquer comme terminé quand même"+msgid "Mark Short"msgstr "Marquer comme manquant"@@ -1164,6 +1167,10 @@ msgstr "Ordres de fabrication ouverts"msgid "Open sub-assembly {0}: {1}"msgstr "Ouvrir le sous-ensemble {0} : {1}"+#. placeholder {0}: formatDate( operation.operationDueDate )+msgid "Operation needed by {0}"+msgstr "Opération requise avant le {0}"+msgid "Operations"msgstr "Opérations"@@ -1312,11 +1319,6 @@ msgstr "Processus"msgid "Progress"msgstr "Progression"-#. placeholder {0}: formatDate( projectedCompletionDate )-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Proj. {0}"-msgid "Quality Issue"msgstr "Problème de qualité"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 2e4a886f55..604ef07b6b 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -13965,10 +13965,6 @@ msgstr "लाभ प्रतिशत"msgid "Progress"msgstr "प्रगति"-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "प्रोज. {0}"-msgid "Project"msgstr "प्रोजेक्ट"@@ -13984,10 +13980,6 @@ msgstr "प्रोजेक्ट प्लान"msgid "Project start"msgstr "प्रोजेक्ट शुरुआत"-#. placeholder {0}: formatDate(projectedDate)-msgid "Projected {0}"-msgstr "अनुमानित {0}"-msgid "Projected completion"msgstr "अनुमानित पूर्णता"diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.poindex 397d892f81..1db3b3e8fe 100644--- a/packages/locale/locales/hi/mes.po+++ b/packages/locale/locales/hi/mes.po@@ -188,12 +188,12 @@ msgstr "क्या आप वाकई इस टाइमकार्ड कmsgid "Are you sure you want to end all production events? This will end all active operations without completing or finishing them."msgstr "क्या आप सभी उत्पादन इवेंट को समाप्त करना चाहते हैं? यह सभी चल रहे ऑपरेशन को पूर्ण किए बिना समाप्त कर देगा।"-msgid "Are you sure you want to finish this operation? This will end all active production events for this operation."-msgstr "क्या आप सुनिश्चित हैं कि आप इस ऑपरेशन को समाप्त करना चाहते हैं? यह इस ऑपरेशन के लिए सभी सक्रिय उत्पादन इवेंट को समाप्त कर देगा।"-msgid "Are you sure you want to leave this page?"msgstr "क्या आप वाकई इस पृष्ठ को छोड़ना चाहते हैं?"+msgid "Are you sure you want to mark this operation as done? This will end all active production events for this operation."+msgstr "क्या आप सुनिश्चित हैं कि आप इस ऑपरेशन को पूर्ण के रूप में चिह्नित करना चाहते हैं? यह इस ऑपरेशन के लिए सभी सक्रिय उत्पादन इवेंट को समाप्त कर देगा।"+msgid "Assembly steps"msgstr "असेंबली चरण"@@ -509,9 +509,9 @@ msgstr "\"{0}\" को ड्रैग करना रद्द कियाmsgid "Due"msgstr "अंतिम तारीख"-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.jobDueDate ) )#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )msgid "Due {0}"msgstr "Due {0} के लिए"@@ -658,13 +658,6 @@ msgstr "स्थान के अनुसार फ़िल्टर करmsgid "Finish"msgstr "समाप्त करें"-#. placeholder {0}: operation.itemReadableId-msgid "Finish {0}"-msgstr "{0} को समाप्त करें"--msgid "Finish Anyways"-msgstr "वैसे भी समाप्त करें"-msgid "Finish setting up your account"msgstr "अपना खाता सेट अप करना पूर्ण करें"@@ -904,6 +897,16 @@ msgstr "इन्वेंटरी में आइटम मैन्युअmsgid "Manually remove items from inventory"msgstr "इन्वेंटरी से मैनुअल रूप से आइटम निकालें"+#. placeholder {0}: operation.itemReadableId+msgid "Mark {0} as Done"+msgstr "{0} को पूर्ण के रूप में चिह्नित करें"++msgid "Mark as Done"+msgstr "पूर्ण के रूप में चिह्नित करें"++msgid "Mark as Done Anyways"+msgstr "फिर भी पूर्ण के रूप में चिह्नित करें"+msgid "Mark Short"msgstr "कम चिह्नित करें"@@ -1164,6 +1167,10 @@ msgstr "खुली जॉब्स"msgid "Open sub-assembly {0}: {1}"msgstr "सब-असेंबली {0} खोलें: {1}"+#. placeholder {0}: formatDate( operation.operationDueDate )+msgid "Operation needed by {0}"+msgstr "ऑपरेशन {0} तक आवश्यक"+msgid "Operations"msgstr "ऑपरेशन"@@ -1312,11 +1319,6 @@ msgstr "प्रक्रियाएं"msgid "Progress"msgstr "प्रगति"-#. placeholder {0}: formatDate( projectedCompletionDate )-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "प्रोज. {0}"-msgid "Quality Issue"msgstr "गुणवत्ता समस्या"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 4cee907b8d..e4a7234529 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -13965,10 +13965,6 @@ msgstr "Percentuale di profitto"msgid "Progress"msgstr "Progresso"-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Prev. {0}"-msgid "Project"msgstr "Progetto"@@ -13984,10 +13980,6 @@ msgstr "Piano di Progetto"msgid "Project start"msgstr "Inizio progetto"-#. placeholder {0}: formatDate(projectedDate)-msgid "Projected {0}"-msgstr "Previsto {0}"-msgid "Projected completion"msgstr "Completamento previsto"diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.poindex 6067fb32b5..b98f5685a2 100644--- a/packages/locale/locales/it/mes.po+++ b/packages/locale/locales/it/mes.po@@ -188,12 +188,12 @@ msgstr "Sei sicuro di voler eliminare questo cartellino? Questa azione non puòmsgid "Are you sure you want to end all production events? This will end all active operations without completing or finishing them."msgstr "Sei sicuro di voler terminare tutti gli eventi di produzione? Questo terminerà tutte le operazioni attive senza completarle o finalizzarle."-msgid "Are you sure you want to finish this operation? This will end all active production events for this operation."-msgstr "Sei sicuro di voler terminare questa operazione? Questo terminerà tutti gli eventi di produzione attivi per questa operazione."-msgid "Are you sure you want to leave this page?"msgstr "Sei sicuro di voler lasciare questa pagina?"+msgid "Are you sure you want to mark this operation as done? This will end all active production events for this operation."+msgstr "Sei sicuro di voler segnare questa operazione come completata? Questo terminerà tutti gli eventi di produzione attivi per questa operazione."+msgid "Assembly steps"msgstr "Passi di assemblaggio"@@ -509,9 +509,9 @@ msgstr "Trascinamento di {0} annullato."msgid "Due"msgstr "Scadenza"-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.jobDueDate ) )#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )msgid "Due {0}"msgstr "Scadenza {0}"@@ -658,13 +658,6 @@ msgstr "Filtra per ubicazione"msgid "Finish"msgstr "Termina"-#. placeholder {0}: operation.itemReadableId-msgid "Finish {0}"-msgstr "Termina {0}"--msgid "Finish Anyways"-msgstr "Termina comunque"-msgid "Finish setting up your account"msgstr "Completa la configurazione del tuo account"@@ -904,6 +897,16 @@ msgstr "Aggiungi manualmente articoli all'inventario"msgid "Manually remove items from inventory"msgstr "Rimuovi manualmente articoli dall'inventario"+#. placeholder {0}: operation.itemReadableId+msgid "Mark {0} as Done"+msgstr "Segna {0} come completato"++msgid "Mark as Done"+msgstr "Segna come completato"++msgid "Mark as Done Anyways"+msgstr "Segna comunque come completato"+msgid "Mark Short"msgstr "Segna Mancante"@@ -1164,6 +1167,10 @@ msgstr "Ordini di produzione aperti"msgid "Open sub-assembly {0}: {1}"msgstr "Apri sottoassieme {0}: {1}"+#. placeholder {0}: formatDate( operation.operationDueDate )+msgid "Operation needed by {0}"+msgstr "Operazione necessaria entro il {0}"+msgid "Operations"msgstr "Operazioni"@@ -1312,11 +1319,6 @@ msgstr "Processi"msgid "Progress"msgstr "Avanzamento"-#. placeholder {0}: formatDate( projectedCompletionDate )-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Prev. {0}"-msgid "Quality Issue"msgstr "Problema di qualità"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex d4e0b216ac..331b402688 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -13965,10 +13965,6 @@ msgstr "利益パーセント"msgid "Progress"msgstr "進捗"-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "予定. {0}"-msgid "Project"msgstr "プロジェクト"@@ -13984,10 +13980,6 @@ msgstr "プロジェクト計画"msgid "Project start"msgstr "プロジェクト開始"-#. placeholder {0}: formatDate(projectedDate)-msgid "Projected {0}"-msgstr "予定: {0}"-msgid "Projected completion"msgstr "予測完了"diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.poindex dbb2bb60c4..36e50034cc 100644--- a/packages/locale/locales/ja/mes.po+++ b/packages/locale/locales/ja/mes.po@@ -188,12 +188,12 @@ msgstr "このタイムカードを削除してもよろしいですか?このmsgid "Are you sure you want to end all production events? This will end all active operations without completing or finishing them."msgstr "すべての生産イベントを終了してもよろしいですか?すべてのアクティブな工程が完了せずに終了します。"-msgid "Are you sure you want to finish this operation? This will end all active production events for this operation."-msgstr "この操作を終了してもよろしいですか?これにより、この操作のすべてのアクティブな生産イベントが終了します。"-msgid "Are you sure you want to leave this page?"msgstr "このページを離れてもよろしいですか?"+msgid "Are you sure you want to mark this operation as done? This will end all active production events for this operation."+msgstr "この工程を完了としてマークしてもよろしいですか?これにより、この工程のすべてのアクティブな生産イベントが終了します。"+msgid "Assembly steps"msgstr "組立ステップ"@@ -509,9 +509,9 @@ msgstr "ドラッグ {0} キャンセル済。"msgid "Due"msgstr "期日"-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.jobDueDate ) )#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )msgid "Due {0}"msgstr "期限 {0}"@@ -658,13 +658,6 @@ msgstr "拠点で絞り込み"msgid "Finish"msgstr "完了"-#. placeholder {0}: operation.itemReadableId-msgid "Finish {0}"-msgstr "完了 {0}"--msgid "Finish Anyways"-msgstr "とにかく完了"-msgid "Finish setting up your account"msgstr "アカウントのセットアップを完了する"@@ -904,6 +897,16 @@ msgstr "手動で在庫に品目を追加"msgid "Manually remove items from inventory"msgstr "在庫から品目を手動で除去"+#. placeholder {0}: operation.itemReadableId+msgid "Mark {0} as Done"+msgstr "{0} を完了としてマーク"++msgid "Mark as Done"+msgstr "完了としてマーク"++msgid "Mark as Done Anyways"+msgstr "それでも完了としてマーク"+msgid "Mark Short"msgstr "短い数量をマーク"@@ -1164,6 +1167,10 @@ msgstr "オープンな製造指図"msgid "Open sub-assembly {0}: {1}"msgstr "サブアセンブリ {0} を開く: {1}"+#. placeholder {0}: formatDate( operation.operationDueDate )+msgid "Operation needed by {0}"+msgstr "工程の必要期日: {0}"+msgid "Operations"msgstr "工程"@@ -1312,11 +1319,6 @@ msgstr "プロセス一覧"msgid "Progress"msgstr "進捗"-#. placeholder {0}: formatDate( projectedCompletionDate )-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "予定 {0}"-msgid "Quality Issue"msgstr "品質問題"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 99c2e9dc34..8bfaf58ba1 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -13965,10 +13965,6 @@ msgstr "수익률"msgid "Progress"msgstr "진행 상황"-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "예상. {0}"-msgid "Project"msgstr "프로젝트"@@ -13984,10 +13980,6 @@ msgstr "프로젝트 계획"msgid "Project start"msgstr "프로젝트 시작"-#. placeholder {0}: formatDate(projectedDate)-msgid "Projected {0}"-msgstr "예상 {0}"-msgid "Projected completion"msgstr "예상 완료"diff --git a/packages/locale/locales/ko/mes.po b/packages/locale/locales/ko/mes.poindex 88019ba952..b843b91d34 100644--- a/packages/locale/locales/ko/mes.po+++ b/packages/locale/locales/ko/mes.po@@ -188,12 +188,12 @@ msgstr "이 근무기록을 삭제하시겠습니까? 이 작업은 되돌릴msgid "Are you sure you want to end all production events? This will end all active operations without completing or finishing them."msgstr "모든 생산 이벤트를 종료하시겠습니까? 이 작업은 완료 처리 없이 모든 진행 중인 공정작업을 종료합니다."-msgid "Are you sure you want to finish this operation? This will end all active production events for this operation."-msgstr "이 공정작업을 완료하시겠습니까? 이 작업은 해당 공정작업의 모든 진행 중인 생산 이벤트를 종료합니다."-msgid "Are you sure you want to leave this page?"msgstr "이 페이지를 나가시겠습니까?"+msgid "Are you sure you want to mark this operation as done? This will end all active production events for this operation."+msgstr "이 공정작업을 완료로 표시하시겠습니까? 이 작업은 해당 공정작업의 모든 진행 중인 생산 이벤트를 종료합니다."+msgid "Assembly steps"msgstr "조립 단계"@@ -509,9 +509,9 @@ msgstr "{0} 드래그 취소됨."msgid "Due"msgstr "기한"-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.jobDueDate ) )#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )msgid "Due {0}"msgstr "기한 {0}"@@ -658,13 +658,6 @@ msgstr "위치별 필터"msgid "Finish"msgstr "마감"-#. placeholder {0}: operation.itemReadableId-msgid "Finish {0}"-msgstr "{0} 완료"--msgid "Finish Anyways"-msgstr "그래도 완료"-msgid "Finish setting up your account"msgstr "계정 설정을 완료하세요"@@ -904,6 +897,16 @@ msgstr "재고에 품목을 수동으로 추가"msgid "Manually remove items from inventory"msgstr "재고에서 품목을 수동으로 제거"+#. placeholder {0}: operation.itemReadableId+msgid "Mark {0} as Done"+msgstr "{0} 완료로 표시"++msgid "Mark as Done"+msgstr "완료로 표시"++msgid "Mark as Done Anyways"+msgstr "그래도 완료로 표시"+msgid "Mark Short"msgstr "부족으로 표시"@@ -1164,6 +1167,10 @@ msgstr "작업 지시 열기"msgid "Open sub-assembly {0}: {1}"msgstr "하위 조립체 {0} 열기: {1}"+#. placeholder {0}: formatDate( operation.operationDueDate )+msgid "Operation needed by {0}"+msgstr "공정 필요일: {0}"+msgid "Operations"msgstr "공정작업"@@ -1312,11 +1319,6 @@ msgstr "공정"msgid "Progress"msgstr "진행 상황"-#. placeholder {0}: formatDate( projectedCompletionDate )-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "예상. {0}"-msgid "Quality Issue"msgstr "품질 이슈"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex c23551c157..a8a959b59a 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -13965,10 +13965,6 @@ msgstr "Procent Zysku"msgid "Progress"msgstr "Postęp"-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Proj. {0}"-msgid "Project"msgstr "Projekt"@@ -13984,10 +13980,6 @@ msgstr "Plan Projektu"msgid "Project start"msgstr "Początek projektu"-#. placeholder {0}: formatDate(projectedDate)-msgid "Projected {0}"-msgstr "Prognozowana {0}"-msgid "Projected completion"msgstr "Przewidywane zakończenie"diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.poindex b98394793a..05102083fb 100644--- a/packages/locale/locales/pl/mes.po+++ b/packages/locale/locales/pl/mes.po@@ -188,12 +188,12 @@ msgstr "Czy na pewno chcesz usunąć tę kartę czasu pracy? Tej operacji nie momsgid "Are you sure you want to end all production events? This will end all active operations without completing or finishing them."msgstr "Czy na pewno chcesz zakończyć wszystkie zdarzenia produkcyjne? Spowoduje to zakończenie wszystkich aktywnych operacji bez ich ukończenia."-msgid "Are you sure you want to finish this operation? This will end all active production events for this operation."-msgstr "Czy na pewno chcesz zakończyć tę operację? Spowoduje to zakończenie wszystkich aktywnych zdarzeń produkcyjnych dla tej operacji."-msgid "Are you sure you want to leave this page?"msgstr "Czy na pewno chcesz opuścić tę stronę?"+msgid "Are you sure you want to mark this operation as done? This will end all active production events for this operation."+msgstr "Czy na pewno chcesz oznaczyć tę operację jako gotową? Spowoduje to zakończenie wszystkich aktywnych zdarzeń produkcyjnych dla tej operacji."+msgid "Assembly steps"msgstr "Kroki montażu"@@ -509,9 +509,9 @@ msgstr "Przeciąganie {0} anulowane."msgid "Due"msgstr "Termin"-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.jobDueDate ) )#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )msgid "Due {0}"msgstr "Termin {0}"@@ -658,13 +658,6 @@ msgstr "Filtruj według lokalizacji"msgid "Finish"msgstr "Zakończ"-#. placeholder {0}: operation.itemReadableId-msgid "Finish {0}"-msgstr "Zakończ {0}"--msgid "Finish Anyways"-msgstr "Zakończ mimo wszystko"-msgid "Finish setting up your account"msgstr "Dokończ konfigurowanie swojego konta"@@ -904,6 +897,16 @@ msgstr "Ręcznie dodaj pozycje do zapasów"msgid "Manually remove items from inventory"msgstr "Ręcznie usuń artykuły z zapasów"+#. placeholder {0}: operation.itemReadableId+msgid "Mark {0} as Done"+msgstr "Oznacz {0} jako gotowe"++msgid "Mark as Done"+msgstr "Oznacz jako gotowe"++msgid "Mark as Done Anyways"+msgstr "Oznacz jako gotowe mimo wszystko"+msgid "Mark Short"msgstr "Oznacz jako brakujące"@@ -1164,6 +1167,10 @@ msgstr "Otwarte zlecenia produkcyjne"msgid "Open sub-assembly {0}: {1}"msgstr "Otwórz podzestawienie {0}: {1}"+#. placeholder {0}: formatDate( operation.operationDueDate )+msgid "Operation needed by {0}"+msgstr "Operacja potrzebna do {0}"+msgid "Operations"msgstr "Operacje"@@ -1312,11 +1319,6 @@ msgstr "Procesy"msgid "Progress"msgstr "Postęp"-#. placeholder {0}: formatDate( projectedCompletionDate )-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Prognoz. {0}"-msgid "Quality Issue"msgstr "Problem z jakością"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 4e5860068d..5880f4504b 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -13965,10 +13965,6 @@ msgstr "Percentual de Lucro"msgid "Progress"msgstr "Progresso"-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Proj. {0}"-msgid "Project"msgstr "Projeto"@@ -13984,10 +13980,6 @@ msgstr "Plano do Projeto"msgid "Project start"msgstr "Início do projeto"-#. placeholder {0}: formatDate(projectedDate)-msgid "Projected {0}"-msgstr "Projetado {0}"-msgid "Projected completion"msgstr "Conclusão projetada"diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.poindex 54f5bd7ea0..98ce50665b 100644--- a/packages/locale/locales/pt/mes.po+++ b/packages/locale/locales/pt/mes.po@@ -188,12 +188,12 @@ msgstr "Tem certeza de que deseja excluir este cartão de ponto? Esta ação nãmsgid "Are you sure you want to end all production events? This will end all active operations without completing or finishing them."msgstr "Tem certeza de que deseja encerrar todos os eventos de produção? Isso encerrará todas as operações ativas sem concluí-las ou finalizá-las."-msgid "Are you sure you want to finish this operation? This will end all active production events for this operation."-msgstr "Tem a certeza de que deseja concluir esta operação? Isto terminará todos os eventos de produção ativos para esta operação."-msgid "Are you sure you want to leave this page?"msgstr "Tem certeza que deseja sair desta página?"+msgid "Are you sure you want to mark this operation as done? This will end all active production events for this operation."+msgstr "Tem a certeza de que deseja marcar esta operação como concluída? Isto terminará todos os eventos de produção ativos para esta operação."+msgid "Assembly steps"msgstr "Etapas de montagem"@@ -509,9 +509,9 @@ msgstr "Arraste de {0} cancelado."msgid "Due"msgstr "Prazo"-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.jobDueDate ) )#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )msgid "Due {0}"msgstr "Vencimento {0}"@@ -658,13 +658,6 @@ msgstr "Filtrar por localização"msgid "Finish"msgstr "Concluir"-#. placeholder {0}: operation.itemReadableId-msgid "Finish {0}"-msgstr "Terminar {0}"--msgid "Finish Anyways"-msgstr "Terminar Mesmo Assim"-msgid "Finish setting up your account"msgstr "Finalize a configuração de sua conta"@@ -904,6 +897,16 @@ msgstr "Adicionar itens ao estoque manualmente"msgid "Manually remove items from inventory"msgstr "Remover itens do estoque manualmente"+#. placeholder {0}: operation.itemReadableId+msgid "Mark {0} as Done"+msgstr "Marcar {0} como Concluído"++msgid "Mark as Done"+msgstr "Marcar como Concluído"++msgid "Mark as Done Anyways"+msgstr "Marcar como Concluído Mesmo Assim"+msgid "Mark Short"msgstr "Marcar como Falta"@@ -1164,6 +1167,10 @@ msgstr "Ordens de produção abertas"msgid "Open sub-assembly {0}: {1}"msgstr "Abrir sub-montagem {0}: {1}"+#. placeholder {0}: formatDate( operation.operationDueDate )+msgid "Operation needed by {0}"+msgstr "Operação necessária até {0}"+msgid "Operations"msgstr "Operações"@@ -1312,11 +1319,6 @@ msgstr "Processos"msgid "Progress"msgstr "Progresso"-#. placeholder {0}: formatDate( projectedCompletionDate )-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Proj. {0}"-msgid "Quality Issue"msgstr "Problema de Qualidade"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 72997c31f8..fa4e189931 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -13965,10 +13965,6 @@ msgstr "Процент прибыли"msgid "Progress"msgstr "Прогресс"-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Прогн. {0}"-msgid "Project"msgstr "Проект"@@ -13984,10 +13980,6 @@ msgstr "План проекта"msgid "Project start"msgstr "Начало проекта"-#. placeholder {0}: formatDate(projectedDate)-msgid "Projected {0}"-msgstr "Прогнозируемое {0}"-msgid "Projected completion"msgstr "Прогнозное завершение"diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.poindex b36d2a5c1b..4940175dd0 100644--- a/packages/locale/locales/ru/mes.po+++ b/packages/locale/locales/ru/mes.po@@ -188,12 +188,12 @@ msgstr "Вы уверены, что хотите удалить этот табmsgid "Are you sure you want to end all production events? This will end all active operations without completing or finishing them."msgstr "Вы уверены, что хотите завершить все производственные события? Это прекратит все активные операции без их завершения."-msgid "Are you sure you want to finish this operation? This will end all active production events for this operation."-msgstr "Вы уверены, что хотите завершить эту операцию? Это завершит все активные производственные события для этой операции."-msgid "Are you sure you want to leave this page?"msgstr "Вы уверены, что хотите покинуть эту страницу?"+msgid "Are you sure you want to mark this operation as done? This will end all active production events for this operation."+msgstr "Вы уверены, что хотите отметить эту операцию как выполненную? Это завершит все активные производственные события для этой операции."+msgid "Assembly steps"msgstr "Шаги сборки"@@ -509,9 +509,9 @@ msgstr "Перетаскивание {0} отменено."msgid "Due"msgstr "Срок"-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.jobDueDate ) )#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )msgid "Due {0}"msgstr "Срок {0}"@@ -658,13 +658,6 @@ msgstr "Фильтровать по площадке"msgid "Finish"msgstr "Завершить"-#. placeholder {0}: operation.itemReadableId-msgid "Finish {0}"-msgstr "Завершить {0}"--msgid "Finish Anyways"-msgstr "Завершить в любом случае"-msgid "Finish setting up your account"msgstr "Завершите настройку вашего аккаунта"@@ -904,6 +897,16 @@ msgstr "Добавить номенклатуру на склад вручнуюmsgid "Manually remove items from inventory"msgstr "Вручную убрать позиции из запасов"+#. placeholder {0}: operation.itemReadableId+msgid "Mark {0} as Done"+msgstr "Отметить {0} как выполненное"++msgid "Mark as Done"+msgstr "Отметить как выполненное"++msgid "Mark as Done Anyways"+msgstr "Всё равно отметить как выполненное"+msgid "Mark Short"msgstr "Отметить как недостача"@@ -1164,6 +1167,10 @@ msgstr "Открытые производственные заказы"msgid "Open sub-assembly {0}: {1}"msgstr "Открыть под-узел {0}: {1}"+#. placeholder {0}: formatDate( operation.operationDueDate )+msgid "Operation needed by {0}"+msgstr "Операция нужна к {0}"+msgid "Operations"msgstr "Операции"@@ -1312,11 +1319,6 @@ msgstr "Процессы"msgid "Progress"msgstr "Прогресс"-#. placeholder {0}: formatDate( projectedCompletionDate )-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Прогноз. {0}"-msgid "Quality Issue"msgstr "Проблема качества"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 3fc2a71ac1..c736cb9e02 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -13965,10 +13965,6 @@ msgstr "Kar Yüzdesi"msgid "Progress"msgstr "İlerleme"-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Proj. {0}"-msgid "Project"msgstr "Proje"@@ -13984,10 +13980,6 @@ msgstr "Proje Planı"msgid "Project start"msgstr "Proje başlangıcı"-#. placeholder {0}: formatDate(projectedDate)-msgid "Projected {0}"-msgstr "Planlanan {0}"-msgid "Projected completion"msgstr "Öngörülen tamamlanma"diff --git a/packages/locale/locales/tr/mes.po b/packages/locale/locales/tr/mes.poindex f0e28187d1..0a99ca1b19 100644--- a/packages/locale/locales/tr/mes.po+++ b/packages/locale/locales/tr/mes.po@@ -188,12 +188,12 @@ msgstr "Bu zaman kartını silmek istediğinizden emin misiniz? Bu geri alınamamsgid "Are you sure you want to end all production events? This will end all active operations without completing or finishing them."msgstr "Tüm üretim olaylarını sonlandırmak istediğinizden emin misiniz? Bu, tüm etkin operasyonları tamamlamadan veya bitirmeden sonlandıracaktır."-msgid "Are you sure you want to finish this operation? This will end all active production events for this operation."-msgstr "Bu işlemi bitirmek istediğinizden emin misiniz? Bu, bu işlem için tüm aktif üretim olaylarını sonlandıracaktır."-msgid "Are you sure you want to leave this page?"msgstr "Bu sayfadan ayrılmak istediğinizden emin misiniz?"+msgid "Are you sure you want to mark this operation as done? This will end all active production events for this operation."+msgstr "Bu işlemi tamamlandı olarak işaretlemek istediğinizden emin misiniz? Bu, bu işlem için tüm aktif üretim olaylarını sonlandıracaktır."+msgid "Assembly steps"msgstr "Montaj adımları"@@ -509,9 +509,9 @@ msgstr "Taşıma {0} iptal edildi."msgid "Due"msgstr "Vade"-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.jobDueDate ) )#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )msgid "Due {0}"msgstr "Süresi dolacak {0}"@@ -658,13 +658,6 @@ msgstr "Konuma göre filtrele"msgid "Finish"msgstr "Bitir"-#. placeholder {0}: operation.itemReadableId-msgid "Finish {0}"-msgstr "Bitir {0}"--msgid "Finish Anyways"-msgstr "Yine de Bitir"-msgid "Finish setting up your account"msgstr "Hesabınızı ayarlamayı tamamlayın"@@ -904,6 +897,16 @@ msgstr "Envantere öğeler eklemek için manuel olarak"msgid "Manually remove items from inventory"msgstr "Envanterden stok kartlarını manuel kaldır"+#. placeholder {0}: operation.itemReadableId+msgid "Mark {0} as Done"+msgstr "{0} öğesini Tamamlandı Olarak İşaretle"++msgid "Mark as Done"+msgstr "Tamamlandı Olarak İşaretle"++msgid "Mark as Done Anyways"+msgstr "Yine de Tamamlandı Olarak İşaretle"+msgid "Mark Short"msgstr "Kısa Teslim Et"@@ -1164,6 +1167,10 @@ msgstr "Açık İş emirleri"msgid "Open sub-assembly {0}: {1}"msgstr "Alt derlemeyi aç {0}: {1}"+#. placeholder {0}: formatDate( operation.operationDueDate )+msgid "Operation needed by {0}"+msgstr "Operasyon için gereken tarih: {0}"+msgid "Operations"msgstr "Operasyonlar"@@ -1312,11 +1319,6 @@ msgstr "Süreçler"msgid "Progress"msgstr "İlerleme"-#. placeholder {0}: formatDate( projectedCompletionDate )-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "Proj. {0}"-msgid "Quality Issue"msgstr "Kalite Sorunu"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 3c54e1c027..4c005f58d0 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -13965,10 +13965,6 @@ msgstr "利润百分比"msgid "Progress"msgstr "进度"-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "预计 {0}"-msgid "Project"msgstr "项目"@@ -13984,10 +13980,6 @@ msgstr "项目计划"msgid "Project start"msgstr "项目开始"-#. placeholder {0}: formatDate(projectedDate)-msgid "Projected {0}"-msgstr "预计 {0}"-msgid "Projected completion"msgstr "预计完成"diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.poindex 6142f622c5..0ab3c590d7 100644--- a/packages/locale/locales/zh/mes.po+++ b/packages/locale/locales/zh/mes.po@@ -188,12 +188,12 @@ msgstr "确定要删除此考勤记录吗?此操作无法撤销。"msgid "Are you sure you want to end all production events? This will end all active operations without completing or finishing them."msgstr "您确定要结束所有生产事件吗?这会结束所有活跃工序而不完成或结束它们。"-msgid "Are you sure you want to finish this operation? This will end all active production events for this operation."-msgstr "您确定要完成此工序吗?这会结束此工序的所有活跃生产事件。"-msgid "Are you sure you want to leave this page?"msgstr "您确定要离开此页面吗?"+msgid "Are you sure you want to mark this operation as done? This will end all active production events for this operation."+msgstr "您确定要将此工序标记为完成吗?这会结束此工序的所有活跃生产事件。"+msgid "Assembly steps"msgstr "装配步骤"@@ -509,9 +509,9 @@ msgstr "拖拽 {0} 已取消。"msgid "Due"msgstr "应交期"-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.jobDueDate ) )#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )msgid "Due {0}"msgstr "截止 {0}"@@ -658,13 +658,6 @@ msgstr "按位置筛选"msgid "Finish"msgstr "完成"-#. placeholder {0}: operation.itemReadableId-msgid "Finish {0}"-msgstr "完成 {0}"--msgid "Finish Anyways"-msgstr "仍然完成"-msgid "Finish setting up your account"msgstr "完成账户设置"@@ -904,6 +897,16 @@ msgstr "手动添加物料至库存管理"msgid "Manually remove items from inventory"msgstr "手动从库存管理中移除物料"+#. placeholder {0}: operation.itemReadableId+msgid "Mark {0} as Done"+msgstr "将 {0} 标记为完成"++msgid "Mark as Done"+msgstr "标记为完成"++msgid "Mark as Done Anyways"+msgstr "仍然标记为完成"+msgid "Mark Short"msgstr "标记短缺"@@ -1164,6 +1167,10 @@ msgstr "未结工单"msgid "Open sub-assembly {0}: {1}"msgstr "打开子装配体 {0}: {1}"+#. placeholder {0}: formatDate( operation.operationDueDate )+msgid "Operation needed by {0}"+msgstr "工序需求日期:{0}"+msgid "Operations"msgstr "工序"@@ -1312,11 +1319,6 @@ msgstr "工艺"msgid "Progress"msgstr "进度"-#. placeholder {0}: formatDate( projectedCompletionDate )-#. placeholder {0}: formatDate(projectedCompletionDate)-msgid "Proj. {0}"-msgstr "预计 {0}"-msgid "Quality Issue"msgstr "质量问题"diff --git a/packages/planning/src/scheduling/batch-scheduler.test.ts b/packages/planning/src/scheduling/batch-scheduler.test.tsindex a0f5fead95..57cee9d8e5 100644--- a/packages/planning/src/scheduling/batch-scheduler.test.ts+++ b/packages/planning/src/scheduling/batch-scheduler.test.ts@@ -486,3 +486,46 @@ it("a predecessor freshly placed past the batch start flags a conflict on the me// The window itself is still the batch's — pinned, not re-placed.assertEquals(memberSelection.placedStart, "2026-01-05T01:00:00.000Z");});++it("a batch window finishing after the job's due date flags the member late", async () => {+ const selector = new WorkCenterSelector(+ {} as unknown as MasterDataProvider,+ "loc1"+ );+ selector.setFiniteContext(makeContext());++ const member = makeOp({+ id: "op-batch",+ workCenterId: "wc1",+ setupTime: 0,+ laborTime: 1,+ laborUnit: "Total Hours",+ machineTime: 0,+ operationQuantity: 1,+ quantityComplete: 0+ });++ const selections = await selector.selectWorkCentersForOperations([member], {+ jobDueDate: "2026-01-04",+ batchPlacements: new Map([+ ["op-batch", batchWindowPlacement(NOW + 3_600_000, NOW + 2 * 3_600_000)]+ ])+ });++ const conflict = selections.get("op-batch")!.conflict;+ assert(conflict, "member past the job's due date carries a late conflict");+ assert(+ conflict!.includes("Finishes 2026-01-05 but the job is due 2026-01-04"),+ "conflict states the lateness"+ );+ assert(conflict!.includes("BAT000001"), "conflict names the batch");++ // On time: no conflict.+ const onTime = await selector.selectWorkCentersForOperations([member], {+ jobDueDate: "2026-01-05",+ batchPlacements: new Map([+ ["op-batch", batchWindowPlacement(NOW + 3_600_000, NOW + 2 * 3_600_000)]+ ])+ });+ assertEquals(onTime.get("op-batch")!.conflict ?? null, null);+});diff --git a/packages/planning/src/scheduling/conflict-messages.ts b/packages/planning/src/scheduling/conflict-messages.tsindex 3c7576349a..7e231a7f61 100644--- a/packages/planning/src/scheduling/conflict-messages.ts+++ b/packages/planning/src/scheduling/conflict-messages.ts@@ -51,7 +51,9 @@ export type LatePlacementCause =/** Nothing delayed it — there simply isn't enough time before the due date. */| { kind: "no-runway" }/** Outside processing turnaround runs past the due date. */- | { kind: "outside-processing" };+ | { kind: "outside-processing" }+ /** Runs in a released batch, whose window is shared with the other jobs in it. */+ | { kind: "batch"; batchReadableId: string | null };/*** Classify why a placed operation finishes late. `waitedMs` is how long the@@ -154,6 +156,7 @@ export function composePlacementNote(: "Starts after an earlier operation in this job finishes";case "no-runway":case "outside-processing":+ case "batch":return null;}}@@ -228,6 +231,10 @@ export function composeLateConflict(return `${late} — not enough time remains before the due date`;case "outside-processing":return `${late} — outside processing pushes it past the due date`;+ case "batch":+ return `${late} — it runs in ${+ cause.batchReadableId ? `batch ${cause.batchReadableId}` : "a batch"+ }, scheduled with the other jobs in it`;}}diff --git a/packages/planning/src/scheduling/master-data-provider.ts b/packages/planning/src/scheduling/master-data-provider.tsindex fa57cf48f8..bdd7f8d994 100644--- a/packages/planning/src/scheduling/master-data-provider.ts+++ b/packages/planning/src/scheduling/master-data-provider.ts@@ -177,10 +177,6 @@ export interface MasterDataProvider {getJobMethodTree(methodId: string): Promise<{ data: JobMethodTreeItem[] | null; error: unknown }>;- /** Manufacturing lead time (raw, in days) of the item each make method builds. */- getMakeMethodLeadTimes(- makeMethodIds: string[]- ): Promise<Map<string, unknown>>;/** The location's timezone, falling back to the company's. */getLocationTimeZone(locationId: string): Promise<string>;getProcessesWithWorkCenters(): Promise<ProcessWorkCenters[]>;@@ -287,7 +283,6 @@ type JobPreload = {jobIdByMakeMethodId: Map<string, string>;rootByJobId: Map<string, { id: string; itemId: string | null }>;treeByRootId: Record<string, JobMethod[]>;- leadTimeByMakeMethodId: Map<string, unknown>;operationIds: Set<string>;operationsWithEvents: Set<string>;};@@ -391,14 +386,9 @@ export class KyselyMasterDataProvider implements MasterDataProvider {const roots = makeMethods.filter((m) => m.parentMaterialId === null);const rootIds = roots.map((m) => m.id);- const itemIds = [- ...new Set(- makeMethods.map((m) => m.itemId).filter((id): id is string => !!id)- )- ];const operationIds = operations.map((o) => o.id);- const [trees, replenishments, withEvents] = await Promise.all([+ const [trees, withEvents] = await Promise.all([rootIds.length === 0? { rows: [] as (JobMethod & { rootMethodId: string })[] }: sql<JobMethod & { rootMethodId: string }>`@@ -407,20 +397,9 @@ export class KyselyMasterDataProvider implements MasterDataProvider {LATERAL get_job_methods_by_method_id(r.id) WITH ORDINALITY AS tORDER BY r.id, t.ordinality`.execute(this.db),- itemIds.length === 0- ? ([] as { itemId: string; leadTime: number }[])- : this.db- .selectFrom("itemReplenishment")- .select(["itemId", "leadTime"])- .where("itemId", "in", itemIds)- .where("companyId", "=", this.companyId)- .execute(),this.readOperationsWithEvents(operationIds)]);- const leadTimeByItemId = new Map<string, unknown>(- replenishments.map((r) => [r.itemId, r.leadTime])- );const preload: JobPreload = {jobs: new Map(jobs.map((j) => [j.id as string, toJob(j)])),operations: groupBy(operations, (o) => o.jobId as string),@@ -430,9 +409,6 @@ export class KyselyMasterDataProvider implements MasterDataProvider {jobIdByMakeMethodId: new Map(makeMethods.map((m) => [m.id, m.jobId])),rootByJobId: new Map(roots.map((m) => [m.jobId, m])),treeByRootId: groupBy(trees.rows, (t) => t.rootMethodId),- leadTimeByMakeMethodId: new Map(- makeMethods.map((m) => [m.id, leadTimeByItemId.get(m.itemId ?? "")])- ),operationIds: new Set(operationIds),operationsWithEvents: withEvents,jobIds: new Set(jobIds)@@ -627,38 +603,6 @@ export class KyselyMasterDataProvider implements MasterDataProvider {return await getJobMethodTree(this.db, methodId);}- async getMakeMethodLeadTimes(- makeMethodIds: string[]- ): Promise<Map<string, unknown>> {- const preloaded = this.preload?.leadTimeByMakeMethodId;- if (preloaded && makeMethodIds.every((id) => preloaded.has(id))) {- return preloaded;- }- if (makeMethodIds.length === 0) return new Map();- const makeMethods = await this.db- .selectFrom("jobMakeMethod")- .select(["id", "itemId"])- .where("id", "in", makeMethodIds)- .execute();- const itemIds = [- ...new Set(- makeMethods.map((m) => m.itemId).filter((id): id is string => !!id)- )- ];- if (itemIds.length === 0) return new Map();- const replenishments = await this.db- .selectFrom("itemReplenishment")- .select(["itemId", "leadTime"])- .where("itemId", "in", itemIds)- .execute();- const leadTimeByItemId = new Map<string, unknown>(- replenishments.map((r) => [r.itemId, r.leadTime])- );- return new Map(- makeMethods.map((m) => [m.id, leadTimeByItemId.get(m.itemId ?? "")])- );- }-getLocationTimeZone(locationId: string): Promise<string> {return this.cached(`locationTimeZone:${locationId}`, () =>readLocationTimeZone(this.db, locationId, this.companyId)diff --git a/packages/planning/src/scheduling/need-by-calculator.test.ts b/packages/planning/src/scheduling/need-by-calculator.test.tsindex 7b8ace8a7b..706d57c8bb 100644--- a/packages/planning/src/scheduling/need-by-calculator.test.ts+++ b/packages/planning/src/scheduling/need-by-calculator.test.ts@@ -166,39 +166,26 @@ it("operationLeadTime on the consumer pulls feeders earlier, in working days", (assertEquals(weekendCrossing.get("a"), "2026-01-08");});-it("assemblyLeadTime applies only when the edge crosses make methods", () => {- // Subassembly op feeding the parent method: pulled back 3 working days.- const crossing = needBy(- [- makeOp({- id: "sub",- order: 1,- jobMakeMethodId: "mm-sub",- assemblyLeadTime: 3- }),- makeOp({ id: "root", order: 1, jobMakeMethodId: "mm-root" })- ],- [["root", "sub"]],- "2026-01-16"- );- assertEquals(crossing.get("root"), "2026-01-16"); // start 2026-01-15- assertEquals(crossing.get("sub"), "2026-01-12"); // 01-15 minus 3 working days-- // Same make method: the lead time is ignored (not an assembly boundary).- const sameMethod = needBy(+it("a subassembly is due when its parent op starts — only its own routing pulls it back", () => {+ // weld -> bend (subassembly method) -> fit (parent method). The+ // subassembly item's manufacturing lead time is NOT subtracted at the+ // assembly edge: its operations are walked here, so it would count twice.+ const ops = [+ makeOp({ id: "weld", order: 1, jobMakeMethodId: "mm-sub" }),+ makeOp({ id: "bend", order: 2, jobMakeMethodId: "mm-sub" }),+ makeOp({ id: "fit", order: 1, jobMakeMethodId: "mm-root" })+ ];+ const result = needBy(+ ops,[- makeOp({- id: "sub",- order: 1,- jobMakeMethodId: "mm-root",- assemblyLeadTime: 3- }),- makeOp({ id: "root", order: 2, jobMakeMethodId: "mm-root" })+ ["bend", "weld"],+ ["fit", "bend"]],- [["root", "sub"]],"2026-01-16");- assertEquals(sameMethod.get("sub"), "2026-01-15");+ assertEquals(result.get("fit"), "2026-01-16"); // start 01-15+ assertEquals(result.get("bend"), "2026-01-15"); // start 01-14+ assertEquals(result.get("weld"), "2026-01-14");});it("With Previous: copies its partner's target dates; upstream chains off the copy", () => {diff --git a/packages/planning/src/scheduling/need-by-calculator.ts b/packages/planning/src/scheduling/need-by-calculator.tsindex 536fbc15e0..0a4869deb5 100644--- a/packages/planning/src/scheduling/need-by-calculator.ts+++ b/packages/planning/src/scheduling/need-by-calculator.ts@@ -10,8 +10,7 @@* calculator (spec .ai/specs/2026-08-15-dual-dates-due-vs-projected.md):* reverse topological order from the job's due date, each operation due at the* earliest dependent constraint (dependent's need-by start minus that- * dependent's `operationLeadTime`, minus `assemblyLeadTime` at assembly- * edges), with two upgrades over main:+ * dependent's `operationLeadTime`), with three changes from main:** 1. Real day lengths — duration-in-days uses the work center's calendar* (`calendarHoursPerDay`), not a hardcoded 8h business day, and the@@ -19,6 +18,8 @@* hardcoded Sat/Sun.* 2. No conflict flags — lateness verdicts come from comparing the forward* projection against these targets, never from this pass.+ * 3. No item lead time at assembly edges — the subassembly's operations are+ * walked explicitly, so its manufacturing lead time would count twice.** HARD RULE: the result is written to `jobOperation.dueDate` and read by* NOTHING in the placement path. Targets never floor, delay, or otherwise@@ -86,8 +87,8 @@ function subtractWorkingDays(* - Leaf operations (no dependents) are due on the job due date.* - An operation with dependents is due at the EARLIEST dependent constraint:* the dependent's need-by START, minus that dependent's `operationLeadTime`- * working days, minus this op's `assemblyLeadTime` working days when the- * edge crosses make methods (a subassembly's output feeding its parent).+ * working days. An edge that crosses make methods (a subassembly's output+ * feeding its parent) is treated the same way.* - Need-by start = due minus `ceil(durationHours / calendarHoursPerDay(wc))`* working days (min 1 day) on the op's own calendar.* - "With Previous" operations copy their partner's target dates (the nearest@@ -231,23 +232,6 @@ export function computeNeedByDates(args: {);}- // Assembly boundary: this op is a subassembly's operation feeding a- // parent make method's operation. Pull the target back by the- // subassembly item's manufacturing lead time so the whole subassembly- // targets finishing that many days early.- const isAssemblyEdge =- !!op.jobMakeMethodId &&- !!dependentOp?.jobMakeMethodId &&- op.jobMakeMethodId !== dependentOp.jobMakeMethodId;- const assemblyLeadTime = op.assemblyLeadTime ?? 0;- if (isAssemblyEdge && assemblyLeadTime > 0) {- constraint = subtractWorkingDays(- constraint,- assemblyLeadTime,- isWorkingDayFor(op.workCenterId)- );- }-constraints.push(constraint);}if (constraints.length > 0) {diff --git a/packages/planning/src/scheduling/scheduling-engine.ts b/packages/planning/src/scheduling/scheduling-engine.tsindex 0feba886c6..cd620a01ce 100644--- a/packages/planning/src/scheduling/scheduling-engine.ts+++ b/packages/planning/src/scheduling/scheduling-engine.ts@@ -219,10 +219,6 @@ export class SchedulingEngine {// Load operationsthis.operations = await this.provider.getOperations(this.jobId);- // Enrich each operation with its make method item's manufacturing lead time- // so the date calculator can pull subassemblies earlier at assembly edges.- await this.assignAssemblyLeadTimes();-// Load existing dependencies as a starting point; createDependencies()// rebuilds the non-rework edges before placement.this.dependencies = await this.provider.getDependencies(this.jobId);@@ -275,37 +271,6 @@ export class SchedulingEngine {return this.allOperations;}- /**- * Populate `assemblyLeadTime` on each loaded operation from the manufacturing- * lead time (itemReplenishment.leadTime) of the item its make method builds.- * Used at assembly boundaries in date calculation so a subassembly finishes- * its lead time (in business days) before the parent operation that consumes it.- */- private async assignAssemblyLeadTimes(): Promise<void> {- const makeMethodIds = [- ...new Set(- this.operations- .map((op) => op.jobMakeMethodId)- .filter((id): id is string => Boolean(id))- )- ];- if (makeMethodIds.length === 0) return;-- const leadTimes = await this.provider.getMakeMethodLeadTimes(makeMethodIds);-- // NUMERIC columns can come back from pg as strings — coerce to a number.- const toLeadTimeDays = (value: unknown): number => {- const n = Number(value ?? 0);- return Number.isFinite(n) && n > 0 ? n : 0;- };-- for (const op of this.operations) {- if (op.jobMakeMethodId) {- op.assemblyLeadTime = toLeadTimeDays(leadTimes.get(op.jobMakeMethodId));- }- }- }-/*** Create operation dependencies based on assembly structure.* Loads ALL operations (including Done) to build the complete DAG.diff --git a/packages/planning/src/scheduling/types.ts b/packages/planning/src/scheduling/types.tsindex 1f3d52d2eb..5d67dc8b7e 100644--- a/packages/planning/src/scheduling/types.ts+++ b/packages/planning/src/scheduling/types.ts@@ -62,13 +62,6 @@ export type BaseOperation = {* set on job operations, so live scheduling is unchanged.*/materialReadyAt?: number;- /**- * Manufacturing lead time (in business days) of the make method's item that- * this operation belongs to. Applied only at assembly boundaries so a- * subassembly is scheduled to finish this many days before its parent- * consumes it. Populated by the engine from itemReplenishment.leadTime.- */- assemblyLeadTime?: number;priority?: number;processId: string | null;setupTime?: number;diff --git a/packages/planning/src/scheduling/work-center-selector.ts b/packages/planning/src/scheduling/work-center-selector.tsindex ec91e05321..a1990d55b4 100644--- a/packages/planning/src/scheduling/work-center-selector.ts+++ b/packages/planning/src/scheduling/work-center-selector.ts@@ -409,6 +409,20 @@ export class WorkCenterSelector {}}}+ // Late vs the JOB due date, like any other placement: the batch's+ // window is shared, so a member can finish after its own job is due.+ if (!conflict && jobDueDate) {+ const placedEndDate = businessDayFromMs(+ batchPlacement.endAt,+ ctx.timeZone+ );+ if (placedEndDate > jobDueDate) {+ conflict = composeLateConflict(placedEndDate, jobDueDate, {+ kind: "batch",+ batchReadableId: batchPlacement.batchReadableId+ });+ }+ }placedEndByOperation.set(op.id, batchPlacement.endAt);selections.set(op.id, {workCenterId: batchPlacement.workCenterId,diff --git a/packages/server-functions/src/batch-operations/index.ts b/packages/server-functions/src/batch-operations/index.tsindex 5ae24034c6..b65591f20c 100644--- a/packages/server-functions/src/batch-operations/index.ts+++ b/packages/server-functions/src/batch-operations/index.ts@@ -219,6 +219,14 @@ async function assertEligible(if (op.jobOperationBatchId) {throw new Error(`Operation ${op.id} is already in a batch`);}+ // A batch is one run on one of our work centers; subcontracted work runs+ // at the supplier, and joining a batch would stamp the batch's work center+ // onto it.+ if (op.operationType === "Outside Processing") {+ throw new Error(+ `Operation ${op.id} is outside processing and can't be batched`+ );+ }if (!NOT_STARTED.includes(op.status)) {throw new Error(`Operation ${op.id} has already started`);}