Skip to content

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

fix(production): reconcile batch planned-duration model (#1610)

Sida3ecb58eb454
diff --git a/.ai/playbooks/job-operation-batching.md b/.ai/playbooks/job-operation-batching.md
index 989597000f..fe21291314 100644
--- a/.ai/playbooks/job-operation-batching.md
+++ b/.ai/playbooks/job-operation-batching.md
@@ -180,3 +180,30 @@ via `[role=option]` textContent).
- **Job detail**: a Ready job with unbatched batchable ops shows an
"N awaiting batching" header chip.
- Completion (§5-7) is UNCHANGED by the release feature — same slicing proof.
+
+### 10. Batch-total planned duration (2026-09-10 — Sequential/Simultaneous + overlap reconciliation)
+
+The batch's single planned-duration number (ERP drawer "Planned time", MES batch
+info-bar duration, builder "≈" estimate chip) is now `process.batchType`-aware and
+overlap-correct via the shared `@carbon/utils` `batchPlanBreakdown` (its `.total`),
+matching the scheduler's `batchDuration` reservation.
+
+- **total** = shared setup (max member) + Σ|max of each member's RUN `max(labor,
+ machine)` — Σ for Sequential, max for Simultaneous. NOT setup+labor+machine
+ (that double-counted a member with both labor and machine).
+- **Per-type buckets** (drawer Run card rows, MES Times denominators) = setup max;
+ labor/machine each Σ (Sequential) | max (Simultaneous).
+- Blockers fixed: the ERP drawer service now embeds `process(name, batchType)`
+ (`production.service.ts` `getJobOperationBatchWithMembers`) and MES
+ `getJobOperationBatch` embeds `process(batchType)`; both previously computed
+ Simultaneous as Sequential.
+
+Fast DB-seed proof (no builder needed — create the batch directly):
+- Simultaneous process; member A setup 30/labor 20/machine 30 (min), member B
+ setup 45/labor 10/machine 8 (min).
+- Expected: buckets Setup **45m** / Labor **20m** / Machine **30m**; total **1h 15m**
+ (75 min = 45 + max(30,10)). The pre-fix bug read **1h 53m** (113 min).
+- Verified 2026-09-10: ERP drawer "Planned time" = 1h 15m; MES info-bar = "1 hour,
+ 15 minutes"; MES Times = 0ms/45m, 0ms/20m, 0ms/30m. The builder estimate uses the
+ same adapter and is covered by `apps/erp/test/batch-suggestions.test.ts` +
+ `packages/utils/src/batch-duration.test.ts` (incl. `total === batchDuration`).
diff --git a/.claude/rules/mes-job-operation-ui.md b/.claude/rules/mes-job-operation-ui.md
index 9429962e32..aa27583d69 100644
--- a/.claude/rules/mes-job-operation-ui.md
+++ b/.claude/rules/mes-job-operation-ui.md
@@ -108,11 +108,18 @@ In batch mode `JobOperation` derives `isBatched = !!batch`,
batch-tagged event — cost posts once at batch completion when the aggregate
events are sliced per member. A timer started on any member is the same shared
timer on every member's page.
-- **Batch-total planned durations** — `displayOperation` aggregates the members'
- `makeDurations` as ONE shared setup (the max — that is the point of batching)
- plus summed labor/machine (with a `machineDuration = 1` fallback), and carries
- the total as `duration`, so the info-bar duration, `WorkTypeToggle`, and
- `Times` denominators read against the batch's total plan, not one member's.
+- **Batch-total planned durations** — `displayOperation` converts each member's
+ times with `makeDurations`, then delegates to `@carbon/utils`
+ `batchPlanBreakdown(durations, batch.process?.batchType ?? "Sequential")` (the
+ same helper the scheduler's `batchDuration` shares its run-combining rule with,
+ and the ERP builder/drawer use). It yields ONE shared setup (the max — that is
+ the point of batching) and per-type labor/machine buckets (Σ Sequential | max
+ Simultaneous) as the `WorkTypeToggle` / `Times` denominators, and carries
+ `plan.total` as `duration` — setup + each member's run `max(labor, machine)`
+ combined by batch type, NOT setup + labor + machine (which double-counts a
+ member that has both). With a `machineDuration = 1` / `duration = 1` fallback
+ when the batch has no planned time anywhere, so the info-bar duration and
+ denominators read against the batch's total plan, not one member's.
The info-bar duration hides entirely when the plan is ≤1ms (no
"0 milliseconds"), and the per-piece header divides the shared elapsed time by
the members' summed `quantityComplete` — a quantity-weighted per-piece rate
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index e308b8df46..5d201bd6a7 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` edge-fn intent (`Planned → Active`, requires ≥1 member — NO work center: the scheduler pre-pass auto-selects earliest-finish among the process's work centers and persists it to batch + members) puts members on the floor, and the ERP `batching.update` action first runs `recalculateJobRequirements` for member jobs still Draft/Planned (no MRP), then 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/ee/src/planning/scheduling/batch-scheduler.ts`, run by `runLocationSchedule` before the per-job passes) writes a single coalesced `capacityReservation` tagged `jobOperationBatchId` (NOT NULL `operationId`/`jobId` anchored on the min member op), members pin to the window in the selector (generalized pinned-OSP path, no per-member reservation), downstream ops chain after the batch end, and the anchor comes from persisted predecessor forecasts (overruns flag a conflict and converge next wave); a batch whose open members all carry zero time standards still surfaces — a flagged 1h placeholder (`workHours` 0, never blocks) with a conflict naming the data gap, instead of silently vanishing from the reservation-driven forecast; Planned batches still schedule per-op. Completion is **two-phase and resumable** — Phase 1 (one txn) slices events + records quantities + flips `Active → Completing`; Phase 2 (idempotent, edge-fn-owned) issues each member's BOM, flips members `Done`, posts GL, then `Completing → Completed`. A Phase-2 failure leaves the batch `Completing` and re-invoking resumes (no double issue/GL). A retry MUST resubmit the quantities Phase 1 recorded — a changed quantity is rejected, not silently applied. Proportional split logic lives in `@carbon/utils` `batch-time-split` (Deno mirror under `supabase/functions/shared/`). Distinct from lot/batch tracking (`trackedEntity`/`batchNumber`). Mutations go through the `batch-operations` edge function (create/add/remove/update/dissolve/complete); payload record ids are re-read under `companyId` (`assertCompanyRecord` for location/work center) and the batch table's location/process/workCenter FKs are composite `(<col>, "companyId")` (`20260905132037_job-operation-batching.sql` (the consolidated branch migration)), so a cross-tenant id is refused by the fn AND rejected by the schema. Batch COMPOSITION happens ONLY in the batch builder (below) — the operations priority board's select-to-batch flow (checkboxes on cards, `BatchSelectionProvider`, the floating create bar, and the `BatchOpportunity` banner/column hints) was removed 2026-09-01 at Sid's direction, after the dedicated drag-and-drop batching board went the same way 2026-08-21. The board still SHOWS batches: each live batch collapses to one `BatchItemCard` in its work-center column (drag across columns reassigns the batch work center via `priorityBatchingUpdate`; Completing cards are read-only). The one composition surface — a guided **batch builder** — launches from the Batches list (`New Batch`) and an Active batch's drawer (`Add operations` → add-mode): a full-screen three-step drawer wizard (`ui/Batches/BatchBuilder.tsx`) that picks a location + batchable process (deep-linkable via `?location=&process=`; the last scope/view is remembered in localStorage), fetches candidates from `api/production/batchable-operations` (the revived `getBatchableOperations` RPC wrapper, enriched with each op's setup/labor/machine time, due date, and item thumbnail, plus per-work-center queue load and a hidden-ops count), and offers local search, a due-window quick filter (7/14/30d, due-date-sorted), a dynamic local-state "+ Filter" facet picker over the dimensions the candidates' BOMs actually contain (the material ITEM itself plus substance/grade/dimension/form/finish where populated — ANY BOM line matches ALL active facets; active facets render as removable/editable chips), two list views (polished table or group-by-material-signature sections with per-group select-all and setup-saving chips — a line's signature falls back to its BOM item's readable id when no normalized properties exist, so property-less BOMs still group by what they consume; an operation with NO op-linked BOM lines takes the JOB's unassigned (`jobOperationId IS NULL`) lines — BOMs are routinely authored without per-operation assignment, and without the fallback every such op read "No materials", emptied the facet picker, and degraded grouping to the produced item), a prominent scored suggestions banner at the top of the operations list — groups ranked by `rankSuggestions` (blended, normalised score: setup saved + due urgency + capacity fit + dimension specificity; each signature group is first split into due-date clusters no wider than `SUGGESTION_DUE_WINDOW_DAYS` = 7 via `splitByDueWindow`, so a suggestion never spans weeks — same material next month is next month's batch), each row a one-click apply with a reason chip (due now / fills a run); grouping uses `groupingKey` (material signature, falling back to the produced item for material-less assembly ops) while the mixed-materials warning uses the materials-only `materialSignature`, so the fallback never fakes a material clash. The pure logic (signatures, value sets, duration math, scoring) lives in `ui/Batches/batch-builder-logic.ts` — no JSX/lingui, unit-tested by `apps/erp/test/batch-suggestions.test.ts`, and a live preview (count · quantity · estimated run time, setup-saving + due-spread chips, plus a non-blocking "mixing materials" warning — material compatibility guides but never blocks, per the locked spec decision). Create-mode can attach a work center (picker shows each center's queue depth) and optional notes (additive `notes` field on the edge fn's create payload), and — instead of creating a duplicate — offers a searchable **"Add to batch"** footer popover (`AddToBatchButton`: a `Command` list over the compatible Active same-process batches from `deriveAddTargets`, each row `readableId · N ops`, on-select → the same `add` submit) rather than one button per batch, so it scales to hundreds of open batches. When the chosen work center has a `batchCapacity` set, a fill bar under the picker shows selected qty vs capacity ("fits in one run" / "over capacity — N loads") plus a `minimumBatchQuantity` met/short line — purely ADVISORY, Create never blocks (`resources.workCenter.batchCapacity`/`minimumBatchQuantity`). The scoped process's `batchRules` (`process.batchRules`, threaded through `getBatchableProcesses`) drives compatibility: the candidate signature/facets/mixed-material warning use every non-"ignore" dimension (default substance/grade/dimension, with the material item as a fallback for property-less BOMs), a "guide" mismatch versus the current selection shows a quiet amber tag on the row, and a "must" mismatch renders the row visible-but-LOCKED (grey lock tag, checkbox no-op, excluded from suggestions/select-all — clears when the selection empties). All resolution/enforcement is the shared `@carbon/utils` `batch-compatibility` module (`resolveBatchRules`/`mustViolations`); the client uses names and the edge fn uses ids through the same value-agnostic fold, so they always agree. The edge fn's `assertMaterialCompatible` re-checks the WHOLE membership (create: incoming set; add: existing members + incoming) after `assertEligible` and rejects a must-violating batch naming the dimension — the LOCK in the UI is advisory-fast; the edge fn is the real gate. It submits `create`/`add` to the same `batching.update` action + `batch-operations` edge fn — no new mutation path. Completion (MES modal → `complete`) can mark a member "not in this run" (`excluded`): it detaches back to the schedule un-run inside the Phase-1 txn instead of flipping Done; excluded members carry no quantities, all-excluded is rejected (dissolve instead), and a resume drops already-applied exclusions but rejects new ones. Batches LIST at `/x/production/batches` (nav: Production → Batches; `getJobOperationBatches` + `getJobOperationBatchMemberStats` + `getJobOperationBatchMembers`); rows are **expandable** (`renderExpandedRow`/`canExpandRow` on the shared `Table`, same mechanism as the ECO change-notices table) to reveal each member operation (job link, item thumbnail + readable id, completed/qty + scrap); clicking a batch opens a FULL-SIZE detail drawer (`ui/Batches/BatchDetailDrawer.tsx`): header meta (status/process/WC/location/created-by/notes), an enriched member table (thumbnails, completed/qty + scrap, status badges), and a Run card — per-type actual-vs-plan progress (plan = max member setup + Σ labor/machine, matching MES batch mode) 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: recalc Draft/Planned member jobs → `releaseJobOperationBatch` → `notifyScheduleInputsChanged`; per-batch edge-fn refusals land in the toast summary's `failed` list, the rest still release; a non-Planned id from a stale selection is skipped). Deleting from ERP = the edge fn's `dissolve`: single via the `batches/delete/:batchId` ConfirmDelete route (destructive "Dissolve Batch" in the table's row context menu + a destructive Dissolve button on the detail drawer, Active only), and bulk via selectable rows → a "Dissolve N batches" bulk action posting the selected Active ids to the `batches/dissolve` route (one edge-fn dissolve per id; the server's per-batch refusal for started batches lands in the toast summary's `failed` list, the rest still dissolve), and a printable **batch list** serves at `/file/batch/:id.pdf` (`BatchListPDF` in `@carbon/documents`; menu entries on the batch card and MES batch chip). 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` edge-fn intent (`Planned → Active`, requires ≥1 member — NO work center: the scheduler pre-pass auto-selects earliest-finish among the process's work centers and persists it to batch + members) puts members on the floor, and the ERP `batching.update` action first runs `recalculateJobRequirements` for member jobs still Draft/Planned (no MRP), then 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/ee/src/planning/scheduling/batch-scheduler.ts`, run by `runLocationSchedule` before the per-job passes) writes a single coalesced `capacityReservation` tagged `jobOperationBatchId` (NOT NULL `operationId`/`jobId` anchored on the min member op), members pin to the window in the selector (generalized pinned-OSP path, no per-member reservation), downstream ops chain after the batch end, and the anchor comes from persisted predecessor forecasts (overruns flag a conflict and converge next wave); a batch whose open members all carry zero time standards still surfaces — a flagged 1h placeholder (`workHours` 0, never blocks) with a conflict naming the data gap, instead of silently vanishing from the reservation-driven forecast; Planned batches still schedule per-op. Completion is **two-phase and resumable** — Phase 1 (one txn) slices events + records quantities + flips `Active → Completing`; Phase 2 (idempotent, edge-fn-owned) issues each member's BOM, flips members `Done`, posts GL, then `Completing → Completed`. A Phase-2 failure leaves the batch `Completing` and re-invoking resumes (no double issue/GL). A retry MUST resubmit the quantities Phase 1 recorded — a changed quantity is rejected, not silently applied. Proportional split logic lives in `@carbon/utils` `batch-time-split` (Deno mirror under `supabase/functions/shared/`). Distinct from lot/batch tracking (`trackedEntity`/`batchNumber`). Mutations go through the `batch-operations` edge function (create/add/remove/update/dissolve/complete); payload record ids are re-read under `companyId` (`assertCompanyRecord` for location/work center) and the batch table's location/process/workCenter FKs are composite `(<col>, "companyId")` (`20260905132037_job-operation-batching.sql` (the consolidated branch migration)), so a cross-tenant id is refused by the fn AND rejected by the schema. Batch COMPOSITION happens ONLY in the batch builder (below) — the operations priority board's select-to-batch flow (checkboxes on cards, `BatchSelectionProvider`, the floating create bar, and the `BatchOpportunity` banner/column hints) was removed 2026-09-01 at Sid's direction, after the dedicated drag-and-drop batching board went the same way 2026-08-21. The board still SHOWS batches: each live batch collapses to one `BatchItemCard` in its work-center column (drag across columns reassigns the batch work center via `priorityBatchingUpdate`; Completing cards are read-only). The one composition surface — a guided **batch builder** — launches from the Batches list (`New Batch`) and an Active batch's drawer (`Add operations` → add-mode): a full-screen three-step drawer wizard (`ui/Batches/BatchBuilder.tsx`) that picks a location + batchable process (deep-linkable via `?location=&process=`; the last scope/view is remembered in localStorage), fetches candidates from `api/production/batchable-operations` (the revived `getBatchableOperations` RPC wrapper, enriched with each op's setup/labor/machine time, due date, and item thumbnail, plus per-work-center queue load and a hidden-ops count), and offers local search, a due-window quick filter (7/14/30d, due-date-sorted), a dynamic local-state "+ Filter" facet picker over the dimensions the candidates' BOMs actually contain (the material ITEM itself plus substance/grade/dimension/form/finish where populated — ANY BOM line matches ALL active facets; active facets render as removable/editable chips), two list views (polished table or group-by-material-signature sections with per-group select-all and setup-saving chips — a line's signature falls back to its BOM item's readable id when no normalized properties exist, so property-less BOMs still group by what they consume; an operation with NO op-linked BOM lines takes the JOB's unassigned (`jobOperationId IS NULL`) lines — BOMs are routinely authored without per-operation assignment, and without the fallback every such op read "No materials", emptied the facet picker, and degraded grouping to the produced item), a prominent scored suggestions banner at the top of the operations list — groups ranked by `rankSuggestions` (blended, normalised score: setup saved + due urgency + capacity fit + dimension specificity; each signature group is first split into due-date clusters no wider than `SUGGESTION_DUE_WINDOW_DAYS` = 7 via `splitByDueWindow`, so a suggestion never spans weeks — same material next month is next month's batch), each row a one-click apply with a reason chip (due now / fills a run); grouping uses `groupingKey` (material signature, falling back to the produced item for material-less assembly ops) while the mixed-materials warning uses the materials-only `materialSignature`, so the fallback never fakes a material clash. The pure logic (signatures, value sets, duration math, scoring) lives in `ui/Batches/batch-builder-logic.ts` — no JSX/lingui, unit-tested by `apps/erp/test/batch-suggestions.test.ts`, and a live preview (count · quantity · estimated run time, setup-saving + due-spread chips, plus a non-blocking "mixing materials" warning — material compatibility guides but never blocks, per the locked spec decision). Create-mode can attach a work center (picker shows each center's queue depth) and optional notes (additive `notes` field on the edge fn's create payload), and — instead of creating a duplicate — offers a searchable **"Add to batch"** footer popover (`AddToBatchButton`: a `Command` list over the compatible Active same-process batches from `deriveAddTargets`, each row `readableId · N ops`, on-select → the same `add` submit) rather than one button per batch, so it scales to hundreds of open batches. When the chosen work center has a `batchCapacity` set, a fill bar under the picker shows selected qty vs capacity ("fits in one run" / "over capacity — N loads") plus a `minimumBatchQuantity` met/short line — purely ADVISORY, Create never blocks (`resources.workCenter.batchCapacity`/`minimumBatchQuantity`). The scoped process's `batchRules` (`process.batchRules`, threaded through `getBatchableProcesses`) drives compatibility: the candidate signature/facets/mixed-material warning use every non-"ignore" dimension (default substance/grade/dimension, with the material item as a fallback for property-less BOMs), a "guide" mismatch versus the current selection shows a quiet amber tag on the row, and a "must" mismatch renders the row visible-but-LOCKED (grey lock tag, checkbox no-op, excluded from suggestions/select-all — clears when the selection empties). All resolution/enforcement is the shared `@carbon/utils` `batch-compatibility` module (`resolveBatchRules`/`mustViolations`); the client uses names and the edge fn uses ids through the same value-agnostic fold, so they always agree. The edge fn's `assertMaterialCompatible` re-checks the WHOLE membership (create: incoming set; add: existing members + incoming) after `assertEligible` and rejects a must-violating batch naming the dimension — the LOCK in the UI is advisory-fast; the edge fn is the real gate. It submits `create`/`add` to the same `batching.update` action + `batch-operations` edge fn — no new mutation path. Completion (MES modal → `complete`) can mark a member "not in this run" (`excluded`): it detaches back to the schedule un-run inside the Phase-1 txn instead of flipping Done; excluded members carry no quantities, all-excluded is rejected (dissolve instead), and a resume drops already-applied exclusions but rejects new ones. Batches LIST at `/x/production/batches` (nav: Production → Batches; `getJobOperationBatches` + `getJobOperationBatchMemberStats` + `getJobOperationBatchMembers`); rows are **expandable** (`renderExpandedRow`/`canExpandRow` on the shared `Table`, same mechanism as the ECO change-notices table) to reveal each member operation (job link, item thumbnail + readable id, completed/qty + scrap); clicking a batch opens a FULL-SIZE detail drawer (`ui/Batches/BatchDetailDrawer.tsx`): header meta (status/process/WC/location/created-by/notes), an enriched member table (thumbnails, completed/qty + scrap, status badges), and a Run card — per-type actual-vs-plan progress (per-type plan buckets = max member setup + Σ|max labor/machine by `process.batchType`; the "Planned time" total = shared setup + Σ|max of each member's run `max(labor, machine)`, matching the scheduler's reservation and MES batch mode via `@carbon/utils` `batchPlanBreakdown`) with a pulsing timer-running badge and the batch's production-event history (`getJobOperationBatchWithMembers` + `getJobOperationBatchEvents`; completed batches show the per-member slices, which keep the batch tag). The Batches list also bulk-RELEASES via selectable rows → a "Release N batches" bulk action posting the selected **Planned** ids to the `batches/release` route (one release per id, mirroring the single-batch `batching.update` release branch: recalc Draft/Planned member jobs → `releaseJobOperationBatch` → `notifyScheduleInputsChanged`; per-batch edge-fn refusals land in the toast summary's `failed` list, the rest still release; a non-Planned id from a stale selection is skipped). Deleting from ERP = the edge fn's `dissolve`: single via the `batches/delete/:batchId` ConfirmDelete route (destructive "Dissolve Batch" in the table's row context menu + a destructive Dissolve button on the detail drawer, Active only), and bulk via selectable rows → a "Dissolve N batches" bulk action posting the selected Active ids to the `batches/dissolve` route (one edge-fn dissolve per id; the server's per-batch refusal for started batches lands in the toast summary's `failed` list, the rest still dissolve), and a printable **batch list** serves at `/file/batch/:id.pdf` (`BatchListPDF` in `@carbon/documents`; menu entries on the batch card and MES batch chip). 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`.
- **Maintenance Dispatch** — reactive/scheduled repair for work centers with comments, events, items, and linked work centers.
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 9e3b94759e..14247102e2 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -6012,7 +6012,7 @@ export async function getJobOperationBatchWithMembers(
) {
const batch = await client
.from("jobOperationBatch")
- .select("*, process(name), workCenter(name), location(name)")
+ .select("*, process(name, batchType), workCenter(name), location(name)")
.eq("id", batchId)
.eq("companyId", companyId)
.single();
diff --git a/apps/erp/app/modules/production/ui/Batches/BatchBuilder.tsx b/apps/erp/app/modules/production/ui/Batches/BatchBuilder.tsx
index 425f1b0f9c..4cdf1c487f 100644
--- a/apps/erp/app/modules/production/ui/Batches/BatchBuilder.tsx
+++ b/apps/erp/app/modules/production/ui/Batches/BatchBuilder.tsx
@@ -2211,10 +2211,12 @@ function ReviewPanel({
const { t } = useLingui();
// Planned durations for the batch, by type: one shared setup (the largest
- // member) plus labor/machine per the process's batch type — summed for
- // Sequential, the largest member for Simultaneous. The estimate is their sum.
+ // member) plus per-type labor/machine buckets. `total` is the wall-clock run
+ // time — one shared setup plus each member's run (the longer of its labor and
+ // machine), combined per the process's batch type — which is what the estimate
+ // shows.
const plan = batchPlanBreakdown(selected, undefined, batchType);
- const estimateMs = plan.setup + plan.labor + plan.machine;
+ const estimateMs = plan.total;
// Setup saving: one shared setup (the largest member) instead of the sum.
const setupMax = plan.setup;
@@ -2285,8 +2287,8 @@ function ReviewPanel({
<span
title={
batchType === "Simultaneous"
- ? t`One shared setup plus the longest labor and machine time — the members run together`
- : t`One shared setup plus the summed labor and machine time`
+ ? t`One shared setup plus the longest member's run time — the greater of its labor and machine — since the members run together`
+ : t`One shared setup plus each member's run time — the greater of its labor and machine — in sequence`
}
>
{t`≈ ${formatDurationMilliseconds(estimateMs, {
diff --git a/apps/erp/app/modules/production/ui/Batches/BatchDetailDrawer.tsx b/apps/erp/app/modules/production/ui/Batches/BatchDetailDrawer.tsx
index 53fcb67357..b397f8c4b4 100644
--- a/apps/erp/app/modules/production/ui/Batches/BatchDetailDrawer.tsx
+++ b/apps/erp/app/modules/production/ui/Batches/BatchDetailDrawer.tsx
@@ -129,17 +129,24 @@ export function BatchDetailDrawer({
);
};
- // Planned durations, batch semantics (mirrors the MES operation view): ONE
- // shared setup — the largest member's — plus labor/machine summed. Missing
- // units default to Total Minutes (setup) / Minutes/Piece (labor, machine).
+ // Planned durations, batch semantics (mirrors the MES operation view and the
+ // scheduler's reservation): ONE shared setup (the largest member's), per-type
+ // labor/machine buckets, and a wall-clock `total` (setup + each member's run —
+ // the longer of its labor and machine — combined per the process's batch
+ // type). Missing units default to Total Minutes (setup) / Minutes/Piece
+ // (labor, machine).
const plan = useMemo(() => {
- const { setup, labor, machine } = batchPlanBreakdown(batch.members ?? [], {
- setupUnit: "Total Minutes",
- laborUnit: "Minutes/Piece",
- machineUnit: "Minutes/Piece"
- });
- return { Setup: setup, Labor: labor, Machine: machine };
- }, [batch.members]);
+ const { setup, labor, machine, total } = batchPlanBreakdown(
+ batch.members ?? [],
+ {
+ setupUnit: "Total Minutes",
+ laborUnit: "Minutes/Piece",
+ machineUnit: "Minutes/Piece"
+ },
+ batch.process?.batchType ?? "Sequential"
+ );
+ return { Setup: setup, Labor: labor, Machine: machine, total };
+ }, [batch.members, batch.process?.batchType]);
// Actual durations from the batch's events. `duration` is generated SECONDS;
// an open event (endTime null) accrues from startTime to render time —
@@ -171,7 +178,7 @@ export function BatchDetailDrawer({
(sum, m) => sum + (m.operationQuantity ?? 0),
0
);
- const plannedTotal = plan.Setup + plan.Labor + plan.Machine;
+ const plannedTotal = plan.total;
const sortedEvents = useMemo(
() =>
diff --git a/apps/erp/app/modules/production/ui/Batches/batch-builder-logic.ts b/apps/erp/app/modules/production/ui/Batches/batch-builder-logic.ts
index cc8e9de894..15a80207e9 100644
--- a/apps/erp/app/modules/production/ui/Batches/batch-builder-logic.ts
+++ b/apps/erp/app/modules/production/ui/Batches/batch-builder-logic.ts
@@ -4,7 +4,9 @@
// transform — see apps/erp/test/batching-migration-guards.test.ts).
import {
+ batchPlanBreakdown as aggregateBatchPlan,
BATCH_RULE_DIMENSIONS,
+ type BatchPlanBreakdown,
type BatchRuleDimension,
type BatchRules,
type BatchType,
@@ -117,21 +119,16 @@ export type BatchDurationMember = {
operationQuantity: number | null;
};
-export type BatchPlanBreakdown = {
- setup: number;
- labor: number;
- machine: number;
-};
-
// The planned batch durations by type: ONE shared setup (the largest member's),
-// then labor and machine per the process's batch type — summed for Sequential
-// (members run one after another off the shared setup) or the largest member
-// for Simultaneous (members run together, e.g. one furnace cycle). The single
-// source for the review preview, the setup-saving chip, and the batch-detail
-// Run card. `unitDefaults` supplies a per-type fallback unit when a member's
-// own unit is null (the drawer defaults setup to Total Minutes and
-// labor/machine to Minutes/Piece); the builder passes none, so a missing unit
-// contributes nothing.
+// per-type labor/machine buckets, and the wall-clock `total` (one shared setup
+// plus each member's run — the longer of its labor and machine — combined per
+// the process's batch type). This is the unit-conversion ADAPTER: it converts
+// each member's raw time+unit to milliseconds via `makeDurations`, then delegates
+// the batch-type aggregation to `@carbon/utils` `batchPlanBreakdown` so the
+// scheduler, builder, drawer, and MES totals all share one rule. `unitDefaults`
+// supplies a per-type fallback unit when a member's own unit is null (the drawer
+// defaults setup to Total Minutes and labor/machine to Minutes/Piece); the
+// builder passes none, so a missing unit contributes nothing.
export function batchPlanBreakdown(
members: BatchDurationMember[],
unitDefaults?: {
@@ -141,10 +138,7 @@ export function batchPlanBreakdown(
},
batchType: BatchType = "Sequential"
): BatchPlanBreakdown {
- let setup = 0;
- let labor = 0;
- let machine = 0;
- for (const m of members) {
+ const durations = members.map((m) => {
const d = makeDurations({
setupTime: m.setupTime ?? 0,
setupUnit: m.setupUnit ?? unitDefaults?.setupUnit,
@@ -154,30 +148,13 @@ export function batchPlanBreakdown(
machineUnit: m.machineUnit ?? unitDefaults?.machineUnit,
operationQuantity: m.operationQuantity
});
- setup = Math.max(setup, d.setupDuration);
- if (batchType === "Simultaneous") {
- labor = Math.max(labor, d.laborDuration);
- machine = Math.max(machine, d.machineDuration);
- } else {
- labor += d.laborDuration;
- machine += d.machineDuration;
- }
- }
- return { setup, labor, machine };
-}
-
-// Estimated batch run time: one shared setup (largest), plus labor and machine
-// per the batch type (see batchPlanBreakdown).
-export function batchEstimateMs(
- members: BatchCandidate[],
- batchType: BatchType = "Sequential"
-): number {
- const { setup, labor, machine } = batchPlanBreakdown(
- members,
- undefined,
- batchType
- );
- return setup + labor + machine;
+ return {
+ setupDuration: d.setupDuration,
+ laborDuration: d.laborDuration,
+ machineDuration: d.machineDuration
+ };
+ });
+ return aggregateBatchPlan(durations, batchType);
}
export function dueDateOf(candidate: BatchCandidate): string | null {
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index c70f8cd699..b26f9e0e7a 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -706,7 +706,7 @@
{"name":"production_getJobOperationBatchEvents","classification":"READ","paramCount":1,"schema":"979f64cb9229","response":"8feaefdf02c8","injectAuth":"companyId","permission":"production:view"},
{"name":"production_getJobOperationBatchMembers","classification":"READ","paramCount":1,"schema":"9bbe23a57535","response":"66bcdc105c00","injectAuth":"companyId","permission":"production:view"},
{"name":"production_getJobOperationBatchMemberStats","classification":"READ","paramCount":1,"schema":"9bbe23a57535","response":"03aaee65a70b","injectAuth":"companyId","permission":"production:view"},
- {"name":"production_getJobOperationBatchWithMembers","classification":"READ","paramCount":1,"schema":"979f64cb9229","response":"1a2d1220c351","injectAuth":"companyId","permission":"production:view"},
+ {"name":"production_getJobOperationBatchWithMembers","classification":"READ","paramCount":1,"schema":"979f64cb9229","response":"a6494db9c633","injectAuth":"companyId","permission":"production:view"},
{"name":"production_getJobOperationDependencies","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"9214ed6d51dd","injectAuth":"companyId","permission":"production:view"},
{"name":"production_getJobOperations","classification":"READ","paramCount":2,"schema":"d772b12a956e","response":"720a58fe2501","injectAuth":"companyId","permission":"production:view"},
{"name":"production_getJobOperationsAssignedToEmployee","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"20f7748935c7","injectAuth":"companyId","permission":"production:view"},
diff --git a/apps/erp/test/batch-suggestions.test.ts b/apps/erp/test/batch-suggestions.test.ts
index e3e10a98e8..4db75cecf5 100644
--- a/apps/erp/test/batch-suggestions.test.ts
+++ b/apps/erp/test/batch-suggestions.test.ts
@@ -7,10 +7,10 @@ import {
candidateValueSets,
computeGuideMismatches,
computeLockedById,
+ computeMemberMismatches,
computeSelectionDimSets,
groupingKey,
materialSignature,
- computeMemberMismatches,
rankSuggestions,
splitByDueWindow
} from "../app/modules/production/ui/Batches/batch-builder-logic";
@@ -448,22 +448,48 @@ describe("batchPlanBreakdown (Sequential vs Simultaneous)", () => {
}
];
- it("Sequential: one shared setup (max), labor and machine summed", () => {
+ it("Sequential: one shared setup (max), labor and machine summed, total sums each member's run", () => {
expect(batchPlanBreakdown(members, undefined, "Sequential")).toEqual({
setup: 45 * 60_000,
labor: (20 + 5) * 60_000,
- machine: (30 + 8) * 60_000
+ machine: (30 + 8) * 60_000,
+ // total overlaps labor/machine per member: 45 + max(20,30) + max(5,8) =
+ // 45 + 30 + 8 = 83 min — NOT setup + labor + machine (which would
+ // double-count each member's overlap).
+ total: (45 + 30 + 8) * 60_000
});
});
- it("Simultaneous: one shared setup (max), labor and machine each the largest member", () => {
+ it("Simultaneous: one shared setup (max), labor and machine each the largest member, total = setup + longest run", () => {
expect(batchPlanBreakdown(members, undefined, "Simultaneous")).toEqual({
setup: 45 * 60_000,
labor: 20 * 60_000,
- machine: 30 * 60_000
+ machine: 30 * 60_000,
+ // 45 + max(max(20,30), max(5,8)) = 45 + 30 = 75 min.
+ total: (45 + 30) * 60_000
});
});
+ it("total does not double-count a member with BOTH labor and machine", () => {
+ // One member, labor 4 min/pc × 10 = 40 min, machine 6 min/pc × 10 = 60 min.
+ // The wall-clock run is max(40, 60) = 60 min, not 100 min.
+ const both = [
+ {
+ setupTime: 0,
+ setupUnit: "Total Minutes",
+ laborTime: 4,
+ laborUnit: "Minutes/Piece",
+ machineTime: 6,
+ machineUnit: "Minutes/Piece",
+ operationQuantity: 10
+ }
+ ];
+ const plan = batchPlanBreakdown(both, undefined, "Sequential");
+ expect(plan.labor).toBe(40 * 60_000);
+ expect(plan.machine).toBe(60 * 60_000);
+ expect(plan.total).toBe(60 * 60_000);
+ });
+
it("defaults to Sequential when no batchType is passed", () => {
expect(batchPlanBreakdown(members)).toEqual(
batchPlanBreakdown(members, undefined, "Sequential")
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index afb7d3424a..a6a1e9c9ef 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -52,6 +52,7 @@ import {
} from "@carbon/react";
import type { TrackedEntityAttributes } from "@carbon/utils";
import {
+ batchPlanBreakdown,
convertDateStringToIsoString,
convertKbToString,
formatDate,
@@ -337,47 +338,62 @@ export const JobOperation = ({
});
// In batch mode the shared timer is judged against the batch's TOTAL plan:
- // ONE shared setup (the largest member's — that is the point of batching) plus
- // each member's labor/machine summed. `displayOperation` feeds the info-bar
- // duration, the work-type toggle, the Times denominators, and controlsHeight
- // so a batch timer reads against the whole batch, not one member. A batch
- // with no planned time anywhere still gets a Machine timer (fallback of 1).
+ // ONE shared setup (the largest member's — that is the point of batching), the
+ // per-type labor/machine buckets (the `Times` denominators), and a wall-clock
+ // `duration` (setup + each member's run — the longer of its labor and machine
+ // — combined per the process's batch type), shared with the scheduler and the
+ // ERP surfaces via `@carbon/utils` `batchPlanBreakdown`. `displayOperation`
+ // feeds the info-bar duration, the work-type toggle, the Times denominators,
+ // and controlsHeight so a batch timer reads against the whole batch, not one
+ // member. A batch with no planned time anywhere still gets a Machine timer
+ // (fallback of 1).
const displayOperation = useMemo<OperationWithDetails>(() => {
if (!batch) return operation;
- const totals = (batch.operations ?? []).reduce(
- (acc, m) => {
- try {
- const d = makeDurations({
- setupTime: m.setupTime ?? 0,
- setupUnit: (m.setupUnit ?? "Total Minutes") as string,
- laborTime: m.laborTime ?? 0,
- laborUnit: (m.laborUnit ?? "Minutes/Piece") as string,
- machineTime: m.machineTime ?? 0,
- machineUnit: (m.machineUnit ?? "Minutes/Piece") as string,
- operationQuantity: m.operationQuantity
- });
- acc.setupDuration = Math.max(acc.setupDuration, d.setupDuration);
- acc.laborDuration += d.laborDuration;
- acc.machineDuration += d.machineDuration;
- } catch {
- // A member without times contributes nothing.
- }
- return acc;
- },
- { setupDuration: 0, laborDuration: 0, machineDuration: 0 }
+ const durations = (batch.operations ?? []).map((m) => {
+ try {
+ const d = makeDurations({
+ setupTime: m.setupTime ?? 0,
+ setupUnit: (m.setupUnit ?? "Total Minutes") as string,
+ laborTime: m.laborTime ?? 0,
+ laborUnit: (m.laborUnit ?? "Minutes/Piece") as string,
+ machineTime: m.machineTime ?? 0,
+ machineUnit: (m.machineUnit ?? "Minutes/Piece") as string,
+ operationQuantity: m.operationQuantity
+ });
+ return {
+ setupDuration: d.setupDuration,
+ laborDuration: d.laborDuration,
+ machineDuration: d.machineDuration
+ };
+ } catch {
+ // A member without times contributes nothing.
+ return { setupDuration: 0, laborDuration: 0, machineDuration: 0 };
+ }
+ });
+ const plan = batchPlanBreakdown(
+ durations,
+ batch.process?.batchType ?? "Sequential"
);
+ const totals = {
+ setupDuration: plan.setup,
+ laborDuration: plan.labor,
+ machineDuration: plan.machine
+ };
+ let duration = plan.total;
+ // No planned time anywhere → keep a drawable Machine timer so the operator
+ // can still record work (the total follows the fallback bucket).
if (
totals.setupDuration === 0 &&
totals.laborDuration === 0 &&
totals.machineDuration === 0
) {
totals.machineDuration = 1;
+ duration = 1;
}
return {
...operation,
...totals,
- duration:
- totals.setupDuration + totals.laborDuration + totals.machineDuration
+ duration
};
}, [batch, operation]);
diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.ts
index cb1f1ae30c..8d807454c7 100644
--- a/apps/mes/app/services/operations.service.ts
+++ b/apps/mes/app/services/operations.service.ts
@@ -84,7 +84,7 @@ export async function getJobOperationBatch(
) {
const batch = await client
.from("jobOperationBatch")
- .select("*")
+ .select("*, process(batchType)")
.eq("id", batchId)
.eq("companyId", companyId)
.single();
diff --git a/packages/ee/src/planning/scheduling/batch-scheduler.ts b/packages/ee/src/planning/scheduling/batch-scheduler.ts
index 6a6d83525c..8b3ccb24aa 100644
--- a/packages/ee/src/planning/scheduling/batch-scheduler.ts
+++ b/packages/ee/src/planning/scheduling/batch-scheduler.ts
@@ -25,10 +25,13 @@ import { allocateOperation, isConflict } from "./slot-allocator.ts";
* placed later than the batch start this wave surfaces as a conflict flag on
* the member (in the selector), and the next wave converges.
*
- * Duration follows `process.batchType`: `setup(max) + Σ run` (Sequential) or
- * `setup(max) + max run` (Simultaneous), net of progress via the shared
- * `batchDuration` from `@carbon/utils` — the same helper the builder estimate
- * uses, so the reservation and the UI can never disagree.
+ * Duration follows `process.batchType`: run_i = `max(labor_i, machine_i)`,
+ * combined `setup(max) + Σ run` (Sequential) or `setup(max) + max run`
+ * (Simultaneous), net of progress via the shared `batchDuration` from
+ * `@carbon/utils`. Its sibling `batchPlanBreakdown` (same `@carbon/utils`
+ * module, same run-combining rule) computes the display totals for the builder
+ * estimate, the drawer, and the MES batch surfaces without progress netting —
+ * so the reservation and the UI can never disagree.
*
* `Planned` batches are deliberately NOT here — their members schedule per-op
* exactly as before release (bounded residual over-booking that disappears at
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 197d53190f..f2be8b186a 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -11368,11 +11368,11 @@ msgstr "Ein Satz von Zahlen"
msgid "One shared setup instead of one per operation"
msgstr "Eine gemeinsame Rüstung statt einer pro Arbeitsgang"
-msgid "One shared setup plus the longest labor and machine time — the members run together"
-msgstr "Ein gemeinsames Rüsten plus die längste Personal- und Maschinenzeit — die Mitglieder laufen zusammen"
+msgid "One shared setup plus each member's run time — the greater of its labor and machine — in sequence"
+msgstr "Ein gemeinsames Rüsten plus die Bearbeitungszeit jedes Mitglieds — das Höhere aus Personal- und Maschinenzeit — nacheinander"
-msgid "One shared setup plus the summed labor and machine time"
-msgstr "Eine gemeinsame Einrichtung plus die Summe der Arbeits- und Maschinenzeit"
+msgid "One shared setup plus the longest member's run time — the greater of its labor and machine — since the members run together"
+msgstr "Ein gemeinsames Rüsten plus die längste Bearbeitungszeit der Mitglieder — das Höhere aus Personal- und Maschinenzeit — da die Mitglieder zusammen laufen"
msgid "One step in a job's routing, naming a process and a work center and carrying its own setup, labor, and machine times and rates."
msgstr "Ein Schritt im Arbeitsplan eines Fertigungsauftrags, der ein Verfahren und einen Arbeitsplatz benennt und seine eigenen Rüst-, Personal- und Maschinenzeiten sowie Sätze trägt."
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 4bfc22a084..4f21647285 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -11368,11 +11368,11 @@ msgstr "One set of numbers"
msgid "One shared setup instead of one per operation"
msgstr "One shared setup instead of one per operation"
-msgid "One shared setup plus the longest labor and machine time — the members run together"
-msgstr "One shared setup plus the longest labor and machine time — the members run together"
+msgid "One shared setup plus each member's run time — the greater of its labor and machine — in sequence"
+msgstr "One shared setup plus each member's run time — the greater of its labor and machine — in sequence"
-msgid "One shared setup plus the summed labor and machine time"
-msgstr "One shared setup plus the summed labor and machine time"
+msgid "One shared setup plus the longest member's run time — the greater of its labor and machine — since the members run together"
+msgstr "One shared setup plus the longest member's run time — the greater of its labor and machine — since the members run together"
msgid "One step in a job's routing, naming a process and a work center and carrying its own setup, labor, and machine times and rates."
msgstr "One step in a job's routing, naming a process and a work center and carrying its own setup, labor, and machine times and rates."
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index f6deab83e0..878dae1b03 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -11368,11 +11368,11 @@ msgstr "Un único conjunto de números"
msgid "One shared setup instead of one per operation"
msgstr "Una sola preparación compartida en lugar de una por operación"
-msgid "One shared setup plus the longest labor and machine time — the members run together"
-msgstr "Una preparación compartida más la mano de obra y tiempo de máquina más largos — los miembros se ejecutan juntos"
+msgid "One shared setup plus each member's run time — the greater of its labor and machine — in sequence"
+msgstr "Una Preparación compartida más el Tiempo de ejecución de cada miembro — el mayor de su Mano de obra y Máquina — en Secuencia"
-msgid "One shared setup plus the summed labor and machine time"
-msgstr "Una configuración compartida más el tiempo de mano de obra y máquina sumados"
+msgid "One shared setup plus the longest member's run time — the greater of its labor and machine — since the members run together"
+msgstr "Una Preparación compartida más el Tiempo de ejecución más largo del miembro — el mayor de su Mano de obra y Máquina — ya que los miembros funcionan juntos"
msgid "One step in a job's routing, naming a process and a work center and carrying its own setup, labor, and machine times and rates."
msgstr "Un paso en la ruta de fabricación de una orden de trabajo, que especifica un proceso y un centro de trabajo y lleva su propia preparación, mano de obra, y tiempos y tasas de máquina."
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 1968793811..afcced0d95 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -11368,11 +11368,11 @@ msgstr "Un seul ensemble de chiffres"
msgid "One shared setup instead of one per operation"
msgstr "Un seul réglage partagé au lieu d'un par opération"
-msgid "One shared setup plus the longest labor and machine time — the members run together"
-msgstr "Un réglage partagé plus la main-d'œuvre et le temps machine les plus longs — les membres s'exécutent ensemble"
+msgid "One shared setup plus each member's run time — the greater of its labor and machine — in sequence"
+msgstr "Un réglage partagé plus le temps de production de chaque membre — le plus grand entre sa main-d'œuvre et sa machine — en séquence"
-msgid "One shared setup plus the summed labor and machine time"
-msgstr "Une configuration partagée plus le temps total de main-d'œuvre et de machine"
+msgid "One shared setup plus the longest member's run time — the greater of its labor and machine — since the members run together"
+msgstr "Un réglage partagé plus le temps de production du membre le plus long — le plus grand entre sa main-d'œuvre et sa machine — puisque les membres fonctionnent ensemble"
msgid "One step in a job's routing, naming a process and a work center and carrying its own setup, labor, and machine times and rates."
msgstr "Une étape dans la gamme d'un OF, identifiant un procédé et un poste de travail, et portant ses propres temps et tarifs de réglage, main-d'œuvre et temps machine."
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 963189f87b..ea24446258 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -11368,11 +11368,11 @@ msgstr "एक ही संख्या का सेट"
msgid "One shared setup instead of one per operation"
msgstr "हर प्रक्रिया के बजाय एक साझा सेटअप"
-msgid "One shared setup plus the longest labor and machine time — the members run together"
-msgstr "एक साझा सेटअप प्लस सबसे लंबा श्रम और मशीन समय — सदस्य एक साथ चलते हैं"
+msgid "One shared setup plus each member's run time — the greater of its labor and machine — in sequence"
+msgstr "एक साझा सेटअप और प्रत्येक सदस्य का रन समय — इसके श्रम और मशीन में से अधिकतम — अनुक्रम में"
-msgid "One shared setup plus the summed labor and machine time"
-msgstr "एक साझा सेटअप जमा श्रम और मशीन समय के साथ"
+msgid "One shared setup plus the longest member's run time — the greater of its labor and machine — since the members run together"
+msgstr "एक साझा सेटअप और सबसे लंबे सदस्य का रन समय — इसके श्रम और मशीन में से अधिकतम — क्योंकि सदस्य एक साथ चलते हैं"
msgid "One step in a job's routing, naming a process and a work center and carrying its own setup, labor, and machine times and rates."
msgstr "एक जॉब की रूटिंग में एक चरण, एक प्रक्रिया और एक वर्क सेंटर का नाम देते हुए और अपने स्वयं के सेटअप, श्रम, मशीन समय और दरें शामिल करते हुए।"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index d432db8d7e..56f5927df7 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -11368,11 +11368,11 @@ msgstr "Un unico set di numeri"
msgid "One shared setup instead of one per operation"
msgstr "Un solo setup condiviso invece di uno per operazione"
-msgid "One shared setup plus the longest labor and machine time — the members run together"
-msgstr "Un attrezzaggio condiviso più il tempo di manodopera e il tempo macchina più lunghi — i componenti vengono eseguiti insieme"
+msgid "One shared setup plus each member's run time — the greater of its labor and machine — in sequence"
+msgstr "Un attrezzaggio condiviso più il tempo di lavorazione di ogni membro — il maggiore tra la sua manodopera e macchina — in sequenza"
-msgid "One shared setup plus the summed labor and machine time"
-msgstr "Una configurazione condivisa più il tempo di lavoro e macchina sommati"
+msgid "One shared setup plus the longest member's run time — the greater of its labor and machine — since the members run together"
+msgstr "Un attrezzaggio condiviso più il tempo di lavorazione del membro più lungo — il maggiore tra la sua manodopera e macchina — poiché i membri vengono lavorati insieme"
msgid "One step in a job's routing, naming a process and a work center and carrying its own setup, labor, and machine times and rates."
msgstr "Un passo nel ciclo di lavorazione di un ordine di produzione, che designa un processo e un centro di lavoro e dispone di propri tempi e tariffe di attrezzaggio, manodopera e tempo macchina."
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 915efcb02b..777d677793 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -11368,11 +11368,11 @@ msgstr "1つの数字セット"
msgid "One shared setup instead of one per operation"
msgstr "工程ごとではなく1回の段取りで共有"
-msgid "One shared setup plus the longest labor and machine time — the members run together"
-msgstr "共有の段取り 1 つと最長の労務と機械時間 — メンバーは一緒に実行されます"
+msgid "One shared setup plus each member's run time — the greater of its labor and machine — in sequence"
+msgstr "1つの共有段取りプラス各メンバーの加工時間(労務と機械のいずれか大きい方)を順番に実行"
-msgid "One shared setup plus the summed labor and machine time"
-msgstr "1つの共有セットアップと合計labor時間およびmachine時間"
+msgid "One shared setup plus the longest member's run time — the greater of its labor and machine — since the members run together"
+msgstr "1つの共有段取りプラス最長メンバーの加工時間(労務と機械のいずれか大きい方)、メンバーは同時に実行"
msgid "One step in a job's routing, naming a process and a work center and carrying its own setup, labor, and machine times and rates."
msgstr "製造指図の工順の1つのステップ。工法と作業区を指定し、段取り、労務、機械時間とそのレートを独自に保有しています。"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 8653ef8275..bd06dbbcd5 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -11368,11 +11368,11 @@ msgstr "하나의 번호 집합"
msgid "One shared setup instead of one per operation"
msgstr "공정마다가 아닌 한 번의 공용 셋업"
-msgid "One shared setup plus the longest labor and machine time — the members run together"
-msgstr "공유된 셋업 하나와 가장 긴 노무 및 기계 시간 — 멤버들이 함께 실행됨"
+msgid "One shared setup plus each member's run time — the greater of its labor and machine — in sequence"
+msgstr "공유되는 셋업 하나 플러스 각 구성원의 가공 시간 — 노무와 기계 중 더 큰 값 — 순서대로"
-msgid "One shared setup plus the summed labor and machine time"
-msgstr "공유 설정 1개 + 누계 노동력 및 기계 시간"
+msgid "One shared setup plus the longest member's run time — the greater of its labor and machine — since the members run together"
+msgstr "공유되는 셋업 하나 플러스 가장 오래 걸리는 구성원의 가공 시간 — 노무와 기계 중 더 큰 값 — 구성원들이 함께 실행되기 때문"
msgid "One step in a job's routing, naming a process and a work center and carrying its own setup, labor, and machine times and rates."
msgstr "작업 지시의 라우팅에서 한 단계로, 공법과 작업장을 지정하고 각자의 셋업, 노무, 기계 시간 및 요금을 포함합니다."
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 034bca6390..0916fc052f 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -11368,11 +11368,11 @@ msgstr "Jeden zestaw liczb"
msgid "One shared setup instead of one per operation"
msgstr "Jedno wspólne przezbrojenie zamiast osobnego dla każdej operacji"
-msgid "One shared setup plus the longest labor and machine time — the members run together"
-msgstr "Jedno wspólne przezbrojenie oraz najdłuższy czas robocizny i czas maszynowy — członkowie działają razem"
+msgid "One shared setup plus each member's run time — the greater of its labor and machine — in sequence"
+msgstr "Jedno wspólne przezbrojenie plus dla każdego elementu jego czas obróbki — większy z robocizny i maszyny — w kolejności"
-msgid "One shared setup plus the summed labor and machine time"
-msgstr "Jedna wspólna konfiguracja plus łączny czas pracy i maszyny"
+msgid "One shared setup plus the longest member's run time — the greater of its labor and machine — since the members run together"
+msgstr "Jedno wspólne przezbrojenie plus czas obróbki najdłuższego elementu — większy z robocizny i maszyny — ponieważ elementy działają razem"
msgid "One step in a job's routing, naming a process and a work center and carrying its own setup, labor, and machine times and rates."
msgstr "Jeden krok w marszrucie zlecenia produkcyjnego, określający proces i stanowisko robocze, posiadający własne przezbrojenie, robociznę, czasy maszynowe i stawki."
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 2123309413..206359c117 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -11368,11 +11368,11 @@ msgstr "Um conjunto de números"
msgid "One shared setup instead of one per operation"
msgstr "Um único setup compartilhado em vez de um por operação"
-msgid "One shared setup plus the longest labor and machine time — the members run together"
-msgstr "Um Setup compartilhado mais os tempos mais longos de mão de obra e de máquina — os membros são executados juntos"
+msgid "One shared setup plus each member's run time — the greater of its labor and machine — in sequence"
+msgstr "Um setup compartilhado mais o tempo de execução de cada membro — o maior entre sua mão de obra e máquina — em sequência"
-msgid "One shared setup plus the summed labor and machine time"
-msgstr "Uma configuração compartilhada mais o tempo de trabalho e máquina somados"
+msgid "One shared setup plus the longest member's run time — the greater of its labor and machine — since the members run together"
+msgstr "Um setup compartilhado mais o tempo de execução do membro mais longo — o maior entre sua mão de obra e máquina — já que os membros executam juntos"
msgid "One step in a job's routing, naming a process and a work center and carrying its own setup, labor, and machine times and rates."
msgstr "Uma operação no roteiro de produção de uma ordem, nomeando um processo e um centro de trabalho, e carregando seu próprio Setup, mão de obra, tempos de máquina e taxas."
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index eb5e51f017..5d448f6fee 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -11368,11 +11368,11 @@ msgstr "Один набор цифр"
msgid "One shared setup instead of one per operation"
msgstr "Одна общая наладка вместо наладки на каждую операцию"
-msgid "One shared setup plus the longest labor and machine time — the members run together"
-msgstr "Одна общая наладка плюс наибольший труд и машинное время — все детали выполняются вместе"
+msgid "One shared setup plus each member's run time — the greater of its labor and machine — in sequence"
+msgstr "Одна общая наладка плюс время обработки каждого изделия — большее значение из его труда и станка — в последовательности"
-msgid "One shared setup plus the summed labor and machine time"
-msgstr "Одна общая подготовка плюс суммированное время труда и машинного времени"
+msgid "One shared setup plus the longest member's run time — the greater of its labor and machine — since the members run together"
+msgstr "Одна общая наладка плюс время обработки самого длительного изделия — большее значение из его труда и станка — так как изделия обрабатываются вместе"
msgid "One step in a job's routing, naming a process and a work center and carrying its own setup, labor, and machine times and rates."
msgstr "Один шаг в маршрутизации задания, определяющий процесс и рабочий центр, и несущий собственное время настройки, труда и машины, а также ставки."
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 64686263da..4b05cf3520 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -11368,11 +11368,11 @@ msgstr "Tek bir sayı seti"
msgid "One shared setup instead of one per operation"
msgstr "Operasyon başına değil, tek ortak hazırlık"
-msgid "One shared setup plus the longest labor and machine time — the members run together"
-msgstr "Bir paylaşılan hazırlık artı en uzun işçilik ve makine süresi — üyeler birlikte çalışır"
+msgid "One shared setup plus each member's run time — the greater of its labor and machine — in sequence"
+msgstr "Bir paylaşılan hazırlık artı her üyenin işleme süresi — işçilik ve makine zamanının daha büyüğü — sırayla"
-msgid "One shared setup plus the summed labor and machine time"
-msgstr "Bir ortak kurulum artı toplam işçilik ve makine süresi"
+msgid "One shared setup plus the longest member's run time — the greater of its labor and machine — since the members run together"
+msgstr "Bir paylaşılan hazırlık artı en uzun üyenin işleme süresi — işçilik ve makine zamanının daha büyüğü — üyeler birlikte çalıştığından"
msgid "One step in a job's routing, naming a process and a work center and carrying its own setup, labor, and machine times and rates."
msgstr "İş emri rotasında bir adım, bir proses ve iş merkezini adlandıran, kendi hazırlık, işçilik, makine süresi ve oranlarını taşıyan."
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index b9764abb1c..a52d43e92d 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -11368,11 +11368,11 @@ msgstr "一套数字"
msgid "One shared setup instead of one per operation"
msgstr "共享一次设置,而非每道工序一次"
-msgid "One shared setup plus the longest labor and machine time — the members run together"
-msgstr "一次共享换型加上最长的人工和机器工时 — 成员一起运行"
+msgid "One shared setup plus each member's run time — the greater of its labor and machine — in sequence"
+msgstr "一次共享换型加上每个成员的加工时间 — 取人工和机器时间的较大值 — 按顺序运行"
-msgid "One shared setup plus the summed labor and machine time"
-msgstr "一个共享设置加上汇总的劳动和机器时间"
+msgid "One shared setup plus the longest member's run time — the greater of its labor and machine — since the members run together"
+msgstr "一次共享换型加上最长的成员加工时间 — 取人工和机器时间的较大值 — 由于成员并行运行"
msgid "One step in a job's routing, naming a process and a work center and carrying its own setup, labor, and machine times and rates."
msgstr "工单工艺路线中的一个步骤,命名一个工艺和工作中心,并包含其自己的换型、人工和机器工时及费率。"
diff --git a/packages/utils/src/batch-duration.test.ts b/packages/utils/src/batch-duration.test.ts
index f73dd42653..45916f1822 100644
--- a/packages/utils/src/batch-duration.test.ts
+++ b/packages/utils/src/batch-duration.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { batchDuration } from "./batch-duration";
+import { batchDuration, batchPlanBreakdown } from "./batch-duration";
describe("batchDuration", () => {
// The spec's worked example: effective member runs of 40/70/50 minutes
@@ -117,3 +117,68 @@ describe("batchDuration", () => {
expect(total).toBe(5 * 60);
});
});
+
+describe("batchPlanBreakdown", () => {
+ // Two members with BOTH labor and machine so the total's overlap rule bites:
+ // m1 run = max(40, 30) = 40; m2 run = max(70, 30) = 70. Buckets keep labor
+ // and machine separate; total combines each member's run.
+ const members = [
+ {
+ setupDuration: 10 * 60,
+ laborDuration: 40 * 60,
+ machineDuration: 30 * 60
+ },
+ { setupDuration: 15 * 60, laborDuration: 70 * 60, machineDuration: 30 * 60 }
+ ];
+
+ it("Sequential: shared setup, summed buckets, total sums each member's run", () => {
+ expect(batchPlanBreakdown(members, "Sequential")).toEqual({
+ setup: 15 * 60,
+ labor: (40 + 70) * 60,
+ machine: (30 + 30) * 60,
+ // NOT setup + labor + machine (which would double-count the overlap):
+ // 15 + max(40,30) + max(70,30) = 15 + 40 + 70 = 125 min.
+ total: (15 + 40 + 70) * 60
+ });
+ });
+
+ it("Simultaneous: shared setup, buckets take the largest, total = setup + longest run", () => {
+ expect(batchPlanBreakdown(members, "Simultaneous")).toEqual({
+ setup: 15 * 60,
+ labor: 70 * 60,
+ machine: 30 * 60,
+ // 15 + max(max(40,30), max(70,30)) = 15 + 70 = 85 min.
+ total: (15 + 70) * 60
+ });
+ });
+
+ it("returns all zeros for an empty batch", () => {
+ expect(batchPlanBreakdown([], "Sequential")).toEqual({
+ setup: 0,
+ labor: 0,
+ machine: 0,
+ total: 0
+ });
+ expect(batchPlanBreakdown([], "Simultaneous")).toEqual({
+ setup: 0,
+ labor: 0,
+ machine: 0,
+ total: 0
+ });
+ });
+
+ // The plan-vs-schedule guarantee: the display total must equal the
+ // scheduler's reservation for zero-progress members with no recorded events.
+ it("total equals batchDuration for zero-progress members without events", () => {
+ const durationMembers = members.map((m) => ({
+ ...m,
+ operationQuantity: 10,
+ quantityComplete: 0
+ }));
+ for (const batchType of ["Sequential", "Simultaneous"] as const) {
+ expect(batchPlanBreakdown(members, batchType).total).toBe(
+ batchDuration(durationMembers, batchType)
+ );
+ }
+ });
+});
diff --git a/packages/utils/src/batch-duration.ts b/packages/utils/src/batch-duration.ts
index 45838970ed..34a673d752 100644
--- a/packages/utils/src/batch-duration.ts
+++ b/packages/utils/src/batch-duration.ts
@@ -22,6 +22,19 @@ export type BatchDurationMember = {
export type BatchType = "Sequential" | "Simultaneous";
+/**
+ * Combine per-member values by the batch type: members run one after another
+ * (Sequential → sum) or together in one load (Simultaneous → the longest).
+ * The single rule `batchDuration` and `batchPlanBreakdown` share, so their run
+ * totals cannot drift. Caller guards the empty case (Simultaneous's max over an
+ * empty list is -Infinity).
+ */
+function combineRuns(values: number[], batchType: BatchType): number {
+ return batchType === "Sequential"
+ ? values.reduce((a, b) => a + b, 0)
+ : Math.max(...values);
+}
+
/**
* Planned duration of an operation batch, in seconds.
*
@@ -52,10 +65,57 @@ export function batchDuration(
return Math.max(m.laborDuration, m.machineDuration) * remainingFraction;
});
- const run =
- batchType === "Sequential"
- ? runs.reduce((a, b) => a + b, 0)
- : Math.max(...runs);
+ return setup + combineRuns(runs, batchType);
+}
+
+/** Pre-converted setup/labor/machine durations for one batch member. */
+export type BatchMemberDurations = {
+ setupDuration: number;
+ laborDuration: number;
+ machineDuration: number;
+};
+
+/**
+ * Planned durations of an operation batch, broken out for display. Unlike
+ * `batchDuration` this is not netted for progress and has no setup-done rule —
+ * it is the full plan a user reads before the run starts.
+ *
+ * - `setup` = max member setup (one shared load).
+ * - `labor` / `machine` = Σ (Sequential) | max (Simultaneous) — per-type
+ * buckets that survive as denominators for plan-vs-actual rows.
+ * - `total` = setup + Σ|max of each member's run (`max(labor_i, machine_i)`),
+ * NOT setup + labor + machine: a member's labor and machine overlap on one
+ * wall clock, so summing the buckets double-counts. This matches the
+ * scheduler's reservation (`batchDuration`) for zero-progress members exactly.
+ */
+export type BatchPlanBreakdown = {
+ setup: number;
+ labor: number;
+ machine: number;
+ total: number;
+};
+
+export function batchPlanBreakdown(
+ members: BatchMemberDurations[],
+ batchType: BatchType
+): BatchPlanBreakdown {
+ if (members.length === 0) return { setup: 0, labor: 0, machine: 0, total: 0 };
+
+ const setup = Math.max(...members.map((m) => m.setupDuration));
+ const labor = combineRuns(
+ members.map((m) => m.laborDuration),
+ batchType
+ );
+ const machine = combineRuns(
+ members.map((m) => m.machineDuration),
+ batchType
+ );
+ const total =
+ setup +
+ combineRuns(
+ members.map((m) => Math.max(m.laborDuration, m.machineDuration)),
+ batchType
+ );
- return setup + run;
+ return { setup, labor, machine, total };
}