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.

feat(production): batch materials, output lots, and lot merge (#1648)

Sid4634b460f0d0
diff --git a/.ai/lessons.md b/.ai/lessons.md
index cc725fb464..b0f4088662 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -1953,6 +1953,36 @@ full-screen ERP route.
**Follow-up (found later):** The original fix only covered the `quote` header row's `internalNotes`/`externalNotes` in `quoteToQuote`. The per-line copy loop in the SAME function (`quoteToQuote`'s `sourceQuoteLines.data` insert into `quoteLine`) still spread the source row raw (`{...line, quoteId, companyId}`), leaving `additionalCharges`, `configuration`, `customFields`, `externalNotes`, `internalNotes`, and `priceTrace` unserialised — and `quoteOperation.workInstruction` (NOT NULL jsonb) was copied raw too. Any quote whose line ever picked up one of these as a non-object (a string/array) fails the copy deterministically with the same "invalid input syntax for type json" 500 — which the caller's `fetchWithRetry` (`packages/auth/src/lib/supabase/client.ts`) then retries blindly up to 3 times, and because this failure lands inside the SAME transaction as the `quote`/`quoteLine`/`quoteLinePrice` inserts it rolls back cleanly (no duplicate). **Rule addendum:** when applying this fix, grep the whole function for every `{...row}` spread and every raw `column: source.column` assignment into a jsonb column, not just the columns already known to be trouble — a partial rollout re-creates the exact bug it fixed, just narrower.
+## Resolve the accounting period BEFORE a transaction that writes for N records
+
+**Context:** The batch material pick (`issue` case `trackedEntitiesToBatch`) runs one Kysely transaction and calls the per-member consumption writer once per batch member. Each member's write path reaches `createMaterialWipEntries` → `getCurrentAccountingPeriod`.
+
+**Problem:** `getCurrentAccountingPeriod` READS the period over HTTP (supabase-js) but CREATES a missing one through the transaction handle. Inside one transaction, member 2's read cannot see member 1's uncommitted insert, so both try to create the same month and the `accountingPeriod_company_fy_period_idx` unique index aborts the whole pick. It only fires on the first posting of a month into a fresh database, so it passes every test run but the first — and the rollback makes it look like the pick silently did nothing (HTTP 200, empty body; the real error is only in the edge-runtime log).
+
+**Rule:** Any lazily-created singleton that reads outside the transaction and writes inside it must be resolved BEFORE the transaction opens, once, when a flow writes for N records in one transaction. For the accounting period that is `await getCurrentAccountingPeriod(client, companyId, db, companyToday.toString())` ahead of `db.transaction()`, guarded on `accountingEnabled`.
+
+**Applies to:** `getCurrentAccountingPeriod` / `getAccountingPeriodForDate` in any multi-record edge-function transaction; the same shape applies to `getNextSequence` and any other get-or-create helper straddling the transaction boundary.
+
+## A post-success prompt must not live in the component the success unmounts
+
+**Context:** MES batch completion. `BatchCompleteModal` submitted the completion and was meant to swap itself for a "merge these lots?" prompt when the action returned one.
+
+**Problem:** The modal is rendered `{batch && batchCompleteModal.isOpen && …}`, and `batch` is only passed by the loader while the batch is `Active`/`Completing`. Completing it — the very thing that produces the prompt — revalidates the loader, `batch` becomes null, and the modal unmounts with its `useFetcher` still holding the response. The prompt could never render, and the symptom was indistinguishable from the server never sending it (the page just sat there, because a `data()` reply does not navigate).
+
+**Rule:** When an action's response drives UI that appears AFTER success, own the fetcher in a component that outlives the state change — here `JobOperation`, passing the fetcher down into the modal and rendering the prompt itself, ungated by `batch`. Before wiring a post-success view, ask which component the success unmounts.
+
+**Applies to:** MES `JobOperation` + `BatchCompleteModal`/`BatchMergePrompt`; any modal gated on loader data that its own submit invalidates.
+
+## Vite caches a module-resolution MISS for the whole dev session
+
+**Context:** Added a `BatchMergePrompt` component: edited the importing file first, created the new file a moment later.
+
+**Problem:** The SSR module graph cached the failed resolution, so every request 500'd with `Failed to load url ./components/BatchMergePrompt … Does the file exist?` even though it did. `docker exec … grep` and `ls` both confirmed the file, which sends you hunting a phantom bug in the import path.
+
+**Rule:** Create the new module BEFORE the code that imports it. If the overlay already says "Does the file exist?" and it does, `touch` the new file and its importer to force re-resolution — the file's presence alone will not invalidate the cached miss.
+
+**Applies to:** any new file under `apps/{erp,mes}/app` added after its importer during a running `crbn up`; the sibling failure mode for edge functions is the cached compiled isolate (`crbn reload edge-runtime`).
+
## An unchecked supabase-js insert turns a NOT NULL violation into silence
**Context:** Inspection rejects were supposed to seed `nonConformanceItemTrackedEntity` links on the NCR's default Scrap row so the MRB could split or reassign specific entities. Nothing ever appeared. Both writers — `x+/inspection+/$id.reject.tsx` and `x+/issue+/new.tsx`'s job-operation auto-link — built their rows without `nonConformanceId`, which is `NOT NULL` on that table (`20260421130000_nc-item-tracked-entity.sql`).
@@ -2061,3 +2091,13 @@ full-screen ERP route.
**Rule:** A retry wrapper must never blindly retry a write with real side effects and no idempotency key. `fetchWithRetry` already carved out `isStorageUpload` for this exact reason ("re-sending a multi-GB PUT ... is wasteful"); the same reasoning applies even harder to Edge Function invocations, which routinely do multi-table, multi-transaction writes (`get-method`, `convert`, every `post-*` function). Added `isEdgeFunctionInvoke` (matches `/functions/v1/`) alongside it — one attempt only, honoring the caller's own signal, no retry on status or network error. When debugging "op failed but extra copies appeared," check for exactly this shape (one incoming request, several committed results) before assuming a client-side double-submit or a browser retry.
**Applies to:** `packages/auth/src/lib/supabase/client.ts` (`fetchWithRetry`, `isEdgeFunctionInvoke`); any future retry/timeout wrapper placed in front of `client.functions.invoke`. Also: `$quoteId.duplicate.tsx` and similar routes that discard the real error into a generic message — add `logger.error` there so a recurrence is diagnosable from Vercel logs alone, without needing Supabase edge-function log access.
+
+## A fetcher's redirect is dropped when anything revalidates during the action
+
+**Context:** MES "Complete Batch" posts through a `useFetcher` to an action that runs for several seconds and ends in `redirect(path.to.operations)`. The operation page also subscribes to realtime changes on `jobOperation`/`job` and calls `revalidate()` on each.
+
+**Problem:** The completion's own writes fired the realtime `revalidate()` mid-action. React Router (`handleFetcherAction`) ignores a fetcher's redirect when `pendingNavigationLoadId > originatingLoadId` — any navigation or revalidation started after the submit wins. The redirect was silently discarded, the fetcher went idle, and the page sat on stale loader data from the mid-run revalidation (the batch still "Completing", button reading "Retry Completion") even though the work had landed.
+
+**Rule:** Realtime listeners must not revalidate while a fetcher on the page is submitting — use `useRealtimeRevalidator()` (`apps/mes/app/hooks/useRealtime.tsx`), never a bare `useRevalidator().revalidate()` in a realtime callback. Skipping loses nothing: the router revalidates after every action, which is why `revalidate()` already no-ops during a navigation submission. The same race also reached single-operation completion: finishing a job's last operation completes the job, the job UPDATE revalidated the operation loader mid-action, its floor gate redirected with "This operation's job has not been released to the floor", and the operator saw that error instead of "Operation finished successfully" (reproduced 2 of 10 runs before the guard, 0 of 8 after). Batch completion additionally returns `data({ completed: true })` and navigates client-side.
+
+**Applies to:** every realtime- or interval-driven `revalidate()` on a page that submits fetchers — MES `useOperation`, `AssemblyView`, `useRealtime`.
diff --git a/.ai/plans/2026-09-16-batch-materials-and-output-lots.md b/.ai/plans/2026-09-16-batch-materials-and-output-lots.md
new file mode 100644
index 0000000000..d7e567eabf
--- /dev/null
+++ b/.ai/plans/2026-09-16-batch-materials-and-output-lots.md
@@ -0,0 +1,305 @@
+# Batch Materials & Output Lots — implementation plan
+
+**Spec:** .ai/specs/2026-09-16-batch-materials-and-output-lots.md
+**Research:** .ai/research/batch-aggregated-material-consumption.md (+ .ai/research/batch-output-lot-identity.md)
+**Branch:** feat/batch-materials-and-output-lots (cut from `main`)
+
+## Progress
+- [x] Task 1: Migration — `Batch Merge` ledger enum values + generate types
+- [x] Task 2: `producedItem` compatibility dimension
+- [x] Task 3: Pro-rata pick splitter (shared pure util + test)
+- [x] Task 4: `issue` case `trackedEntitiesToBatch`
+- [x] Task 5: `issue` case `mergeTrackedEntities` (+ shared/batch-merge.ts)
+- [x] Task 6: `issue` case `jobOperationBatchOutput` (extraction)
+- [x] Task 7: `batch-operations` complete — batch numbers in, output step, entity ids out
+- [x] Task 8: MES batch materials panel + shared pick
+- [x] Task 9: BatchCompleteModal — batch-number fields + merge prompt
+- [x] Task 10: ERP batch detail drawer merge action + service wrappers
+- [x] Task 11: i18n + full scoped validation
+- [x] Task 12: Browser verification (/test)
+
+## Dependencies
+- Task 1 first (enum + types) — Tasks 5/10 reference `Batch Merge`.
+- Task 2 independent of everything else (can run in parallel with 3–7).
+- Tasks 4, 5, 6 all edit `packages/database/supabase/functions/issue/index.ts` — run **sequentially** (4 → 5 → 6), never as parallel subagents.
+- Task 7 needs 6. Task 8 needs 3+4. Task 9 needs 7 (+5 for the prompt). Task 10 needs 5.
+- Tasks 11–12 last.
+
+---
+
+## Task 1: Migration — `Batch Merge` ledger enum values + generate types
+
+**Depends on:** none
+**Files:**
+- Create: migration via `pnpm db:migrate:new batch-merge-ledger-enum` (never hand-pick the timestamp)
+- Copy from (precedent): `packages/database/supabase/migrations/20250225145619_tracked-entities.sql:21` and `packages/database/supabase/migrations/20260504000000_cost-layers.sql:16`
+
+**Steps:**
+1. `pnpm db:migrate:new batch-merge-ledger-enum`
+2. Migration body (idempotent, additive only):
+ ```sql
+ ALTER TYPE "itemLedgerDocumentType" ADD VALUE IF NOT EXISTS 'Batch Merge';
+ ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Batch Merge';
+ ```
+3. `pnpm db:migrate`
+4. `pnpm run generate:types`
+
+**Verify:**
+```bash
+grep -rn "'Batch Merge'" packages/database/src/types.ts | head -2
+# Expected: 'Batch Merge' appears in both itemLedgerDocumentType and journalLineDocumentType unions
+pnpm exec turbo run typecheck --filter=@carbon/database
+# Expected: exit 0
+```
+
+**Out of scope:** any other enum, any table change.
+
+## Task 2: `producedItem` compatibility dimension
+
+**Depends on:** none
+**Files:**
+- Modify: `packages/database/supabase/functions/shared/batch-compatibility.ts` — add `"producedItem"` to `BATCH_RULE_DIMENSIONS`, `DEFAULT_BATCH_RULES.producedItem = "ignore"`, extend the value-set fold (`MemberValueSets`) with the member's produced item readable id
+- Modify: `apps/erp/app/modules/production/ui/Batches/batch-builder-logic.ts` — candidates already carry `itemReadableId` (the produced item, used as `groupingKey` fallback at line ~70); when `rules.producedItem !== "ignore"`, include it in `materialSignature`/value sets exactly like the other dimensions
+- Modify: `packages/database/supabase/functions/batch-operations/index.ts` — `assertMaterialCompatible`'s value-set build gains the produced item per member op (`jobOperation → item.readableId`)
+- Modify: the process form's "Compatibility rules" card (grep `Compatibility rules` under `apps/erp/app/modules/resources/ui/Processes/`) — add the "Produced item" row, same Require Match / Suggest Match / Ignore control as existing rows
+- Modify: `packages/utils/src/batch-compatibility.test.ts` and `apps/erp/test/batch-suggestions.test.ts` — new cases: `producedItem: "must"` refuses mixed produced items; `"guide"` splits groups; DEFAULT rules reproduce current signatures byte-for-byte (existing snapshot tests must NOT change)
+
+**Steps:**
+1. Extend the shared module first (it is the single source: `packages/utils/src/batch-compatibility.ts` re-exports it).
+2. Wire client fold + edge fn fold; copy the exact pattern of the existing `item` dimension (`batch-compatibility.ts:42` uses `line.itemReadableId` — the CONSUMED line item; `producedItem` reads the candidate/member's own `itemReadableId`, NOT a BOM line).
+3. Add the form row; stored values stay `must`/`guide`/`ignore` (labels "Require Match"/"Suggest Match" — see spec 2026-08-21 changelog 2026-09-01).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/utils test -- batch-compatibility
+pnpm --filter erp test -- batch-suggestions
+# Expected: all pass, including untouched pre-existing snapshot/signature cases
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+```
+
+**Out of scope:** any change to DEFAULT behavior of existing dimensions; suggestions due-window logic.
+
+## Task 3: Pro-rata pick splitter (shared pure util + test)
+
+**Depends on:** none
+**Files:**
+- Create: `packages/database/supabase/functions/shared/batch-pick-split.ts`
+- Create: `packages/database/supabase/functions/shared/batch-pick-split.test.ts`
+- Create: `packages/utils/src/batch-pick-split.ts` — one-line re-export (`export * from "../../database/supabase/functions/shared/batch-pick-split.ts";`)
+- Copy from (precedent): `packages/database/supabase/functions/shared/batch-time-split.ts` (+ its `.test.ts`) for the shared-module shape; `packages/utils/src/precision.ts` re-export pattern
+
+**Steps:**
+1. Export `splitPickAcrossMembers(members: { jobOperationId: string; remaining: number }[], pickedQuantity: number): { jobOperationId: string; quantity: number }[]`.
+2. Weights = each member's `remaining` (skip members with remaining ≤ 0); shares computed via `distributeRoundingResidual` from `../shared/precision.ts` at internal scale so shares sum EXACTLY to `pickedQuantity` (numeric-precision rule: never round parts independently).
+3. Reject (throw) `pickedQuantity` > Σ remaining and Σ remaining === 0 — callers surface the message verbatim.
+4. Tests: exact-sum at 5-decimal quantities; the customer sequence (remaining 4,000/2,500, pick 4,000 then 2,500 → totals land exactly 4,000/2,500 with both picks pro-rata); single-member; over-pick rejection.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/utils test -- batch-pick-split
+# Expected: all cases pass, including the two-pick exact-total sequence
+```
+
+**Out of scope:** any DB access — this module stays pure.
+
+## Task 4: `issue` case `trackedEntitiesToBatch`
+
+**Depends on:** Task 3
+**Files:**
+- Modify: `packages/database/supabase/functions/issue/index.ts` — new discriminated-union member + case
+- Copy from (precedent): the `trackedEntitiesToOperation` validator (`issue/index.ts:910`) and its case body
+
+**Steps:**
+1. Validator: `{ type: "trackedEntitiesToBatch", batchId, parentTrackedEntityId, children: [{trackedEntityId, quantity}], overrideExpired?, overrideReason?, companyId, userId }`.
+2. `requirePermissions(req, companyId, userId, { update: "production" })`.
+3. One Kysely transaction: load the batch under `companyId` (reject missing or `Completed`); load member ops + their `jobMaterial` rows matching the parent entity's item, `FOR UPDATE`; remaining = estimated − already-consumed per member; split the total picked quantity with `splitPickAcrossMembers`; per member, perform the same writes `trackedEntitiesToOperation` performs for that member's share — extract the per-operation write sequence from the existing case into a helper function both cases call (no copy-paste; if extraction proves unsafe because the existing case's writes are interleaved with case-specific reads, STOP and report rather than duplicating the logic).
+4. Expired-entity policy check runs once against the parent, same helper the existing case uses.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/database
+# Expected: exit 0
+grep -n "trackedEntitiesToBatch" packages/database/supabase/functions/issue/index.ts | head -3
+# Expected: validator + case + helper call sites present
+```
+Runtime check happens in Task 12 (the local edge runtime live-mounts `functions/`).
+
+**Out of scope:** any change to `trackedEntitiesToOperation`'s external behavior; untracked materials (they stay backflush-only).
+
+## Task 5: `issue` case `mergeTrackedEntities` (+ shared/batch-merge.ts)
+
+**Depends on:** Tasks 1, 4 (same-file sequencing)
+**Files:**
+- Create: `packages/database/supabase/functions/shared/batch-merge.ts`
+- Create: `packages/database/supabase/functions/shared/batch-merge.test.ts`
+- Modify: `packages/database/supabase/functions/issue/index.ts` — new validator + case calling the helper
+- Copy from (precedent): `packages/database/supabase/functions/shared/batch-split.ts` (+ test) — mirror its plan-builder shape, its `"Merge"` activity write (line ~252), its net-zero `Batch Split` ledger rows (lines ~190–203), and its bin resolution (`resolveTrackedEntityBin` — lessons.md "actual bin")
+
+**Steps:**
+1. Helper builds a merge plan from parent rows: validate ≥2 parents, all same `itemId`, same `companyId`, all `Available`; merged entity = fresh `nanoid`, quantity = Σ parents, `expirationDate` = earliest non-null parent expiry, attributes kept only where every parent has the identical value, plus provenance attribute `"Merged From Entity IDs": [...]` (add the key to `TrackedEntityAttributes` in `packages/utils/src/types.ts` AND `functions/lib/utils.ts`, both — see split spec's pointer-attribute decision).
+2. New batch readable number: use the same sequence/generation path the existing entity-creation flow uses (grep `batch-numbers` / how `trackedEntity` readable ids are assigned in `assign-serial-numbers/index.ts`; if there is no reusable generator, STOP and report — do not invent a numbering scheme).
+3. `issue` case: `{ type: "mergeTrackedEntities", trackedEntityIds (min 2), companyId, userId }`, permission `update: "inventory"`; one transaction: insert merged entity, `Merge` activity (inputs = each parent @ its quantity, output = merged @ Σ), net-zero `Batch Merge` itemLedger rows at each parent's resolved bin (−q per parent) and +Σq for the merged entity, parents → `Consumed`. Returns `{ trackedEntityId }`.
+4. Tests (pure plan builder): conflict policy (earliest expiry; disagreeing attribute dropped; equal attribute kept), mixed-item rejection, <2 rejection, quantity sum.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/utils test -- batch-merge 2>/dev/null || (cd packages/database/supabase/functions && deno test shared/batch-merge.test.ts)
+# Expected: plan-builder tests pass (run under the same runner batch-split.test.ts uses — check how it is invoked in CI/package.json first)
+pnpm exec turbo run typecheck --filter=@carbon/database
+# Expected: exit 0
+```
+
+**Out of scope:** merging entities of different items under any flag; a generic inventory-wide merge UI.
+
+## Task 6: `issue` case `jobOperationBatchOutput` (extraction)
+
+**Depends on:** Tasks 4, 5 (same-file sequencing)
+**Files:**
+- Modify: `packages/database/supabase/functions/issue/index.ts` — extract the `Produce`-activity + entity-flip block from `jobOperationBatchComplete` (lines ~1125–1180: `trackedActivity` "Produce", `trackedActivityOutput`, entity → `Available` with summed quantity) into a helper; new case `jobOperationBatchOutput` `{ jobOperationId, trackedEntityId, quantity, companyId, userId }` that calls ONLY that helper — no `productionQuantity` insert, no `issueJobOperationMaterials`
+
+**Steps:**
+1. Extract; `jobOperationBatchComplete` keeps calling the helper plus its existing quantity insert + backflush — its external behavior must not change.
+2. New case: permission `update: "production"`; idempotency: if the entity is already `Available`, return success without writing (this is the resume path).
+3. For the entity flip's quantity, sum the member's `Production` `productionQuantity` rows (they exist — batch Phase 1 wrote them) exactly as the existing case does.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/database
+# Expected: exit 0
+grep -c "issueJobOperationMaterials" packages/database/supabase/functions/issue/index.ts
+# Expected: same count of CALL SITES as before the task in jobOperationBatchComplete/jobOperation paths; zero calls inside the new case
+```
+
+**Out of scope:** `jobOperationSerialComplete`; any behavior change to the single-op completion flow.
+
+## Task 7: `batch-operations` complete — batch numbers in, output step, entity ids out
+
+**Depends on:** Task 6
+**Files:**
+- Modify: `packages/database/supabase/functions/batch-operations/index.ts` — `complete` payload member rows gain optional `batchNumber`/`trackedEntityId`; Phase 2 gains the output step; result gains `outputTrackedEntityIds`
+- Modify: `apps/mes/app/services/models.ts` (completion validator — find with `grep -rn "completeJobOperationBatch" apps/mes/app/services/`) and its test `apps/mes/app/services/models.batch.test.ts`
+
+**Steps:**
+1. Phase 2 order becomes: material issue per member → **output per member** (`issue` `jobOperationBatchOutput` for members whose produced item `requiresBatchTracking` and whose payload row carries `trackedEntityId`) → Done flip → GL → finalize. Fail-fast semantics identical to neighbors (first error verbatim, batch stays `Completing`).
+2. Resume contract: like quantities, a resume must carry the same `trackedEntityId`s Phase 1 recorded the run against — the output step's idempotency (entity already `Available`) makes re-runs no-ops; do NOT add new Phase-1 writes.
+3. If a member's produced item requires batch tracking but the payload row lacks `trackedEntityId`, reject with an error naming the member — never silently skip a tracked output.
+4. Return `outputTrackedEntityIds: string[]` (created/available entities of this completion) so the MES route can offer the merge prompt without a refetch.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/database --filter=mes
+# Expected: exit 0
+pnpm --filter mes test -- models.batch
+# Expected: validator tests pass incl. new batchNumber/trackedEntityId rows
+```
+
+**Out of scope:** Phase 1 slicing/quantities; the resume quantity-mismatch contract (unchanged).
+
+## Task 8: MES batch materials panel + shared pick
+
+**Depends on:** Tasks 3, 4
+**Files:**
+- Modify: `apps/mes/app/services/operations.service.ts` (or the service file exporting `getJobMaterialsByOperationId` — locate with `grep -rn "getJobMaterialsByOperationId" apps/mes/app/services/`) — add `getJobMaterialsByBatchId(client, { batchId, companyId })`: member ops' materials, same row shape, plus `jobOperationId`
+- Modify: `apps/mes/app/routes/x+/operation.$operationId.tsx:242` — in batch mode (loader already resolves `batch`), load materials by batch instead of by operation
+- Modify: `apps/mes/app/components/JobOperation/JobOperation.tsx` (materials block, ~line 1244) — in batch mode group rows by item with summed required/issued, member rows expandable beneath; untracked items: display only (no issue button); tracked items: pick action opens the existing modal
+- Modify: `apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx` — batch mode submits `{ type: "trackedEntitiesToBatch", batchId, … }` through the existing issue route
+- Modify: the MES issue action route (`apps/mes/app/routes/x+/issue.tsx` — confirm it forwards to the `issue` edge fn; if the modal posts elsewhere, follow the modal's existing action) — accept and forward the new payload type
+- Copy from (precedent): the existing materials block + `IssueMaterialModal` in the same files; grouping UI follows the kit-materials grouping already in `JobOperation.tsx` (~line 1271 `kitMaterialsByParentId`)
+
+**Steps:**
+1. Service + loader swap (batch mode only — single-op mode byte-for-byte unchanged).
+2. Grouped rendering with summed quantities; per-member issued progress from the same rows.
+3. Pick modal: title shows the summed remaining; on submit in batch mode, pass `batchId`; surface the edge fn's error message verbatim on failure (flash pattern — `.claude/rules/flash-system.md`).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=mes
+# Expected: exit 0
+pnpm run lint
+# Expected: exit 0
+```
+Behavioral proof in Task 12.
+
+**Out of scope:** ERP materials surfaces; single-operation (non-batch) picking; picking-list flows.
+
+## Task 9: BatchCompleteModal — batch-number fields + merge prompt
+
+**Depends on:** Tasks 5, 7
+**Files:**
+- Modify: `apps/mes/app/components/JobOperation/components/BatchCompleteModal.tsx` — per-member `batchNumber` field (only for members whose produced item `requiresBatchTracking`; pre-filled from the member's WIP tracked entity, editable) + hidden `trackedEntityId`; after a successful completion whose result carries ≥2 `outputTrackedEntityIds` of the same item, render the merge prompt ("N lots of the same item — merge into one?") whose confirm posts `mergeTrackedEntities` and then shows the merged lot number
+- Modify: `apps/mes/app/routes/x+/batch.$batchId.complete.tsx` — pass the new member fields through to the edge fn; add the merge intent (invoke `issue` `mergeTrackedEntities`)
+- Copy from (precedent): `BatchCompleteModal.tsx` itself (member-row array pattern); use `NumberControlled`-style controlled inputs per the batching memory (react-aria + RVF nested-array defaults are unreliable — see `.ai/lessons.md` and project memory); batch-number lookups precedent: `apps/mes/app/routes/api+/batch-numbers.ts`
+
+**Steps:**
+1. Loader/route supplies each member's WIP `trackedEntityId` + current batch number (the operation page already resolves `trackedEntityId` for the single-op flow — reuse that resolution per member; if a member has NO WIP entity, show the field empty and let the edge fn's Task-7 rejection surface — do not create entities client-side).
+2. "Retry Completion" (Completing state) re-sends the same `trackedEntityId`s.
+3. Merge prompt: one button, no form fields; on success show the merged readable batch number; all strings `<Trans>`/`t`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=mes
+# Expected: exit 0
+```
+Behavioral proof in Task 12.
+
+**Out of scope:** serial members (no field, unchanged); auto-merge; scrap fields.
+
+## Task 10: ERP batch detail drawer merge action + service wrappers
+
+**Depends on:** Task 5
+**Files:**
+- Modify: `apps/erp/app/modules/inventory/inventory.service.ts` — `mergeTrackedEntities(client, { trackedEntityIds, companyId, userId })` invoke wrapper (`{data, error}` shape)
+- Modify: `apps/erp/app/modules/inventory/inventory.models.ts` — `mergeTrackedEntitiesValidator` (`trackedEntityIds: min 2`)
+- Modify: `apps/erp/app/modules/production/ui/Batches/BatchDetailDrawer.tsx` — for a `Completed` batch whose members' output entities are ≥2 same-item and un-merged (none carries `"Merged From Entity IDs"` pointing at them / none `Consumed` by a Merge), show "Merge output lots"; posts to a new action route under the batches route folder (follow the drawer's existing action-route pattern — grep its current fetcher targets)
+- Copy from (precedent): `BatchDetailDrawer.tsx`'s existing actions; route action shape from the batching routes (`grep -rn "batch-operations" apps/erp/app/routes/x+/ | head` to find the invoke-forwarding precedent)
+
+**Steps:**
+1. Wrapper + validator + action route with `requirePermissions` `{ update: "inventory" }`.
+2. Drawer button gated to the un-merged state; after success, revalidate and show the merged lot's readable id linking to the traceability page (existing path helper — grep `path.to.` traceability usages in the drawer's module).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+```
+
+**Out of scope:** a standalone inventory-wide merge screen; BatchesTable columns.
+
+## Task 11: i18n + full scoped validation
+
+**Depends on:** Tasks 2, 7, 8, 9, 10
+**Files:**
+- Modify: `packages/locale/locales/*/{erp,mes}.po` via the translate pipeline
+
+**Steps:**
+1. Lingui extract per the i18n rule (`.claude/rules/i18n-lingui-system.md`), then `/translate` to fill missing strings.
+2. Full gate: lint, scoped typechecks, unit tests.
+
+**Verify:**
+```bash
+pnpm run lint
+pnpm exec turbo run typecheck --filter=erp --filter=mes --filter=@carbon/database --filter=@carbon/utils
+pnpm --filter @carbon/utils test && pnpm --filter erp test -- batch && pnpm --filter mes test -- models.batch
+# Expected: all exit 0; no missing msgstr for new ids
+```
+
+**Out of scope:** committing — that goes through /check-and-commit with the user.
+
+## Task 12: Browser verification (/test)
+
+**Depends on:** Task 11
+**Files:** none (verification only; playbook may be cached to `.ai/playbooks/`)
+
+**Steps:**
+1. With the user's dev stack up (never restart it), run `/test` against this branch's diff. Scenario, end to end:
+ a. Flag a process batchable with `producedItem: must`; verify the builder refuses mixed produced items and the edge fn rejects a forced create.
+ b. Seed 2 jobs (batch-tracked output item, shared batch-tracked input item, BOM 4,000/2,500) — reuse the seeding technique in `.ai/playbooks/job-operation-batching.md`.
+ c. Batch them; in MES verify the materials panel shows one 6,500 group; pick 6,500 from one lot → verify per-member consumption rows 4,000/2,500 against the same lot (DB check), then a second scenario picking from two lots → pro-rata links to both.
+ d. Complete with batch numbers → verify per-member entities `Available`, quantities correct; kill the edge fn mid-Phase-2 once (or force an issue failure) → verify `Completing` + retry resumes without duplicate entities.
+ e. Accept the merge prompt → verify ONE merged entity (Σ quantity, earliest expiry), `Merge` activity with both parents, net-zero `Batch Merge` ledger rows, parents `Consumed`, traceability graph walks merged → both jobs.
+ f. Regression: an unbatched op's materials panel and completion are unchanged; a serial-tracked member batches and completes exactly as today.
+
+**Verify:** the /test run report; every acceptance criterion in the spec checked off with evidence (DB queries or screenshots).
+
+**Out of scope:** performance testing; MRP interaction.
diff --git a/.ai/playbooks/batch-materials-and-output-lots.md b/.ai/playbooks/batch-materials-and-output-lots.md
new file mode 100644
index 0000000000..60ea5685a7
--- /dev/null
+++ b/.ai/playbooks/batch-materials-and-output-lots.md
@@ -0,0 +1,136 @@
+# Batch Materials & Output Lots
+
+Last tested: 2026-09-16 (feat/batch-materials-and-output-lots — re-verified on a clean `crbn up` stack)
+Routes: ERP `/x/resources/processes/$processId` (Produced item rule), `/x/production/batches/$batchId` (Merge output lots); MES `/x/operation/$operationId` (batch materials annotation + Batch Number column)
+Edge fns: `issue` (`trackedEntitiesToBatch`, `jobOperationBatchOutput`, `mergeTrackedEntities`), `batch-operations` (`complete` with `trackedEntityId`/`batchNumber` member fields)
+
+## Strategy
+
+Same split as `job-operation-batching.md`: UI (agent-browser) for the process
+rule row, the MES annotation, and the completion modal; edge fn `curl` +
+SQL for every mutation proof. All logic proofs are DB-level.
+
+## Prerequisites / seeding
+
+On top of the batching playbook's seeding gotchas:
+- Produced items and the input item need `itemTrackingType='Batch'`;
+ `jobMakeMethod.requiresBatchTracking=true` per member.
+- Each member needs a WIP `trackedEntity` (`status='Reserved'`, quantity 0,
+ `attributes: {"Job Make Method": <jmmId>, "Job": <jobId>}`) — outputs finalize
+ into it, and the shared pick books consumption against it.
+- The input lot needs an `itemLedger` `Positive Adjmt.` row (bin resolution).
+- **`itemCost` rows are mandatory** for every seeded item when
+ `companySettings.accountingEnabled` — `calculateCOGS` throws "no result"
+ without them (first observed failure mode).
+- enum values: `methodType='Pull from Inventory'`, `operationType='Process'`,
+ `processType='Process'`.
+
+## Steps
+
+### 1. producedItem compatibility rule
+- SQL: `update process set "batchRules"='{"producedItem":"must"}'`.
+- Edge fn `batch-operations` `create` with ops producing DIFFERENT items →
+ `These operations can't share a batch — the producedItem must match…`.
+- Same produced item → `{success, readableId: BAT…}`.
+- UI: `/x/resources/processes/$id` → Compatibility rules card shows a
+ "Produced item" row; a stored `must` renders as "Require Match".
+
+### 2. Shared pick (trackedEntitiesToBatch)
+- `POST /functions/v1/issue` `{type:"trackedEntitiesToBatch", batchId, itemId,
+ children:[{trackedEntityId: <lot>, quantity: <sum>}]}`.
+- Verify: `jobMaterial.quantityIssued` per member = its OWN estimated quantity
+ (4000/2500 from a 6500 pick); a partial draw creates a split child
+ (`Split` activity) consumed by member 1, the remainder consumed whole by
+ member 2; each `Consume` activity outputs that member's WIP entity;
+ `itemLedger` nets to zero for the lot moves + per-member `Job Consumption`.
+- Over-pick → `Pick of N exceeds the batch's remaining requirement of M`.
+
+### 3. Completion with output lots
+- Seed a batch-tagged `productionEvent`, then `batch-operations` `complete`
+ with member rows carrying `trackedEntityId` (the WIP entity) + `batchNumber`.
+- Verify: WIP entities → `Available` with the entered readableId + produced
+ quantity; sliced events ∝ operationQuantity; ops Done; batch Completed;
+ response carries `outputTrackedEntityIds`.
+
+### 4. Output idempotency
+- Re-invoke `issue` `jobOperationBatchOutput` on an Available entity →
+ `{success:true, created:false}`, still exactly ONE `Produce` activity.
+
+### 5. Lot merge
+- `issue` `{type:"mergeTrackedEntities", trackedEntityIds:[A,B], readableId?}` →
+ ONE new entity (Σ quantity, earliest parent expiry; `readableId` inherits the
+ FIRST parent's when omitted — the edge fn orders parents by the CALLER's list,
+ so `[WIP1,WIP2]` yields WIP1's number and the reverse yields WIP2's),
+ `Merge` activity (inputs = parents at their quantities, output = merged),
+ net-zero `Batch Merge` ledger rows, parents `Consumed`.
+- MES prompt: completing via `/x/batch/$batchId/complete` with ≥2 same-item
+ outputs returns `{merge:{count}}` instead of redirecting; the prompt renders
+ from `JobOperation` (NOT the completion modal — completing unmounts it).
+- The merge action posts `intent=merge` and **no ids**; the route re-derives
+ them from the batch's membership. Negative test: post
+ `trackedEntityIds=<two unrelated Available same-item lots>` and confirm those
+ lots are untouched (before the fix they would have been merged).
+- ERP drawer shows "Merge output lots" only for a Completed batch with ≥2
+ Available same-item outputs (absent once merged).
+
+### 6. MES batch materials UI
+- `/x/operation/$memberOpId` in batch mode: the materials row shows
+ `Batch: <summed required>` under required and `Batch: <summed issued>` under
+ issued (from `getBatchMaterialTotals`).
+- Complete modal (icon button with the package-check icon in Controls — click
+ via `document.querySelectorAll('button')` index hunting, aria-labels are
+ empty on the icon buttons): table columns Job / Quantity / Scrap /
+ **Batch Number** (batch-number inputs pre-filled from each member's WIP
+ entity readableId).
+- The pick modal's quantity in batch mode defaults to the BATCH remaining
+ (6,500), not the member's share — if it shows the member's number the
+ `batchRemainingQuantity` wiring has regressed and the pro-rata split will
+ under-serve every member.
+
+## Selector Notes
+- MES Controls icon buttons have NO aria-labels; the big start/stop is the
+ `size-24` button, the complete/ellipsis buttons flank it. Click by index via
+ eval, never by ref.
+- Login `Continue` is overlay-blocked for `agent-browser click` — use
+ `form.requestSubmit(button)` via eval.
+
+## Stack setup (crbn)
+
+```bash
+pnpm exec crbn status # port assignment + container health
+pnpm exec crbn up --all # compose services + both dev servers
+pnpm exec crbn reload edge-runtime # REQUIRED after editing functions/** — see below
+```
+
+`crbn up` rewrites `.env.local` with this worktree's own slug URLs
+(`https://{erp,mes,api}.<branch-slug>.dev`) — never reuse another worktree's URLs.
+
+**The edge runtime caches compiled isolates.** The functions tree is live-mounted,
+so `docker exec <edge> grep …` shows your edit, but the running isolate still
+serves the OLD module — a fix appears not to work while the file is provably
+correct. `crbn reload edge-runtime` is the fix; allow ~30-60s before the first
+call succeeds (an early call returns "An invalid response was received from the
+upstream server").
+
+## Seeding gotchas found the hard way
+
+- Seed the jobs at a location that HAS `storageUnit` rows (all bins live at
+ Manufacturing Plant `loc_GYZ…`, none at Headquarters) and give the input lot's
+ `itemLedger` row a `storageUnitId` — otherwise `get_available_tracked_entities`
+ returns nothing and the pick modal says "Batch number is not available".
+- That RPC's argument order is `(item, company, location)` — easy to transpose.
+- The Scan field takes the entity **id** (what a barcode encodes), not the human
+ `readableId`; a valid scan auto-submits the pick.
+- Resetting a batch for a re-run must also zero `jobOperation.quantityComplete`,
+ or the completion modal pre-fills 0, reads every row as "not in this run", and
+ disables submit.
+
+## Common Failures
+- `{"message":"no result"}` on the pick → missing `itemCost` row (accounting on).
+- `duplicate key … accountingPeriod` on the FIRST pick of a month →
+ fixed in code (period pre-resolved before the batch transaction); if seen,
+ the edge isolate is stale — `crbn reload edge-runtime`.
+- Merged lot comes back with `readableId: null` → stale isolate (the builder
+ inherits the first parent's number). Reload and retry.
+- `{}` empty response with 200 → look at
+ `docker logs carbon-carbon-edge-runtime-1` — the error is server-side.
diff --git a/.ai/research/batch-aggregated-material-consumption.md b/.ai/research/batch-aggregated-material-consumption.md
new file mode 100644
index 0000000000..7e86956cc8
--- /dev/null
+++ b/.ai/research/batch-aggregated-material-consumption.md
@@ -0,0 +1,211 @@
+# Batch Aggregated Material Consumption Research: Best Practices Survey
+
+> Researched: 2026-09-15 · Prompted by: vertical-farming customer use cases
+> (`Work_Order_Stitching_Use_Cases.pdf` + the harvest-merge cases) — "pick the
+> material ONCE for a batch run spanning N jobs" (64 ml chemical, 6,500 seeds, 2 tray
+> lots) instead of N per-job issues.
+> Complements: `.ai/research/job-operation-batching.md` (composition/costing — its §5
+> established "consumption follows each order's own BOM") and
+> `.ai/research/batch-output-lot-identity.md` (2026-08-27 — the OUTPUT-lot half of the
+> same customer ask; single shared output lot = same-material, deliberate-act special
+> case). This file covers only the INPUT side: the aggregated pick/issue.
+
+## Summary
+
+Surveyed SAP (PP-PI campaigns, collective orders, Mill Order Combination, SAP DM
+process lots, EWM cross-order staging, batch where-used), Fulcrum, Steelhead,
+nesting write-back (SigmaNEST/ProNest), process ERPs (BatchMaster, Deacom, Aptean
+Ross), and pharma campaign weighing. Every system that supports cross-order runs
+converges on one model: **the physical pick is aggregated at the run-level entity
+(work order / load / nest / campaign / combined order), while per-member attribution
+is derived** — either as per-order ledger postings from the shared pick (SAP EWM
+staging, pharma campaign weighing) or as a costing/settlement-time allocation
+(Fulcrum bounding-box, SAP MILL_OC quantity distribution). No system makes the
+operator perform N picks, and no system loses per-order lot genealogy: one input
+batch consumed by N orders is recorded as N consumption postings referencing the
+same batch number. SAP's *default* (PP-PI campaign) aggregates only fixed
+setup/clean-out costs and keeps variable consumption per order; its true
+aggregate-then-split pattern (MILL_OC) exists but does it on a synthetic combined
+order settled back to the originals — the shape Carbon's spec already rejected
+(jobs are never merged).
+
+## Competitors Surveyed
+
+- **SAP** (PP-PI production campaigns, collective orders, Mill Order Combination /
+ Combined Production Orders, SAP DM process lots, EWM cross-order staging) —
+ enterprise reference; MILL_OC is the closest analog to combining N orders into
+ one execution
+- **Fulcrum** — job-shop MES; its grouped work orders "pick once" with automatic
+ cost allocation is the strongest direct match for the ask
+- **Steelhead Technologies** — plating MES; racks/loads span orders and customers
+ daily; consumables consumed at tank/load level
+- **SigmaNEST / ProNest** — nesting write-back: the program owns the sheet issue
+- **BatchMaster / Deacom / Aptean Ross** — process-manufacturing ERPs (campaign /
+ super batch concepts)
+- **Pharma MES (BatchLine, LZ Lifescience)** — "campaign weighing/dispensing", the
+ cleanest process-industry analog for the aggregated seed/chemical pick
+
+## Key Consensus Patterns
+
+### 1. One physical pick, owned by the run-level entity
+
+- **Fulcrum**: "Material items will now be picked once to the work order, creating
+ a single clean pick transaction."
+- **SAP EWM cross-order staging**: open quantities of multiple Production Material
+ Requests are summed into one consolidated requirement and staged to the
+ Production Supply Area in one picking stream.
+- **Pharma campaign weighing**: select the material once, list the batches that
+ need it, weigh for all of them in one session.
+- **SigmaNEST/ProNest**: the whole sheet is issued to the nest program; remnants
+ return to inventory.
+- **Rationale**: the operator's action mirrors the physical act — one lot comes off
+ the shelf once.
+
+### 2. Attribution back to members is derived, and the ledger stays per order in the mainstream pattern
+
+- **SAP EWM staging**: consumption (261 goods issue) still posts **per order**
+ against each order's reservation, from the shared staged stock. Aggregate the
+ pick, keep the ledger per order.
+- **Pharma campaign weighing**: each batch's quantity is recorded separately in the
+ session, so genealogy stays per batch.
+- **Fulcrum**: the single pick transaction is allocated across jobs **at costing
+ time**, proportional to each job's bounding box (per-item "lock" for fixed
+ quantities).
+- **SAP MILL_OC**: goods issue posts once against the synthetic combined order;
+ costs settle back to the original orders via Quantity Distribution at final
+ confirmation (exit-overridable ratios).
+- **Rationale**: per-order costing and genealogy are non-negotiable; only the
+ *when* of the split differs (issue time vs costing/settlement time).
+
+### 3. SAP's default aggregates fixed costs only, never variable consumption
+
+- **PP-PI campaigns** are a scheduling/costing bracket: member process orders keep
+ their own reservations and their own goods issues. Dedicated setup/clean-out
+ orders distribute **fixed** campaign costs across members by rule; variable
+ material cost is never aggregated.
+- **SAP DM process lots** group SFCs for collective Start/Complete, but component
+ consumption is recorded per SFC and flows back per each SFC's own order.
+- **Rationale**: aggregation is an execution/UI convenience; the accounting model
+ stays per order unless you opt into the synthetic-order pattern (MILL_OC).
+
+### 4. Lot genealogy: N postings referencing the same input batch
+
+- **SAP batch where-used (MB56)**: one batch consumed by N orders = N material
+ documents, same batch number, each with its own order; the where-used tree just
+ shows N branches. Granularity is order-level.
+- **BatchMaster**: lots allocated per batch job by expiry/rotation → per-batch
+ genealogy.
+- **Rationale**: "one physical movement" and "N traceability records" are not in
+ tension anywhere in the industry.
+
+## Answers to Research Questions
+
+1. **One aggregated issue split system-side, or N issues?** — Mainstream (SAP EWM
+ staging, pharma, SAP DM): aggregate the *pick*, post *per-order* consumption.
+ Aggregate-transaction-with-derived-allocation exists (Fulcrum, SAP MILL_OC) but
+ Fulcrum defers the split to costing and MILL_OC needs a synthetic order.
+2. **How does the operator experience it?** — One action: one pick line for the
+ summed quantity (Fulcrum "one fell swoop"; campaign weighing session; EWM
+ consolidated warehouse task). Never N repeated picks.
+3. **Can staging aggregate multiple orders into one pick list?** — Yes: SAP EWM
+ cross-order staging is purpose-built for it; stock staged non-order-bound to the
+ PSA, consumed per order later.
+4. **How is one input lot attributed to N orders?** — N consumption postings
+ referencing the same batch/lot id (SAP MB56 pattern); genealogy per member.
+5. **Cost attribution for aggregated consumption?** — Three SAP tiers: default
+ per-order BOM issue (no split needed); MILL_OC ratio distribution at settlement;
+ product cost collector (abandons per-order). Fulcrum: proportional (area) with
+ per-item fixed-quantity lock. Nesting: actual per-part usage written back.
+6. **Terminology?** — "pick to the work order" (Fulcrum), "campaign
+ weighing/dispensing" (pharma), "cross-order staging" (SAP EWM), "combined order
+ / quantity distribution" (SAP MILL_OC), "campaign / super batch" (BatchMaster).
+ No vendor calls it "kitting" or "staging" for the multi-order pick itself.
+
+## Competitor-Specific Details
+
+### SAP
+- **MILL_OC / Combined Production Orders** (mill products; now S/4HANA Cloud):
+ components of the originals are *copied* to the combined order with the
+ fixed-quantity indicator (not re-exploded); confirmation + GI post once on the
+ combined order; GR posts per original order via explicit Quantity Distribution;
+ settlement pushes collected costs back by that distribution; customer exits
+ override ratios. The full aggregate-then-split machine — at the cost of a
+ synthetic order.
+- **Collective orders** are vertical (parent/sub-assembly), not sibling batching.
+- **PP kanban + product cost collector**: consumption posts to a period cost
+ collector, never per order — the "give up attribution" end of the spectrum.
+
+### Fulcrum
+- The batching entity is the Work Order (groups jobs); it owns the pick; job
+ costing allocates the pick's value by nested bounding-box area; a per-item lock
+ fixes quantities instead. Labor is tracked once against the group and
+ apportioned the same way (matches Carbon's time-slice design).
+
+### Steelhead
+- Consumables consumed against tank/inventory item (weigh or QR scan), woven into
+ job costing and surcharge invoicing downstream. Exact per-load allocation model
+ not publicly documented.
+
+### Process ERPs / pharma
+- BatchMaster: campaign / super batch / sub-batch across lines; manual or
+ backflushed consumption from formulas per batch job. Deacom/Aptean Ross:
+ batch-centric genealogy; aggregated-issue transaction shape not publicly
+ documented. Pharma campaign weighing: one weighing session, per-batch records.
+
+## Recommended Approach for Carbon
+
+1. **Aggregate the pick, keep the ledger per member** (SAP EWM staging / pharma
+ campaign-weighing pattern, not Fulcrum's costing-time allocation). In MES batch
+ mode, load materials for the whole batch (all member ops), group by item, show
+ the summed requirement; one operator action issues/picks, and under the hood
+ Carbon posts the existing per-member consumptions (`trackedEntitiesToOperation`
+ / per-member `issue`) referencing the same lot. Zero changes to costing, GL, or
+ traceability — the same "materialize per member, no downstream special-casing"
+ principle as the time-slice design.
+2. **Split basis: each member's own BOM quantity** (SAP default), not a
+ proportional share of a total — each `jobMaterial.estimatedQuantity` already
+ defines the member's requirement; the aggregate is just their sum (the
+ customer's own examples are plain sums: 32+32=64, 4,000+2,500=6,500).
+3. **Do NOT adopt the synthetic combined order** (MILL_OC / customer's "Case A"):
+ it re-introduces order merging, which the batching spec and the lot-identity
+ research both reject; every system that aggregates the *transaction* pays for
+ it with a shadow order or deferred allocation.
+4. **Genealogy needs nothing new**: N `trackedActivity` consumptions referencing
+ one input `trackedEntity` is already the industry-standard shape (MB56).
+5. **Naming**: plain "batch picking" / "batch material issue" in UI copy; reserve
+ "campaign" (SAP PP-PI) — it means a scheduling bracket, not a pick.
+
+## Sources
+
+- https://help.sap.com/docs/SAP_ERP/698b19fa88b846359bc611f11184c810/6f80bf53f106b44ce10000000a174cb4.html (PP-PI production campaign)
+- https://answers.sap.com/questions/12535983/setup-and-clean-out-orders-in-production-campaigns.html
+- http://saphelp.ucc.ovgu.de/NW750/EN/3a/81bf53f106b44ce10000000a174cb4/content.htm (setup/clean-out orders)
+- https://help.sap.com/docs/SAP_S4HANA_CLOUD/4032610758dc437089f0c28320eec93f/09ccd8530439414de10000000a174cb4.html (collective orders)
+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-members/combined-production-order-processing-dimp/ba-p/13266644 (MILL_OC)
+- https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/34de0103497c4b80a7c7fbf6952ff971/19cfc353b677b44ce10000000a174cb4.html (components in a combined order)
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/confirmation-of-combined-orders-in-mill-oc/qaq-p/14273736
+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-sap/combined-production-orders-in-sap-s-4hana-cloud-public-edition/ba-p/14397369
+- https://community.sap.com/t5/product-lifecycle-management-blog-posts-by-sap/configure-and-use-process-lots-in-sap-digital-manufacturing/ba-p/13553892 (SAP DM process lots)
+- https://help.sap.com/docs/sap-digital-manufacturing/apis/process-lot
+- https://community.sap.com/t5/supply-chain-management-blog-posts-by-sap/staging-to-production-in-sap-extended-warehouse-management-overview/ba-p/13514770
+- https://www.saplogisticsexpert.com/mastering-cross-order-staging-in-sap-ewm-a-comprehensive-guide-to-production-supply-optimization/
+- https://help.sap.com/docs/SAP_EXTENDED_WAREHOUSE_MANAGEMENT/3d97bec9bf1649099384bb8167df3cf2/019deb535cbb5d1ee10000000a441470.html (staging for production)
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/traceability-with-mb56/qaq-p/3294080 (batch where-used)
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/mb56-batch-where-used-list-components-used/qaq-p/5790159
+- https://fulcrumpro.com/product-updates?ddcf7c2e_page=11 (pick-once / bounding-box allocation)
+- https://fulcrumpro.com/article/streamline-production-with-work-orders-in-fulcrum
+- https://fulcrumpro.com/manufacturing-software/grouped-work-and-nesting
+- https://fulcrumpro.com/article/product-showcase-video-using-materials-for-remnant-tracking-quoting-purchasing-and-nesting-in-fulcrum
+- https://gosteelhead.com/resource-library/managing-inventory-metal-finishing-steelhead
+- https://finishingandcoating.com/index.php/new-technology/2380-using-software-in-barrel-plating-to-improve-efficiencies
+- https://gosteelhead.com/chemical-processing
+- https://www.sigmanest.com/nesting-software/work-order-basics/
+- https://mecadmfg.co.za/how-sigmanest-streamlines-material-management-and-inventory-control/
+- https://mecadmfg.co.za/3509-2/ (remnant write-back)
+- https://www.hypertherm.com/products/software/pronest-erp-mrp-integration/
+- https://www.batchmaster.com/erp-for-food-manufacturing/
+- https://www.top10erp.org/products/batchmaster-manufacturing/production-management
+- https://www.ecisolutions.com/products/deacom-erp-software/batch-manufacturing-software/
+- https://www.aptean.com/en-US/solutions/erp/products/ross-process-manufacturing-erp
+- https://batchline.com/simplify-your-pharmaceutical-weighing-operations-with-batchline/ (campaign weighing)
+- https://www.lzlifescience.com/solutions/weigh-dispense/
diff --git a/.ai/specs/2026-09-16-batch-materials-and-output-lots.md b/.ai/specs/2026-09-16-batch-materials-and-output-lots.md
new file mode 100644
index 0000000000..8bc26e0728
--- /dev/null
+++ b/.ai/specs/2026-09-16-batch-materials-and-output-lots.md
@@ -0,0 +1,346 @@
+# Batch Materials & Output Lots
+
+> Status: implemented
+> Author: Claude (with Sid)
+> Date: 2026-09-16
+> Research: `.ai/research/batch-aggregated-material-consumption.md` (2026-09-15, input side) +
+> `.ai/research/batch-output-lot-identity.md` (2026-08-27, output side) +
+> `.ai/research/job-operation-batching.md` (composition/costing)
+> Builds on: `.ai/specs/2026-08-21-job-operation-batching.md` (shipped, #1550) and
+> `.ai/specs/2026-08-04-batch-split-identity-flip.md` (shipped — the `"Merge"` activity
+> and `Batch Split` ledger patterns this spec reuses)
+> Customer driver: Work Order Stitching use cases (treatment prep / sowing / harvest) —
+> "one physical action = one pick and one output batch", Case B of the customer's
+> harvest-merge proposal (single shared run, per-job lots, merged after)
+
+## TLDR
+
+Operation batching runs N job operations as one run, but the inventory story is still
+per member: N material picks where one lot left the shelf once, and no tracked output
+at all (batch mode disables tracked activity wholesale). This spec closes both halves:
+(1) a **shared material pick** — the batch shows one summed material list, the operator
+picks once, and the system records each member's own consumption from that lot;
+(2) **output lots at batch completion** — one lot per member for batch-tracked produced
+items, created on the completion screen; (3) a **lot merge** — a one-click prompt after
+completion (and a batch-detail action) that combines same-item output lots into a single
+lot with genealogy to every source job; and (4) a **produced-item compatibility rule**
+so a process can require members to make the same item before they group. Jobs are
+never merged; costing and genealogy stay per job throughout.
+
+Industry grounding (research): aggregate the physical pick at the run, keep the ledger
+per order (SAP EWM cross-order staging, pharma campaign weighing, Fulcrum pick-once);
+a literal shared output lot is a deliberate same-item act layered on per-order lots —
+which is exactly what the merge step is.
+
+## Problem Statement
+
+Two jobs, same crop, harvested in one batched run:
+
+- **Input:** the batch's materials are loaded per member (`getJobMaterialsByOperationId`,
+ `apps/mes/app/routes/x+/operation.$operationId.tsx:242`) and lot-tracked material is
+ picked per operation (`issue` case `trackedEntitiesToOperation`). The operator picks
+ the same seed lot twice: once for 4,000, once for 2,500 — two picks for one physical
+ scoop of 6,500. Untracked materials backflush per member (`issue` case
+ `jobOperation`), which is correct but invisible as a combined requirement.
+- **Output:** batch mode passes `isTrackedActivity={!isBatched && …}`
+ (`apps/mes/app/components/JobOperation/JobOperation.tsx:2501`), so a batch-tracked
+ produced item cannot be completed through a batch at all — `BatchCompleteModal`
+ records quantities only. The customer's "one output batch of 3 kg" is unreachable.
+- **Eligibility:** `BATCH_RULE_DIMENSIONS` covers the consumed BOM line's item and
+ material properties, but not the **produced** item — "same output" cannot be required.
+
+## Proposed Solution
+
+Four additions, all on top of the shipped batching feature. Nothing changes for
+unbatched operations or for batches of untracked items beyond a display improvement.
+
+### 1. Shared material pick (MES batch mode)
+
+- The batch-mode materials panel loads materials for **all members** (new
+ `getJobMaterialsByBatchId`), grouped by item with summed required/issued quantities.
+ Per-member rows expand under each item group.
+- **Untracked items: display-only aggregation.** Consumption keeps backflushing per
+ member at completion Phase 2 — no new issue path, no double-issue risk.
+- **Batch-tracked items: one pick action per source lot.** The existing pick modal, in
+ batch mode, submits a new `issue` case `trackedEntitiesToBatch`
+ `{ batchId, parentTrackedEntityId, children: [{trackedEntityId, quantity}], … }`.
+ In one transaction the function reads each member's **remaining** requirement for
+ that item and splits the picked quantity **pro-rata by remaining requirement**, using
+ `distributeRoundingResidual` so member shares sum exactly to the picked quantity.
+ It then performs the same per-member writes `trackedEntitiesToOperation` performs
+ today (consumption records, activity attribution, ledger rows) — N records, one
+ operator action, same downstream costing and genealogy as N manual picks.
+- Multi-lot picks are N invocations of the same case (one per source lot); because each
+ split is pro-rata by remaining requirement, every member is linked to every lot it
+ physically consumed from — recall traceability is complete.
+
+### 2. Output lots at batch completion
+
+- For members whose produced item `requiresBatchTracking`, `BatchCompleteModal` gains a
+ per-member batch-number field (pre-filled from the tracking sequence, editable),
+ alongside the existing per-member quantity field.
+- Batch completion Phase 2 finalizes each member's output entity via a new lean `issue`
+ case `jobOperationBatchOutput` (per member, the member's own WIP `trackedEntityId`):
+ the `Produce` activity + `Available` flip extracted from `jobOperationBatchComplete`,
+ WITHOUT that case's `productionQuantity` insert (Phase 1 already recorded it) and
+ WITHOUT its backflush (Phase 2's issue step already ran). Inserted between the
+ material-issue step and the Done flip, idempotent like its neighbors (skip members
+ whose entity is already `Available` — resume-safe).
+- Serial-tracked members are **out of scope**: they keep today's behavior exactly
+ (quantities only, no tracked activity in batch mode). Eligibility is unchanged.
+
+### 3. Lot merge
+
+- New `issue` case `mergeTrackedEntities` `{ trackedEntityIds (min 2), companyId, userId }`:
+ - All parents must be the same item, `Available` status, and same company/location.
+ - Creates ONE new entity: summed quantity, fresh id, new batch number,
+ `expirationDate` = **earliest** parent expiry, properties kept only where all
+ parents agree.
+ - Genealogy: one `trackedActivity` `type: "Merge"` — inputs = each parent at its
+ quantity, output = the merged entity (the type already exists:
+ `packages/database/supabase/functions/shared/batch-split.ts:252`).
+ - Ledger: net-zero `Batch Merge` rows at the parents' resolved bin (−q per parent,
+ +Σq merged), mirroring `Batch Split`'s shape. Parents become `Consumed`.
+- **Completion prompt (the customer's banner):** after a batch completes with ≥2
+ same-item output lots, the MES completion flow offers "N lots of the same item —
+ merge into one?" One click invokes the merge. The same action appears on the ERP
+ batch detail drawer for completed batches with unmerged same-item outputs.
+- Auto-merge (no click) is deliberately **deferred**: a wrong automatic merge needs a
+ split to undo; a click does not. Revisit as a `process` setting once the banner flow
+ has real usage.
+
+### 4. Produced-item compatibility rule
+
+- `producedItem` joins `BATCH_RULE_DIMENSIONS` (`shared/batch-compatibility.ts`),
+ default `"ignore"` so every existing process behaves byte-for-byte as before.
+- `must`/`guide`/`ignore` semantics identical to the existing dimensions: enforced
+ client-side in the builder and server-side in the edge fn's compatibility gate, on
+ create + add; `guide` splits suggestion groups.
+- The process form's "Compatibility rules" card gains the row.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Pick aggregation model | Aggregate the PICK, keep the LEDGER per member — never one consumption row split at costing time | Research consensus (SAP EWM cross-order staging, pharma campaign weighing); zero changes to costing, GL, or traceability, same principle as the shipped time-slice design |
+| Member split basis | Each member's own remaining BOM requirement; `distributeRoundingResidual` for exact sums | The aggregate is just the sum of per-member requirements (customer math: 4,000+2,500=6,500); precision rule forbids independent rounding |
+| Multi-lot attribution | Pro-rata by remaining requirement per pick — every member links to every lot it drew from | Sid 2026-09-16. Physically honest for blended preps; sequential fill under-links recalls |
+| Fan-out ownership | New `issue` case `trackedEntitiesToBatch`, one Kysely transaction | A client-side loop of N invokes is not transactional; `issue` already owns every consumption shape |
+| Tracked scope v1 | Batch-tracked + untracked only; serial-tracked members unchanged, eligibility untouched | Sid 2026-09-16. Serial per-unit identity inside batch completion is real work with no customer driver; changing shipped eligibility could strand existing users' batches |
+| Untracked materials | Display-only aggregation; backflush at completion unchanged | Sid 2026-09-16. Manual early issue would duplicate backflush and invite double-issue |
+| Output lot shape | One lot PER MEMBER at completion, then merge — never one lot written directly across jobs | Case B (customer-agreed). Per-member lots are what per-job genealogy requires; the 08-27 research shows direct shared lots destroy per-order identity everywhere they exist |
+| Output creation path | New lean `issue` case `jobOperationBatchOutput` per member (the `Produce` activity + entity flip EXTRACTED from `jobOperationBatchComplete`), inside completion Phase 2, idempotent | The shipped case also inserts a `productionQuantity` row and backflushes materials (`issue/index.ts:1180`) — both already owned by batch completion Phase 1/2; calling it verbatim would double-count. Extracting keeps one source of truth for the Produce write |
+| Merge mechanism | New `issue` case `mergeTrackedEntities`; `trackedActivity` `type: "Merge"`; net-zero `Batch Merge` ledger rows; parents → `Consumed` | Mirrors the shipped `Batch Split` pattern in reverse; `"Merge"` activity type already exists from merge-on-return |
+| Merged lot identity | New entity, fresh id, NEW batch number | Matches the customer's own `-M` diagram, the split precedent (children get new ids), and the industry "deliberate act" framing |
+| Merge conflict policy | Same item required; expiry = earliest parent; properties kept only where all parents agree | Sid 2026-09-16. Conservative and standard; blocking on hour-level expiry differences would kill the one-click flow |
+| Merge surfaces | MES post-completion prompt + ERP batch detail drawer action; generic inventory-wide merge UI deferred | The feature's own surfaces; a generic merge tool is scope creep until someone asks |
+| Auto-merge | Deferred (future `process` setting) | Sid: undoing a wrong merge needs a split; a click is cheap. Validate the banner first |
+| `producedItem` rule default | `"ignore"` | Same rule as every dimension added so far: an unconfigured process behaves byte-for-byte as before |
+| Multi-tenancy | No new tables. New `issue` cases validate every record id under `companyId`; merge validates all parents share it | Heuristics 1/4; edge-fn rule: payload ids re-read under companyId |
+| Service shape | `(client, …) → {data, error}` wrappers in `production.service.ts` (batch materials) and `inventory.service.ts` (merge); mutations via `issue` edge fn | Heuristics 2/6; one service/models per module |
+| RLS / permissions | No new tables → no new policies. `trackedEntitiesToBatch` requires `update: "production"`; `mergeTrackedEntities` requires `update: "inventory"` | Matches the surfaces that invoke them (MES batch page; inventory lot action) |
+| Form pattern | `BatchCompleteModal` stays `ValidatedForm` + zod (batch-number fields join the member array); merge prompt is a plain action button (no user input) | Heuristic 5; a confirm with zero fields needs no form machinery |
+| Backward compatibility | No frozen surface touched. One additive enum migration (`Batch Merge`). Unbatched ops, untracked batches, serial members: byte-for-byte unchanged | Heuristic 7 |
+
+## Data Model Changes
+
+No new tables. One additive migration:
+
+```sql
+-- Merge ledger rows, mirroring 'Batch Split' (20250225145619, 20260504000000)
+ALTER TYPE "itemLedgerDocumentType" ADD VALUE IF NOT EXISTS 'Batch Merge';
+ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Batch Merge';
+```
+
+`process.batchRules` is sparse JSONB — `producedItem` needs no migration.
+`trackedActivity.type` is TEXT — `"Merge"` is already written by merge-on-return.
+After the migration: `pnpm run generate:types` before typecheck.
+
+## API / Service Changes
+
+### `issue` edge function — two new cases
+
+- `trackedEntitiesToBatch` `{ batchId, parentTrackedEntityId, children: [{trackedEntityId, quantity}], overrideExpired?, overrideReason?, companyId, userId }`
+ — permission `update: "production"`. One transaction: load the batch's member
+ operations + their `jobMaterial` rows for the parent entity's item; compute each
+ member's remaining requirement; split each child draw pro-rata with
+ `distributeRoundingResidual`; per member, perform the same writes as
+ `trackedEntitiesToOperation` (reusing its internals, extracted if needed — no
+ copy-paste). Rejects a batch with no member requiring that item, and a batch that is
+ `Completed`.
+- `mergeTrackedEntities` `{ trackedEntityIds (min 2), companyId, userId }` — permission
+ `update: "inventory"`. Validates same item / same company / `Available`; creates the
+ merged entity (fresh id, new batch number via the tracking sequence, earliest expiry,
+ agreed properties); writes the `Merge` activity (inputs = parents, output = merged);
+ net-zero `Batch Merge` ledger rows at the resolved bin
+ (`resolveTrackedEntityBin` — see `.ai/lessons.md` "actual bin"); parents `Consumed`.
+ Returns `{ trackedEntityId }`.
+
+### `batch-operations` edge function
+
+- `complete` Phase 2: after material issue, before the Done flip — for each member
+ whose produced item `requiresBatchTracking`, invoke `issue`
+ `jobOperationBatchComplete` with that member's submitted batch number/quantity.
+ Idempotent: skip members whose output entity already exists. Payload's member rows
+ gain optional `batchNumber`.
+- Completion result gains `outputTrackedEntityIds` so the MES route can offer the
+ merge prompt without a refetch.
+
+### Services
+
+- `production.service.ts` (ERP) + MES services: `getJobMaterialsByBatchId(client, { batchId, companyId })`
+ — member materials grouped for the batch panel.
+- `inventory.service.ts`: `mergeTrackedEntities(client, payload)` → invoke wrapper.
+- `production.models.ts` / MES `models.ts`: completion validator member rows gain
+ optional `batchNumber`; merge payload validator.
+- `shared/batch-compatibility.ts` (+ `@carbon/utils` re-export): `producedItem` in
+ `BATCH_RULE_DIMENSIONS`, `DEFAULT_BATCH_RULES.producedItem = "ignore"`, value-set
+ fold extended; `batch-builder-logic.ts` signature/facets updated symmetrically.
+
+## UI Changes
+
+| Surface | Change |
+|---------|--------|
+| MES operation page, batch mode | Materials panel switches to the batch-wide list: item groups with summed required/issued, member rows expanded beneath; pick modal submits `trackedEntitiesToBatch`; per-item progress reflects all members |
+| `BatchCompleteModal` (MES) | Per-member batch-number field (pre-filled, editable) for members with batch-tracked output; hidden otherwise. On success with ≥2 same-item output lots: merge prompt — "N lots of the same item — merge into one?" with the new lot's number shown after |
+| ERP batch detail drawer (`BatchDetailDrawer`) | For a `Completed` batch with unmerged same-item output lots: "Merge output lots" action; after merge, shows the merged lot's readable id linking to traceability |
+| Process form, "Compatibility rules" card | New "Produced item" row with the standard Require Match / Suggest Match / Ignore choices |
+| Batch builder | `producedItem` participates in signatures/facets exactly like existing dimensions when its rule is not `ignore` |
+
+All new strings via lingui (`<Trans>`/`t`) in both apps; `/translate` after.
+
+## Acceptance Criteria
+
+- [ ] A batch of 2 members (BOM 4,000 + 2,500 of the same batch-tracked seed item) shows one materials row "6,500" with both member rows beneath; one pick of 6,500 from lot L1 records 4,000 to member 1 and 2,500 to member 2, both referencing L1; each job's cost carries only its own share; the lot's where-used shows both jobs.
+- [ ] Picking 4,000 from L1 then 2,500 from L2 (two invocations) links BOTH members to BOTH lots pro-rata by remaining requirement, and per-member totals still sum exactly to 4,000/2,500 (`distributeRoundingResidual` — no drift at 5-decimal scale).
+- [ ] A pick exceeding the batch's remaining requirement for that item is rejected with a specific error; a pick against a `Completed` batch is rejected.
+- [ ] Untracked materials appear in the batch materials list with summed quantities but no pick action; completion still backflushes them per member exactly as before (ledger rows identical to pre-feature behavior).
+- [ ] Completing a batch whose members produce a batch-tracked item creates one output entity per member with the entered batch numbers and quantities; a Phase-2 failure after output creation resumes without duplicating entities.
+- [ ] After completion with 2 same-item output lots, the merge prompt appears; one click yields ONE new entity (summed quantity, new batch number, earliest parent expiry), a `Merge` activity with both parents as inputs, net-zero `Batch Merge` ledger rows, parents `Consumed`; the traceability graph walks merged lot → both jobs → their inputs.
+- [ ] Merging entities of different items is rejected server-side with a specific error; the prompt never offers it.
+- [ ] Serial-tracked members batch and complete exactly as today (no batch-number field, no entities, no eligibility change).
+- [ ] A process with `producedItem: "must"` refuses (client and server) a batch mixing produced items; `"guide"` splits suggestion groups; an unconfigured process's suggestions and gates are byte-for-byte unchanged.
+- [ ] `pnpm exec turbo run typecheck --filter=erp --filter=mes`, lint, and unit tests green; new tests: pro-rata split (exact sums, multi-lot), merge validation + conflict policy, compatibility fold with `producedItem`.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Pro-rata split drifts against member BOM totals across many partial picks | Med | Split by REMAINING requirement each pick + `distributeRoundingResidual`; unit test the multi-pick sequence to exact sums |
+| Double consumption if `trackedEntitiesToBatch` and a member-level manual pick race | Med | Both paths read remaining requirement inside their transaction; the batch case locks the member `jobMaterial` rows (`FOR UPDATE`) |
+| Output-entity creation breaks Phase 2 resume idempotency | Med | Existence check per member before create, same pattern as the backflush cap and `postedToGL` skip; covered by a resume test |
+| Merged lot hides a parent-specific quality signal | Low | Deliberate and customer-chosen: genealogy keeps both parents one hop away; earliest-expiry policy is conservative |
+| `producedItem` rule reshuffles existing suggestion groups | Low | Default `"ignore"` reproduces current signatures exactly; pinned by the compatibility fold test |
+| Enum migration ordering vs generated types | Low | Standard flow: migrate → `pnpm run generate:types` → typecheck |
+
+## Open Questions
+
+> All resolved 2026-09-16 with Sid before this spec was written; the customer's
+> proposals (harvest-merge cases) and follow-ups resolved the output-side questions.
+
+- [x] **Multi-lot pick: how are lots attributed to members?** — **Answer:** pro-rata by
+ remaining requirement per pick — every member links to every lot it drew from.
+ Sequential fill rejected: under-links recalls for physically blended preps.
+- [x] **Serial-tracked members?** — **Answer:** out of scope v1; behavior and
+ eligibility unchanged. Including serial (per-unit assignment) rejected for v1 scope;
+ blocking serial from batching rejected as a regression to shipped behavior.
+- [x] **Merge policy on conflicting expiry/properties?** — **Answer:** allow; earliest
+ parent expiry wins; properties kept only where parents agree; same item always
+ required. Blocking on mismatch rejected: hour-level differences would defeat the
+ one-click flow.
+- [x] **Untracked materials in the batch panel?** — **Answer:** display-only
+ aggregation; backflush unchanged. Aggregated manual issue rejected: duplicates
+ backflush, double-issue risk.
+- [x] **Output: one shared lot written directly, or per-member lots merged?** —
+ **Answer:** per-member lots + merge (customer's Case B, agreed by the customer);
+ direct shared lot (Case A / merged jobs) rejected — severs per-job cost and history,
+ contradicts both research files.
+- [x] **Output quantity split: coefficient or per-member entry?** — **Answer:**
+ per-member entry, pre-filled proportionally from planned quantities (customer
+ confirmed; real yields differ per cycle — 45/44 kg — so a fixed % would fabricate
+ yields). Time/cost remains the shipped proportional split.
+- [x] **Auto-merge without the click?** — **Answer:** deferred; candidate `process`
+ setting after the banner flow sees real usage (a wrong auto-merge needs a split to
+ undo).
+
+## Changelog
+
+- 2026-09-18 (Sid): releasing a batch releases its Draft/Planned member jobs
+ through the job page's own path (`releaseJobs`: recalc, MRP, Ready,
+ outside-operation POs, releasedDate), after validating every one
+ (`getJobReleaseReadiness`: assemblies without operations, manufacturing
+ blocked). Decisions: an invalid member job blocks the WHOLE batch; the
+ Release dialog chooses a PO per supplier once for all jobs (a supplier's
+ first new PO is reused, so a batch lands on one PO per supplier); bulk
+ release has no dialog, so it releases clean batches and skips — naming —
+ any that need a fix or have Draft POs to choose from. The job Release route
+ now re-checks missing operations server-side (previously browser-only).
+ Open: the job dialog's "Missing Suppliers" check never fires (outside
+ operations without a supplier are silently skipped, not blocked) — left
+ as shipped pending a decision.
+
+- 2026-09-18 (Sid): lot identity moves from the floor to planning. The batch
+ builder's Output section sets each member's lot (written to its WIP
+ trackedEntity.readableId at create) or, when every member makes the same
+ batch-tracked item, one combined lot (`jobOperationBatch.mergeOutput` +
+ `outputLotNumber`, 20260918094217). The MES completion modal loses its
+ editable Batch Number column (read-only Lot column / "All output goes to lot
+ X"), and the completion route merges only planned-merge batches. Supersedes
+ the "batch number IS the merge intent" entry below. MES also gains a Batch |
+ job scope switch: the batch view aggregates completion, materials (one pick
+ per material, per-job split) and output across members. Not built: editing
+ the lot plan on an existing batch's drawer.
+
+- 2026-09-16 (live-test follow-up, Sid): completing a batch now completes its
+ Draft/Planned member jobs (sync_finish_job_operation admits them when the
+ Done op carries a jobOperationBatchId — 20260916155634). Their receipts post
+ before the route's merge, so a merged lot's on-hand equals its combined
+ quantity immediately. Supersedes the earlier "keep manual, surface it" call;
+ the drawer nudge remains for members with operations still open.
+
+- 2026-09-16 (UX simplification, Sid): the post-completion merge prompt is
+ gone. The batch number is the merge intent — members completed under one
+ number (same item) merge at completion, confirmed inline in the Complete
+ Batch form; one number across different items is refused (client block +
+ server pre-check) so duplicate lot numbers are never minted. BatchMergePrompt
+ deleted; route merges via getOutputLotMergeGroups after completion; the
+ drawer's "Merge output lots" remains for lots kept separate.
+
+- 2026-09-16 (post-ship, user-found): the merge's net-zero ledger rows assumed
+ every parent was already received into stock. Merging at batch completion
+ (before member job receipts) subtracted unreceived quantity and stranded the
+ remaining jobs' receipts ("Tracked entity not found" — the job's lot was
+ Consumed). Redesigned identity-only: merge ledger rows are sized by each
+ parent's on-ledger balance (none when unreceived), and
+ complete_job_to_inventory resolves through Merge activities so each member
+ job's receipt posts against the merged lot
+ (20260916131445_merge-aware-job-receipt.sql).
+
+- 2026-09-16: Created, all questions resolved pre-writing (Sid + customer answers).
+- 2026-09-16: Implemented on `feat/batch-materials-and-output-lots`. Five changes
+ the design did not anticipate, all found by end-to-end testing rather than by
+ typecheck or unit tests:
+ - **Accounting period pre-resolution.** `getCurrentAccountingPeriod` reads over
+ HTTP but writes in-transaction, so N members in ONE pick transaction each
+ tried to create the same missing month and the unique index rolled the whole
+ pick back. Resolved before the transaction opens.
+ - **Merge-prompt fetcher ownership.** Completing the batch is exactly what makes
+ the loader stop passing `batch`, unmounting `BatchCompleteModal` — so a
+ fetcher owned there took the prompt's payload with it and the prompt could
+ never render. `JobOperation` owns the fetcher and renders `BatchMergePrompt`.
+ - **Merged lot identity.** Neither caller passed a `readableId`, so every merged
+ lot landed `Available` with a NULL batch number (unidentifiable on the floor;
+ in real data every `Available` lot has one). It now inherits the FIRST
+ parent's, matching the split child's inheritance, and the edge fn orders
+ parents by the caller's list so "first" is deterministic rather than DB row
+ order.
+ - **Shared-pick default quantity.** The pick modal defaulted to the member's own
+ share, which the pro-rata split then divided again across all members (a 6,500
+ batch requirement picked as 4,000 became 2461.54/1538.46, satisfying neither).
+ Batch mode defaults to the batch's outstanding requirement.
+ - **Merge authorization.** The MES merge action took `trackedEntityIds` from the
+ form and invoked `issue` with the SERVICE ROLE, so the edge fn's `inventory`
+ check validated the service role rather than the operator — a
+ production-only user could merge any two same-item lots in the company. Both
+ entry points now derive the parent ids server-side from the batch's
+ membership (`getMergeableOutputLots`), mirroring the ERP route.
diff --git a/.claude/rules/mes-job-operation-ui.md b/.claude/rules/mes-job-operation-ui.md
index aa27583d69..5660ec5426 100644
--- a/.claude/rules/mes-job-operation-ui.md
+++ b/.claude/rules/mes-job-operation-ui.md
@@ -84,7 +84,38 @@ Progress" has a space). List visibility alone was the leak: nothing else gated
a direct operation URL.
-There is **no separate batch page** — the operation view IS the batch UI. When an
+There is **no separate batch page** — the operation view IS the batch UI. In
+batch mode the job heading is replaced by ONE scope switcher — an outlined
+`rounded-full` pill `(BAT… N jobs | Jobs ⌄)` whose selected segment gets a soft
+`bg-accent` fill; the second segment IS the member-job picker (it reads the
+open job's id in the job scope) — which sets
+`?scope=` between **Batch**
+(default; `BatchOverview`: completed/issued/scrap/output-lot stat cards, one
+materials table from `getBatchMaterialTotals` with the per-job split and a
+batch-wide "Pick N", the steps/parameters/files of every member, and the
+member jobs table — each list in a bordered panel with the DS `Table`) and the member's own job
+details (`?scope=job`, which member links use). The `IssueMaterialModal` is
+mounted in both scopes via `renderIssueModal`. The batch scope shows no member's
+values anywhere: the context bar reads batch status (Released/Completing),
+customers, the batch plan and the earliest member due date; the dock's Item is
+the batch's item (or "N items"); the ⋮ menu offers only the batch list (plus
+Item Master when every member makes the same item). The tabs stay as on a
+single job: Details (`BatchOverview view="details"`: stats, a load list only when parts must be
+kept apart (the jobs make different items, or each job gets its own output lot)
+— each job's quantity to run with due date/customer and a total — materials grouped "To pick" / "Used automatically at completion",
+and files) and Instructions
+(`view="instructions"`: the batch's steps and process parameters); Chat is
+disabled on the batch because notes (`jobOperationNote`) belong to one job
+operation. The job scope
+opens with a banner saying the job runs in the batch — timer and completion are
+shared — with "Back to batch". Work-instruction steps are recorded
+for the whole batch from `BatchRecordModal` — a per-job grid with an "All
+jobs" row that fills every cell (typed cells for Measurement/Value/List/Person,
+ticks for Task/Checkbox/Timestamp, one upload copied into each job's own step
+folder for File/Inspection) posting to `batch.$batchId.record.tsx`
+(`insertBatchStepRecords`: steps re-read under the batch + company, upsert at
+record set 0, then the per-step backflush). Only new or changed rows are sent,
+since a re-record re-runs the step's backflush. When an
operation belongs to a batch that is still `Active`/`Completing`, the loader
(`operation.$operationId.tsx`) reads `jobOperationBatch` (via
`getJobOperationBatch`; the RPC `get_job_operation_by_id` omits
@@ -124,13 +155,21 @@ In batch mode `JobOperation` derives `isBatched = !!batch`,
"0 milliseconds"), and the per-piece header divides the shared elapsed time by
the members' summed `quantityComplete` — a quantity-weighted per-piece rate
consistent with the completion split's `operationQuantity` weights.
-- **Batch chip** — a `DropdownMenu` in the info bar (`BAT… · N jobs`, yellow
- `Completing` badge) lists members as `Link`s to hop between them.
+- **Scope switcher** — the batch segment carries the yellow `Completing`
+ badge; the chevron menu lists members as `Link`s to their `?scope=job` view.
+ "Print batch list" lives in the job's ⋮ menu.
- **Completion** — the "Log Completed" button becomes "Complete Batch" and opens
`BatchCompleteModal`, a **spreadsheet-style grid** (bare `<input inputMode="numeric">`
cells in a bordered `border-separate` table — no react-aria stepper arrows, no
- close-X via `withCloseButton={false}`, Job / Quantity / Scrap columns only —
- the per-member Operation is redundant in a batch). Rows are pre-filled
+ close-X via `withCloseButton={false}`, Job / Quantity / Scrap columns —
+ the per-member Operation is redundant in a batch). **The operator never
+ enters a lot number** — lot identity is planned at batch creation
+ (`jobOperationBatch.mergeOutput` / `outputLotNumber`, or each member's WIP
+ `trackedEntity.readableId`). A merged batch shows a success `Alert` naming
+ the lot; otherwise a read-only **Lot** column lists each member's planned
+ lot, and a tracked member with no planned lot blocks submit with a warning
+ naming the jobs (legacy batches — fix via the job's properties sidebar).
+ Each row still submits a hidden `trackedEntityId`. Rows are pre-filled
`operationQuantity − quantityComplete`, controlled as strings in local state.
Completing a batch **auto-stops** any still-running shared timer: the Phase-1
txn closes open `jobOperationBatchId`-tagged `productionEvent`s with
@@ -144,7 +183,21 @@ In batch mode `JobOperation` derives `isBatched = !!batch`,
"completed with 0" warning: 0 simply means not-in-this-run. All-excluded (every
row 0/0) disables submit. Scrap / Rework /
Finish are hidden in the actions sheet (per-op writes would double-count a
- member); Maintenance + Quality Issue stay. The batch chip menu also offers
+ member); Maintenance + Quality Issue stay.
+- **Planned merge** — when `batch.mergeOutput`, the completion route passes
+ `outputLotNumber` as every member's batch number, then (after completion
+ succeeds) `getPlannedMergeLots` reads the members' Available output lots and
+ invokes `issue` `mergeTrackedEntities` with that readableId. The merge
+ carries **no entity ids from the form** — the route invokes `issue` with the
+ SERVICE ROLE, so a posted id list would let a production-only user merge any
+ two same-item lots. A merge failure leaves the batch completed with
+ per-member lots; the ERP batch drawer's "Merge output lots" is the recovery
+ path. The route returns `data({ completed: true })` + flash, NOT a
+ redirect: the completion's own writes fire `useOperation`'s realtime
+ `revalidate()` mid-action, and React Router drops a fetcher redirect when a
+ newer navigation started after the submit — `JobOperation` navigates to
+ `path.to.operations` when the fetcher settles with `completed`. The job's ⋮
+ menu also offers
"Print batch list" (`path.to.file.batchLoadList` → the ERP
`/file/batch/:id.pdf` route, `BatchListPDF`). The kanban keyboard wedge is
disabled (`active: !!kanban?.id && !isBatched`) — it completes a single op,
@@ -156,11 +209,9 @@ In batch mode `JobOperation` derives `isBatched = !!batch`,
`Tabs`, header/job-info bar, and all detail sections.
- **`JobOperation/components/Controls.tsx`** — exports `Controls`, `Times`,
`WorkTypeToggle`, `StartStopButton`, `IconButtonWithTooltip`, `FloatingActionMenu`,
- `PlayButton`/`PauseButton`. The right/bottom control panel: work center, work-type
+ `PlayButton`/`PauseButton`. The dock / bottom action bar (see Layout): work center, work-type
toggle (Setup/Labor/Machine), big start-stop button, "Log Completed", and a "More
- Actions" sheet (Scrap, Rework, Finish, Maintenance, Quality Issue). Carries
- **mobile-only** job/customer/deadline info in a `md:hidden` block (the header hides
- that info on mobile).
+ Actions" sheet (Scrap, Rework, Finish, Maintenance, Quality Issue).
- **`components/Step.tsx`** — exports `StepsListItem`, **`RecordModal`**, and
**`DeleteStepRecordModal`** (these are NOT separate files). File/Inspection step
uploads go to the private bucket at
@@ -186,7 +237,11 @@ when `parentIsSerial`) Serial Numbers.
`useOperation` subscribes on topic `job-operations:${operation.id}` to postgres changes
on `job`, `productionEvent` (filtered by `jobOperationId`), and `jobOperation`. Event
-inserts/updates/deletes patch local state; job/operation updates `revalidate()`. A
+inserts/updates/deletes patch local state; a job update revalidates through
+`useRealtimeRevalidator` (`~/hooks`), which skips while any fetcher is
+submitting — a submission's own writes echo back mid-action, and a revalidation
+started then makes React Router drop the action's redirect. `AssemblyView`'s
+live sync uses the same hook. A
deleted operation toasts and redirects to `path.to.operations`.
## Key tables (newest migrations)
@@ -208,22 +263,39 @@ Serial Numbers section uses shared `~/components` `PrintButton` with
per-entity (`sourceDocument="Entity"`, `trackedEntityLabel*`). See
`.claude/rules/` printing notes / cache for fallback-to-download behavior.
-## Responsive / CSS gotchas
-
-- CSS vars: **`--controls-width: 220px`** (260px at xl, in `apps/mes/app/styles/tailwind.css`),
- `--controls-height` set inline from a computed `controlsHeight` memo, `--header-height`
- from `@carbon/react`. Details scrollport classes live **inline on the details
- container in `JobOperation.tsx`** (no separate helper):
- - **Below `lg`:** `h-auto` + page scroll — Controls/Times stack inline under content so
- Files / Serial Numbers stay reachable (do **not** put a viewport-filling fixed height
- here; that nested-scroll trap was #959).
- - **`lg+`:** fixed height
- `calc(100dvh - var(--header-height)*2 - var(--controls-height) - 2rem)` with
- `lg:pr-[var(--controls-gutter)]` so absolute Controls/Times dock without overlap.
-- Root Tabs is `min-h-screen h-auto lg:h-screen` for the same reason.
-- Header detail metadata is `hidden lg:flex` (so `Controls` shows it on mobile instead);
- Materials "Source" column is `hidden lg:table-cell`; Procedure steps list is
- `hidden lg:block`; the `Controls` panel is inline on mobile, `lg:absolute` top-right
- on desktop.
-
-<!-- UNVERIFIED: exact column set of jobOperation (status/duration fields) not fully audited here; check the live schema or 20240909194622_jobs.sql + later alters when relying on specific fields. -->
+## Layout (application shell)
+
+The `Tabs` root in `JobOperation.tsx` IS the shell: a CSS grid of named areas,
+each pane scrolling on its own — nothing is absolutely positioned and no height
+is computed in JS (the old `--controls-height` / `--controls-gutter` /
+`calc(100dvh - …)` scheme is gone).
+
+- **Areas.** Below `lg`: one column — `header`, `context`, `sep`, `main`,
+ `status`, `dock`. From `lg`: `main`/`status` on the left, `dock` spanning both
+ on the right (`minmax(0,1fr) auto`). Every TabsContent sits in `main`
+ (inactive ones are `display:none`, so they take no track); `Times` is
+ `status`; `Controls` is `dock`.
+- **Height.** The MES outlet frame (`x+/_layout.tsx`) is only `min-h-svh`
+ bounded because other screens page-scroll, so the shell sizes itself:
+ `h-svh md:h-[calc(100svh-1rem)]` (the frame's `md:my-2` inset). Never
+ `h-screen`/`h-full` here — the first overflowed the inset frame (clipped the
+ status bar), the second resolves to content height.
+- **Dock (`Controls`).** ONE mounted instance — it owns the start/stop form and
+ the modal triggers, so it is re-laid-out by CSS, never rendered twice: a
+ `--controls-width` column from `lg` (collapsible to a 76px rail via
+ `data-collapsed` + `group/dock` variants, persisted per device in
+ localStorage `mes:operation-dock-collapsed`, read after mount), a pinned
+ bottom action bar below `lg` (toggle · start/stop · complete · more). Play/Pause
+ and `IconButtonWithTooltip` size by context (`size-14`/`size-12` in the bar
+ and rail, full size in the dock).
+- **Status bar (`Times`).** A footer row, not a floating card: one meter per
+ planned work type plus quantity. A plan of ≤1ms is the batch no-plan
+ placeholder — it shows elapsed time alone over an empty track (never
+ "0ms/1ms").
+- **Context bar.** Wraps below `lg`; its metadata row (customer, description,
+ status, duration, deadline) scrolls sideways (`scrollbar-hide`, items
+ `shrink-0`) instead of hiding, so there is no mobile-only duplicate in the
+ dock. Header tabs scroll sideways too (`ml-auto` on the list, never
+ `justify-end` on an overflow container — it strands the start).
+- Materials "Source" column stays `hidden lg:table-cell`; Procedure steps list
+ `hidden lg:block`.
diff --git a/.claude/rules/traceability-model.md b/.claude/rules/traceability-model.md
index 3b8ce6257b..82a09218b8 100644
--- a/.claude/rules/traceability-model.md
+++ b/.claude/rules/traceability-model.md
@@ -160,6 +160,24 @@ shared record builder is `functions/shared/batch-split.ts` (`buildBatchSplitReco
`quality-disposition.subdivideBatchEntity`. Serial paths never split. Exception: the
PO-sourced `post-shipment` split posts no `itemLedger` (matches pre-flip behavior).
+**Lot merge (the deliberate inverse; spec `.ai/specs/2026-09-16-batch-materials-and-output-lots.md`):**
+`issue` case `mergeTrackedEntities` combines N **same-item, Available** entities into ONE
+new entity via `buildBatchMergeRecords` (`functions/shared/batch-merge.ts`, the mirror of
+`buildBatchSplitRecords`). Parents keep their quantity as a historical record and flip
+`Consumed`; the merged entity gets a fresh id, the SUMMED quantity, the **earliest** parent
+`expirationDate`, and only those `attributes` every parent agrees on, plus
+`"Merged From Entity IDs"` provenance. It inherits the FIRST parent's `readableId` when the
+caller supplies none — an `Available` lot with a NULL batch number is unidentifiable on the
+floor (the split child inherits `parent.readableId` for the same reason), so callers that
+care about which number wins must pass the parents in their intended order. Genealogy is one
+`trackedActivity` `type: 'Merge'` with an input edge per parent (at its quantity) and one
+output edge for the merged entity; the ledger gets net-zero `Batch Merge` rows (−q at each
+parent's `resolveTrackedEntityBin`, +Σq at the first parent's). Distinct from
+`buildMergeRecords` in `batch-split.ts`, which is the **merge-on-return** of a split child
+back into its own parent — same activity type, different operation. Reached from the MES
+batch-completion prompt and the ERP batch drawer's "Merge output lots"; both derive the
+parent ids server-side from the batch's membership (see `mes-job-operation-ui.md`).
+
**Pick → consume → return lifecycle (batch/serial):** a **pick** (`post-picking`) is an
`itemLedger` Transfer warehouse→lineside (the departing lineside lot is the split CHILD, and
`pickingListLineTrackedEntity` records the CHILD id); **consumption** (`issue`
diff --git a/apps/erp/app/components/EnumerableGroup.tsx b/apps/erp/app/components/EnumerableGroup.tsx
new file mode 100644
index 0000000000..49132cdb0b
--- /dev/null
+++ b/apps/erp/app/components/EnumerableGroup.tsx
@@ -0,0 +1,83 @@
+import {
+ Badge,
+ cn,
+ Popover,
+ PopoverContent,
+ PopoverTrigger
+} from "@carbon/react";
+import { useLingui } from "@lingui/react/macro";
+import { Enumerable } from "./Enumerable";
+
+type EnumerableGroupItem = {
+ label: string;
+ onClick?: () => void;
+};
+
+type EnumerableGroupProps = {
+ items: EnumerableGroupItem[];
+ limit?: number;
+ // "enumerable" = colored entity chips; "outline" = readable-id badges,
+ // matching how item ids render across the app.
+ chip?: "enumerable" | "outline";
+ chipClassName?: string;
+};
+
+// Single-line sibling of AvatarGroup for Enumerable chips: the first `limit`
+// render inline and the rest collapse behind a +N chip that opens them (click,
+// tap or keyboard — a hover card left touch and keyboard users out), so
+// a list cell never wraps and every table row keeps the same height.
+const EnumerableGroup = ({
+ items,
+ limit = 2,
+ chip = "enumerable",
+ chipClassName
+}: EnumerableGroupProps) => {
+ const { t } = useLingui();
+ if (items.length === 0) return null;
+ const visible = items.slice(0, limit);
+ const overflow = items.slice(limit);
+
+ const renderChip = (item: EnumerableGroupItem) =>
+ chip === "outline" ? (
+ <Badge
+ key={item.label}
+ variant="outline"
+ onClick={item.onClick}
+ title={item.label}
+ className={cn(item.onClick && "cursor-pointer", chipClassName)}
+ >
+ {item.label}
+ </Badge>
+ ) : (
+ <Enumerable
+ key={item.label}
+ value={item.label}
+ onClick={item.onClick}
+ className={cn(item.onClick && "cursor-pointer", chipClassName)}
+ />
+ );
+
+ return (
+ <span className="flex items-center gap-2 whitespace-nowrap">
+ {visible.map(renderChip)}
+ {overflow.length > 0 && (
+ <Popover>
+ <PopoverTrigger
+ aria-label={t`Show ${overflow.length} more`}
+ onClick={(e) => e.stopPropagation()}
+ className="inline-flex min-h-[1.5rem] items-center rounded-md border bg-secondary px-2 text-[12px] font-bold tabular-nums text-secondary-foreground outline-none transition-colors hover:bg-secondary/80 focus-visible:ring-[3px] focus-visible:ring-ring/50"
+ >
+ +{overflow.length}
+ </PopoverTrigger>
+ <PopoverContent className="w-auto max-w-[280px] p-2">
+ <div className="flex flex-wrap items-center gap-2">
+ {overflow.map(renderChip)}
+ </div>
+ </PopoverContent>
+ </Popover>
+ )}
+ </span>
+ );
+};
+
+export { EnumerableGroup };
diff --git a/apps/erp/app/components/Form/EmojiPicker.tsx b/apps/erp/app/components/Form/EmojiPicker.tsx
index 08d8c99675..0ccc516cca 100644
--- a/apps/erp/app/components/Form/EmojiPicker.tsx
+++ b/apps/erp/app/components/Form/EmojiPicker.tsx
@@ -10,10 +10,14 @@ import {
useMode
} from "@carbon/react";
import data from "@emoji-mart/data";
-import Picker from "@emoji-mart/react";
-import { useState } from "react";
+import { lazy, Suspense, useState } from "react";
import { LuSmilePlus, LuTrash } from "react-icons/lu";
+// Lazy, not a static import: @emoji-mart/react is CommonJS, so under SSR its
+// default import is `{ default: Picker }` and dev React warns "type is
+// invalid" the moment the element is created, even in a closed popover.
+const Picker = lazy(() => import("@emoji-mart/react"));
+
type EmojiPickerProps = {
name: string;
label?: string;
@@ -67,15 +71,17 @@ const EmojiPicker = ({ name }: EmojiPickerProps) => {
align="start"
sideOffset={8}
>
- <Picker
- data={data}
- onEmojiSelect={onEmojiSelect}
- theme={pickerTheme}
- previewPosition="none"
- skinTonePosition="none"
- navPosition="bottom"
- perLine={8}
- />
+ <Suspense>
+ <Picker
+ data={data}
+ onEmojiSelect={onEmojiSelect}
+ theme={pickerTheme}
+ previewPosition="none"
+ skinTonePosition="none"
+ navPosition="bottom"
+ perLine={8}
+ />
+ </Suspense>
{value && (
<PopoverFooter className="flex justify-center">
<Button
diff --git a/apps/erp/app/components/index.ts b/apps/erp/app/components/index.ts
index c7ab20de44..d9b6b3d282 100644
--- a/apps/erp/app/components/index.ts
+++ b/apps/erp/app/components/index.ts
@@ -17,6 +17,7 @@ import EmployeeAvatar from "./EmployeeAvatar";
import EmployeeAvatarGroup from "./EmployeeAvatarGroup";
import Empty from "./Empty";
import { Enumerable } from "./Enumerable";
+import { EnumerableGroup } from "./EnumerableGroup";
import FileDropzone from "./FileDropzone";
import Hyperlink from "./Hyperlink";
import {
@@ -74,6 +75,7 @@ export {
EmployeeAvatarGroup,
Empty,
Enumerable,
+ EnumerableGroup,
FileDropzone,
Hyperlink,
ItemLifecycleBadge,
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/batching.md b/apps/erp/app/modules/agent/kb/docs/reference/batching.md
index 309ebb640c..c6e74a3356 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/batching.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/batching.md
@@ -12,7 +12,7 @@ An operation batch (`BAT000001`) is a production-run concept. It is unrelated to
Batching is switched on per **process**, not per item or method. On the process form (**Resources → Processes**), turn on **"Batchable"** and pick a **"Batch type"**: **"Sequential"** (parts run one after another, like a saw or laser table) or **"Simultaneous"** (parts run together in one load, like a furnace, oven, or plating bath). The type drives the run-time estimate: sequential sums the members' times, simultaneous takes the longest.
-The same card holds the **"Compatibility rules"**: how strictly each material property must match for operations to share a batch. Six dimensions (material, substance, grade, dimension, form, finish), each set to **"Require Match"**, **"Suggest Match"**, or **"Ignore"**. By default substance, grade, and dimension suggest a match and the rest are ignored.
+The same card holds the **"Compatibility rules"**: how strictly each dimension must match for operations to share a batch. Six describe the material consumed (material, substance, grade, dimension, form, finish) and a seventh, **"Produced item"**, describes what each job makes. Each is set to **"Require Match"**, **"Suggest Match"**, or **"Ignore"**. By default substance, grade, and dimension suggest a match and the rest are ignored. Requiring a match on "Produced item" keeps a run to a single output item, which is what makes its [output lots](#completing-the-batch) mergeable afterwards.
Only "Require Match" ever blocks anything; a suggested mismatch just warns. A work center can additionally carry an advisory **"Batch Capacity"** and **"Minimum Batch Quantity"**; the builder shows a fill bar against them but never refuses a batch over them.
@@ -22,7 +22,11 @@ Open **Production → Batches** and press **"New Batch"** (the production dashbo
Operations whose "Require Match" dimensions clash with your selection stay visible but locked, and mixed "Suggest Match" materials get an amber tag plus a warning to confirm they nest together on this run.
-The builder also proposes ready-made groupings: operations sharing a material signature and due within the same seven-day window, ranked by setup saved, urgency, and capacity fit. Finish with **"Create batch"** (the batch waits as **"Planned"**) or **"Create & Release"** (it goes straight to the floor). A work center is optional at this point: leave it blank and the scheduler auto-assigns the earliest-finishing candidate on release, writing it to the batch and every member.
+The builder also proposes ready-made groupings: operations sharing a material signature and due within the same seven-day window, ranked by setup saved, urgency, and capacity fit.
+
+When the selected operations produce a lot-tracked item, the review panel adds an **"Output"** section: this is where the run's lot numbers are decided, not on the shop floor. Each job gets its own lot number, pre-filled from the job's current one. When every selected operation makes the same lot-tracked item, **"Combine output into one lot"** replaces them with a single lot number for the whole run. Creating is disabled until every lot number is filled in and no two jobs share one.
+
+Finish with **"Create batch"** (the batch waits as **"Planned"**) or **"Create & Release"** (it goes straight to the floor). A work center is optional at this point: leave it blank and the scheduler auto-assigns the earliest-finishing candidate on release, writing it to the batch and every member.
## Lifecycle
@@ -35,7 +39,9 @@ There is no cancelled state: **"Dissolve Batch"** returns the members to the sch
The moment a single timer event is recorded against the batch, membership is permanent: adding, removing, changing the work center, unreleasing, and dissolving are all refused, and the only exit is completing it. Decide the composition before work starts.
-A batched operation is visible to operators when its **batch** is released, even if its own job is still "Draft" or "Planned"; the batch's schedule outranks the job's. Releasing recalculates requirements for those unreleased member jobs first, so materials are known, but it does not run MRP. The same job's other, unbatched operations stay hidden until the job itself is released.
+Member jobs still in "Draft" or "Planned" are released with the batch, exactly as **"Release Job"** would release them: requirements are recalculated, MRP runs, the job becomes "Ready", and its outside operations go on purchase orders. The **"Release"** dialog checks every one of those jobs first — each assembly needs an operation and manufacturing must not be blocked — and a single job that fails keeps the whole batch unreleased until it is fixed. For each supplier you choose a new purchase order or an existing draft, once for the whole batch, so outside operations from every member job land on one order.
+
+Bulk **"Release N batches"** on the Batches list has no dialog: a batch whose jobs need fixing, or whose suppliers already have a draft purchase order to choose from, is skipped and named in the summary. Release those from the batch itself.
## On the schedule
@@ -45,13 +51,33 @@ On the `docs/reference/scheduling`, the batch renders as one card listing its jo
## On the shop floor
-There is no separate batch screen in the shop floor app: any member's operation view *is* the batch UI. A batch chip shows the `BAT…` number, the member jobs, and a **"Print batch list"** action; the timer is shared, so starting it runs one clock for the whole batch, and planned time shows the batch total.
+There is no separate batch page in the shop floor app: any member's operation view *is* the batch UI. A batch chip shows the `BAT…` number, the member jobs, and a **"Print batch list"** action; the timer is shared, so starting it runs one clock for the whole batch, and planned time shows the batch total.
+
+Beside the chip, a **Batch | job** switch picks what the page shows. **"Batch"** (the default) is the whole run: completed quantity across every job, materials issued, scrap, the output lot, one materials table with batch totals, and the list of member jobs. The job switch shows the member's own steps, parameters, materials, and files, as for any operation.
+
+## Picking materials
+
+The run is shared, so the materials list is too. The batch view lists each material once with the batch's total requirement and the split per job beneath it (for example `2 · 4 · 6`), and a **"Pick"** button for what is still outstanding. In the job view each material row carries a second **"Batch"** figure beside the member's own.
+
+Picking a lot-tracked material issues it to every member at once. The quantity defaults to the batch's outstanding requirement, and Carbon divides what you pick across the members in proportion to what each still needs. Costing and lot `docs/reference/traceability` stay per job; only the operator's trip to the shelf is pooled.
+
+The split is proportional, so a smaller pick is divided across every member rather than filling one of them. On a batch needing 4,000 and 2,500, picking 4,000 leaves both members short instead of completing the first. Take the default, which is the batch total.
+
+Materials that are not lot-tracked show a batch total for reference only. They are still consumed per job automatically at completion.
+
+## Completing the batch
+
+Completion happens once, for the whole batch, in the **"Complete Batch"** modal: one row per member with **Quantity** and **Scrap**, pre-filled with each operation's remaining quantity. Leave a row at zero to skip that operation, which detaches it and returns it to the schedule un-run, with no time or quantity recorded.
-Completion happens once, for the whole batch, in the **"Complete Batch"** modal: one row per member with **Quantity** and **Scrap**, pre-filled with each operation's remaining quantity. Leave a row at zero to skip that operation — it detaches and returns to the schedule un-run, with no time or quantity recorded.
+The operator never enters a lot number. A combined run states its lot above the rows (*"All output goes to lot …"*); otherwise a read-only **"Lot"** column shows each job's planned lot. A batch created before lot planning existed, with a lot-tracked member that has no lot number, cannot complete: the modal names those jobs, and the fix is the lot number in the job's properties sidebar.
-On submit, any running timer stops, the shared time is sliced into per-member events in proportion to each member's planned quantity, scrap is recorded per member exactly as typed, materials issue, costs post, and every remaining member is marked **"Done"**.
+On submit, any running timer stops, the shared time is sliced into per-member events in proportion to each member's planned quantity, scrap is recorded per member exactly as typed, each member's output lot is created, materials issue, costs post, and every remaining member is marked **"Done"**.
-Entering less than the pre-filled quantity records less output, but the member operation is marked "Done" regardless. The only way to keep a member open is to zero it out entirely so it leaves the batch. If a downstream step fails mid-completion, the batch parks at "Completing" and the modal's button becomes **"Retry Completion"** — the retry must resubmit the recorded quantities, and corrections happen after completion.
+Entering less than the pre-filled quantity records less output, but the member operation is marked "Done" regardless. The only way to keep a member open is to zero it out entirely so it leaves the batch. If a downstream step fails mid-completion, the batch parks at "Completing" and the modal's button becomes **"Retry Completion"**. The retry must resubmit the recorded quantities, and corrections happen after completion.
+
+Each member first gets its own lot, because each job has its own cost and history. When the batch was planned to combine its output, those lots merge into the planned lot right after completion. Otherwise they stay separate. Completing the batch also completes each member job whose batched operation was its last, so the merged lot's full quantity is on hand immediately; a member with operations still remaining completes later and adds its share then. A completed batch's drawer still offers **"Merge output lots"** for lots kept separate.
+
+The merged lot holds the summed quantity and the earliest expiry date of the lots that went into it, and its genealogy still reaches back through every member job to the materials each one consumed. A quality event on it resolves to the exact jobs involved, which a single directly-produced lot could never tell you.
## Related
@@ -59,6 +85,7 @@ Entering less than the pre-filled quantity records less output, but the member o
- Jobs The work orders whose operations a batch groups.
- Work centers Where a batch runs, and the advisory capacity numbers the builder reads.
- MES The shop floor app where the shared timer runs and completion happens.
+ - Traceability The lots a batch consumes and produces, and how a merged lot still traces to every member job.
## Internals, exact strings, and troubleshooting
@@ -72,7 +99,17 @@ Eligibility (`assertEligible`): same company, same process, process batchable, `
Two-phase completion (`completeBatch`): phase 1 in one transaction — detach excluded members, auto-close a running timer at NOW(), slice events per member ∝ `operationQuantity` (largest-remainder whole seconds; `productionEvent.duration` is GENERATED so cost follows), insert per-member `productionQuantity` rows (Production when qty>0, Scrap when scrap>0), flip Active→Completing. Phase 2 idempotent — issue materials per member with qty>0, flip members Done (fires `sync_finish_job_operation` each), post GL per sliced event skipping already-posted, finalize Completing→Completed. MES batch timers skip `post-production-event` at End (`apps/mes/app/routes/x+/event.tsx:129-132`); cost posts once at completion. Scheduler: `batch-scheduler.ts` pre-pass places Active/Completing batches as one unit (Planned excluded), auto-assigns earliest-finish work center when blank (guarded `WHERE workCenterId IS NULL`), writes one reservation anchored on the min open member op; the reservation is spared by per-job regen and retired only by the status trigger (`20260907155426_cleanup-reservations-on-batch-exit.sql`) on entry to Planned/Completed; dissolve self-heals via FK SET NULL. Employee finiteness is deliberately absent in v1 — the batch reserves the work center only.
-Key refusal strings (edge fn): "The process is not batchable"; "Operation {id} is already in a batch"; "Operation {id} has already started"; "Operations with recorded production events cannot be batched"; "These operations can't share a batch — the {dims} must match on this process"; "Cannot add operations to a batch with status {status}"; "The batch has already started — complete it instead"; "Cannot remove operations: production has been recorded. Complete the batch instead."; "Cannot change the work center: production has been recorded."; "Only a planned batch can be released"; "Cannot release an empty batch"; "Only an active batch can be unreleased"; "Cannot dissolve: production has been recorded. Complete the batch instead — member jobs then proceed independently."; "Every operation is excluded — dissolve the batch instead of completing it"; "Operation {id} was included when completion started — retry with the recorded values; corrections happen after completion."; "Quantities were already recorded for this batch ({detail}). Retry with the recorded values; corrections happen after completion."; "One or more operations were already claimed by another batch — refresh and try again". MES gates: "This operation is part of a batch that has not been released to the floor"; "This operation's job has not been released to the floor". Builder add-mode: "Only a planned or active batch can take more operations". Scheduling conflict: "{Batch} has no estimated time — add setup, labor, or machine time to its operations to schedule it".
+Materials and output lots (spec `.ai/specs/2026-09-16-batch-materials-and-output-lots.md`). Shared pick: `issue` case `trackedEntitiesToBatch` (permission `update: "production"`) resolves the accounting period BEFORE opening its transaction (`getCurrentAccountingPeriod` reads over HTTP but writes in-transaction, so N members in one transaction would each try to create a missing month), locks the members' `jobMaterial` rows `FOR UPDATE`, and splits each picked lot with `splitPickAcrossMembers` (`shared/batch-pick-split.ts`, re-exported by `@carbon/utils`) weighted by each member's REMAINING requirement, via `distributeRoundingResidual`. Per-member writes reuse `consumeTrackedEntitiesIntoOperation`, the sequence extracted from `trackedEntitiesToOperation`, so genealogy and ledger rows are identical to N manual picks. Each picked lot is split separately, so every member ends up linked to every lot it actually drew from (complete recall coverage). MES panel totals come from `getBatchMaterialTotals`; the pick modal's `batchRemainingQuantity` prop is what makes the default the batch total rather than the member's share. Untracked materials are display-only and still backflush in completion phase 2.
+
+Output lots: completion phase 2 calls `issue` case `jobOperationBatchOutput` per member whose `jobMakeMethod.requiresBatchTracking` is true, between the material issue and the Done flip. It is the `Produce` activity plus the entity flip to Available, extracted from `jobOperationBatchComplete` WITHOUT that case's `productionQuantity` insert (phase 1 wrote it) or backflush (the issue step ran). Idempotent: an already-Available entity returns `{ created: false }`. A member that requires batch tracking but carries no `trackedEntityId` is refused rather than silently skipped.
+
+Lot merge: `issue` case `mergeTrackedEntities` (permission `update: "inventory"`) → `buildBatchMergeRecords` (`shared/batch-merge.ts`). Parents keep their quantity and flip `Consumed`; the merged entity is a fresh id with the summed quantity, the EARLIEST parent `expirationDate`, attributes kept only where all parents agree, `"Merged From Entity IDs"` provenance, and the FIRST parent's `readableId` when the caller passes none (the edge fn orders parents by the caller's list, so "first" is deterministic). Genealogy is one `trackedActivity` `type: "Merge"`, inputs = each parent at its quantity, output = the merged entity; ledger gets `Batch Merge` rows sized by each parent's RECEIVED (on-ledger) balance — the merge is identity-only, so lots merged straight off a completed batch (nothing received yet) write no ledger rows at all, and each member job's later receipt posts against the merged lot (`complete_job_to_inventory` walks Merge activities to the terminal output; migration `20260916131445_merge-aware-job-receipt.sql`; enum added by `20260915201233_batch-merge-ledger-enum.sql`). **Both callers derive the parent ids server-side from batch membership** — MES `getPlannedMergeLots` in `batch.$batchId.complete.tsx` (only when the batch has `mergeOutput`; the members' Available output lots, merged right after completion succeeds under `outputLotNumber`), ERP `getBatchOutputLots` in the `mergeOutputs` intent — because these routes invoke `issue` with the service role, so the edge fn's `inventory` check validates the service role rather than the operator. No entity ids travel through a form.
+
+Lot planning (migration `20260918094217_batch-output-lot-at-creation.sql`): `jobOperationBatch.mergeOutput` + `outputLotNumber` (CHECK: a merged batch has a non-blank lot). The `batch-operations` create payload carries either `mergeOutput` + `outputLotNumber` or `lotNumbers: [{ jobOperationId, lotNumber }]`; split mode writes each member's WIP `trackedEntity.readableId` in the create transaction. `get_batchable_operations` returns `itemId`, `requiresBatchTracking`, `trackedEntityId`, `lotNumber` so the builder can pre-fill. `add` on a merged batch re-runs `assertMergeable`. The MES completion form no longer posts batch numbers: the route passes `outputLotNumber` (merged) or null (split, the entity keeps its planned readableId). The completion route returns `data({ completed: true })` rather than a redirect because realtime revalidation during the action makes React Router drop a fetcher redirect; `JobOperation` navigates on it.
+
+Compatibility: `producedItem` is the seventh entry in `BATCH_RULE_DIMENSIONS`, default `ignore`, resolved from the job's item readable id on both the client fold and the edge fn's `assertMaterialCompatible`. Batch completion completes member JOBS too: `sync_finish_job_operation`'s status gate admits Draft/Planned jobs when the Done operation carries a `jobOperationBatchId` (migration `20260916155634_batch-completion-completes-draft-jobs.sql`) — a Draft job's op can only reach Done through a released batch, so the run genuinely happened; the job's receipt posts before the route's merge, which is why a merged lot's on-hand equals its full quantity. Serial-tracked members are unchanged by all of the above — batch mode still disables tracked activity for them.
+
+Key refusal strings (edge fn): "The process is not batchable"; "Operation {id} is already in a batch"; "Operation {id} has already started"; "Operations with recorded production events cannot be batched"; "These operations can't share a batch — the {dims} must match on this process"; "Cannot add operations to a batch with status {status}"; "The batch has already started — complete it instead"; "Cannot remove operations: production has been recorded. Complete the batch instead."; "Cannot change the work center: production has been recorded."; "Only a planned batch can be released"; "Cannot release an empty batch"; "Only an active batch can be unreleased"; "Cannot dissolve: production has been recorded. Complete the batch instead — member jobs then proceed independently."; "Every operation is excluded — dissolve the batch instead of completing it"; "Operation {id} was included when completion started — retry with the recorded values; corrections happen after completion."; "Quantities were already recorded for this batch ({detail}). Retry with the recorded values; corrections happen after completion."; "One or more operations were already claimed by another batch — refresh and try again"; "Pick of {n} exceeds the batch's remaining requirement of {m}"; "No member operation still requires this item"; "Batch is already completed"; "Operation {id} produces a batch-tracked item — its output lot is required"; "Operation {id} produces a batch-tracked item — its batch number is required"; "Only lots of the same item can be merged"; "At least two lots are required to merge"; "Lot {readableId} is not available to merge"; "Lot {readableId} has no quantity to merge"; "No mergeable output lots" (ERP mergeOutputs, when server-side derivation finds nothing); "A combined output needs its lot number"; "Lot number {n} is used twice — give each job its own, or combine them into one lot"; "Only operations that produce a batch-tracked item can combine into one lot"; "Lots of different items can't combine into one lot" (create/add lot planning). Batch release (ERP `releaseBatchMemberJobs`): "Fix these jobs before releasing: {jobId}: no operations on {assemblies}; {jobId}: manufacturing is blocked; {jobId}: choose a supplier for {operation} on the job; {jobId}: {operation} has no supplier" (an outside operation's supplier is its own supplier process, else its process's only supplier — a process with several needs the choice made on the job's own Release); "Outside operations need a purchase order choice — open the batch to release it" (bulk release only, when a supplier has Draft POs to choose from); "Failed to create purchase orders for job {id}". Job release route: "Assign an operation to each assembly before releasing: {assemblies}". MES gates: "This operation is part of a batch that has not been released to the floor"; "This operation's job has not been released to the floor". Builder add-mode: "Only a planned or active batch can take more operations". Scheduling conflict: "{Batch} has no estimated time — add setup, labor, or machine time to its operations to schedule it".
### The batch card is missing from the operations board / MES
Planned batches are invisible outside the Batches list and the builder: the board and the floor only surface Active ("Released") and Completing batches. Release it.
@@ -89,5 +126,14 @@ By design: a resume must match what phase 1 recorded (mismatches are quoted back
### The builder hides some operations on the process
The hidden-ops note explains: "{n} already started", "{n} already in a batch". Started or event-carrying operations can never be batched.
+### The pick modal says a batch number is not available
+The lot picker lists stock at the member job's location that is Available with a positive on-hand and a storage unit on its ledger. A lot in another location, with no bin, or already allocated to a picking list will not appear. The Scan field matches the tracked entity id a label encodes, not the human-readable lot number.
+
+### A shared pick left every member short
+Expected when less than the batch's outstanding requirement was picked: `splitPickAcrossMembers` divides whatever was picked pro-rata across every member with remaining need (largest-remainder at internal scale, so shares sum exactly). Pick the batch total, which is the modal default in batch mode.
+
+### Completed the batch but the lots did not merge
+Merging happens only when the batch was created with "Combine output into one lot". Otherwise separate lots are by design; serial-tracked members never merge. Lots kept separate can still be merged from the completed batch's drawer ("Merge output lots") until they are consumed.
+
### Suggested batches look wrong / too small
Suggestions group by material signature split into 7-day due windows, scored by setup saved (0.4), urgency (0.35), capacity fit (0.15), specificity (0.1); top 6 shown. Undated members ride the earliest dated cluster. They're suggestions — manual selection is never constrained by them.
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/traceability.md b/apps/erp/app/modules/agent/kb/docs/reference/traceability.md
index 40c4b9ddc3..4dd63a074a 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/traceability.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/traceability.md
@@ -23,6 +23,8 @@ Receiving a tracked item creates entities **On Hold**; posting the receipt relea
Every material event (consume, produce, split, ship) is recorded as an **activity** with **inputs** (what was consumed) and **outputs** (what was produced). Parent and child link through the activity, so the genealogy graph is built as work happens and walked later to trace a unit's ancestry or descendants. Consuming part of a batch records a **split**, linking the original lot to the consumed portion and the remainder.
+The inverse is a **merge**, which combines lots of one item into a single lot carrying their summed quantity and the earliest expiry date among them. Both lots stay in the graph as inputs to that merge, so the new lot traces back through each of them. `docs/reference/batching` merges the members a run completed under one batch number; lots kept separate can still be merged from the batch's drawer.
+
There are no separate serial-number or batch-number tables — one tracked-entity model represents both, and the number itself is an attribute. Genealogy isn't a stored parent pointer; it's reconstructed by walking the activity graph from a unit outward.
## Shelf life
diff --git a/apps/erp/app/modules/agent/kb/manifest.json b/apps/erp/app/modules/agent/kb/manifest.json
index 37431e5c8c..2b47df93d0 100644
--- a/apps/erp/app/modules/agent/kb/manifest.json
+++ b/apps/erp/app/modules/agent/kb/manifest.json
@@ -382,6 +382,8 @@
"Lifecycle",
"On the schedule",
"On the shop floor",
+ "Picking materials",
+ "Completing the batch",
"Related",
"Internals, exact strings, and troubleshooting",
"The batch card is missing from the operations board / MES",
@@ -389,6 +391,9 @@
"An operator sees a job that was never released",
"Retry Completion rejects my corrected quantities",
"The builder hides some operations on the process",
+ "The pick modal says a batch number is not available",
+ "A shared pick left every member short",
+ "Completed the batch but the lots did not merge",
"Suggested batches look wrong / too small"
]
},
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index b068f4e7e2..b1d67cf5e0 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -1347,6 +1347,30 @@ export async function getShippingTermsList(
.order("name", { ascending: true });
}
+// Merge >=2 same-item Available lots into ONE new entity (fresh id, summed
+// quantity, earliest expiry) with genealogy back to every parent. The issue
+// edge fn owns the writes; see shared/batch-merge.ts.
+export async function mergeTrackedEntities(
+ client: SupabaseClient<Database>,
+ args: {
+ trackedEntityIds: string[];
+ readableId?: string | null;
+ companyId: string;
+ userId: string;
+ }
+) {
+ return client.functions.invoke<{
+ trackedEntityId?: string;
+ readableId?: string | null;
+ error?: string;
+ }>("issue", {
+ body: {
+ type: "mergeTrackedEntities",
+ ...args
+ }
+ });
+}
+
export async function getTrackedEntities(
client: SupabaseClient<Database>,
companyId: string,
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index 3701d304f0..90d5d8e68c 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 (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.
+- **Operation Batch** (`jobOperationBatch`) — N job operations sharing one run on a **batchable process** (`process.batchable`: laser table, furnace, plating; `process.batchType` `Sequential`/`Simultaneous` = the s-batch/p-batch physics — serial queue vs parallel load — driving the batch's planned duration `setup(max) + Σ|max(run)` via `@carbon/utils` `batchDuration`). Jobs are never merged and the BOM is never modified; each member stays a first-class `jobOperation`. Time/cost split **proportional to `operationQuantity`**, materialized at completion as per-member `productionEvent` slices, so job costing/GL post per job with no special-casing. Status **`Planned → Active → Completing → Completed`** (no `Cancelled` — dissolve deletes a pre-start batch instead). `Planned` is the pre-floor state: composed in the builder from ANY live job's unstarted ops (the planner RPC no longer requires released jobs), fully editable (add/remove/work-center widened to Planned+Active pre-event), invisible to MES. **`Active` displays as "Released"** (exactly like job `Ready`); the `release` edge-fn intent (`Planned → Active`, requires ≥1 member — NO work center: the scheduler pre-pass auto-selects earliest-finish among the process's work centers and persists it to batch + members) puts members on the floor, and releasing it RELEASES its Draft/Planned member jobs through the job page's own path — `releaseBatchMemberJobs` → `releaseJobs` (`production.server.ts`: recalc, MRP, status Ready, outside-operation POs via `create` `purchaseOrderFromJob`, releasedDate) after `getJobReleaseReadiness` validates EVERY such job (assemblies without operations, manufacturing blocked, or an outside operation whose supplier can't be resolved — `resolveOperationSupplier`: its own supplier process, else the process's only supplier — refuse the whole batch untouched; there is no per-operation supplier picker on batch release); a supplier's first new PO is reused for the later jobs so a batch lands on one PO per supplier. The `BatchReleaseModal` (drawer, table row action, builder Create & Release) shows the checks and the per-supplier PO choice; bulk `batches/release` passes no choice, so a batch needing a fix or with Draft POs to choose from is skipped and named. Then it notifies the scheduler; `unrelease` (`Active → Planned`) is allowed only before the first production event. **Membership-handoff floor rule**: an op in a batch is floor-visible iff its BATCH is Released (`Active`/`Completing`) — even when its job is Draft/Planned; an op in no batch follows its JOB's release (the pre-batching rule — a released job's un-batched batchable op always remains runnable, never blocked; removing it from a batch is the escape hatch). Enforced in `get_active_job_operations_by_location`, MES `getOpenJobs`, AND server-side in the MES operation loader + start route (list visibility alone was the leak). **Scheduling**: a Released batch is ONE scheduling unit — the batch pre-pass (`packages/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: `releaseBatchMemberJobs` → `releaseJobOperationBatch` → `notifyScheduleInputsChanged`; per-batch edge-fn refusals land in the toast summary's `failed` list, the rest still release; a non-Planned id from a stale selection is skipped). Deleting from ERP = the edge fn's `dissolve`: single via the `batches/delete/:batchId` ConfirmDelete route (destructive "Dissolve Batch" in the table's row context menu + a destructive Dissolve button on the detail drawer, Active only), and bulk via selectable rows → a "Dissolve N batches" bulk action posting the selected Active ids to the `batches/dissolve` route (one edge-fn dissolve per id; the server's per-batch refusal for started batches lands in the toast summary's `failed` list, the rest still dissolve), and a printable **batch list** serves at `/file/batch/:id.pdf` (`BatchListPDF` in `@carbon/documents`; menu entries on the batch card and MES batch chip). **Materials and output lots (2026-09-16):** the MES batch-mode materials panel shows each item's summed BATCH requirement alongside the member's own (`getBatchMaterialTotals`), and ONE pick covers the whole batch — `issue` case `trackedEntitiesToBatch` splits the picked lot(s) **pro-rata by each member's REMAINING requirement** (`splitPickAcrossMembers` in `@carbon/utils` `batch-pick-split`, largest-remainder so shares sum exactly) and records each member's own consumption against its own WIP entity, so cost and lot genealogy stay per job while the operator acts once; the pick modal's default quantity is the batch remaining, NOT the member's share (defaulting to one member's share splits it again across all of them and satisfies none). Completion finalizes each member's produced lot via the lean `issue` case `jobOperationBatchOutput` (the `Produce` activity + entity flip EXTRACTED from `jobOperationBatchComplete`, WITHOUT that case's `productionQuantity` insert and backflush — Phase 1 and the Phase-2 issue step already did both), under lot numbers PLANNED AT CREATION — the builder's Output section (`ui/Batches/BatchOutputLots.tsx`) either sets each member's lot (written to its WIP `trackedEntity.readableId` by the `batch-operations` create) or, when every member makes the same batch-tracked item, "Combine output into one lot" (`jobOperationBatch.mergeOutput` + `outputLotNumber`, migration `20260918094217_batch-output-lot-at-creation.sql`); the operator never edits lots at completion. A merged batch's member lots are combined right after completion (and the batch drawer's "Merge output lots" covers a Completed batch kept separate) into ONE lot via `issue` `mergeTrackedEntities` — genealogy keeps every source job, so the merged lot is strictly more traceable than a single directly-produced one. Both entry points derive the parent ids SERVER-SIDE from the batch's membership: these routes invoke `issue` with the service role, so the edge fn's `inventory` permission check validates the service role rather than the operator. Eligibility gained a `producedItem` dimension in `BATCH_RULE_DIMENSIONS` (default `ignore`) so a process can require members to make the same item. Serial-tracked members are unchanged — batch mode still disables tracked activity for them. Job surfaces show live-batch membership: a Batches column on the jobs table (loader-side lookup), a badge on the `JobBillOfProcess` operation row (`jobOperationBatch` embed), and a chip on the MES job DAG node.
- **Procedure** — versioned work instructions linked to operations via `processId`. Statuses: Draft/Active/Archived.
- **Assembly Instructions** — 3D animated work instructions, available to all users. (Previously gated to Carbon-internal emails via `requireAssembliesInternal` / `useFlags().isInternal`; that gate was removed to ship publicly.) **Versioned** (Draft/Published/Archived) as **row-per-version**, not an in-place counter: sibling versions are grouped by a self-referential `assemblyInstruction.rootInstructionId` (NULL = "I am the root"; group root = `rootInstructionId ?? id`, siblings = `id = root OR rootInstructionId = root`). `copyAssemblyInstructionAsVersion` spins a new editable **Draft** as a perfect copy (`version = max+1`, deep-copies steps with `parentStepId` remapped + each step's materials/slides/tools). `activateAssemblyInstructionVersion` makes a version active: publishes it, **archives the prior Published sibling**, and repoints `jobOperation.assemblyInstructionId` from other group versions to it — but only for active operations (status ≠ Done/Canceled) on active jobs (`!isJobLocked`). Only Draft is editable; the header exposes a "Versions" switcher + Make Active / New Version. `updateAssemblyInstructionStatus` no longer bumps `version`. The **list** (`getAssemblyInstructions`) reads the `assemblyInstructions` **view** (not the base table): it collapses each group to its latest version (`WHERE version = MAX(version)` per `rootInstructionId ?? id`) and rolls every sibling into a `versions` jsonb array, mirroring the `procedures` view — the table shows a `Version N` subtitle on the name plus a "Versions" hover card. Migration `20260730153412_assembly-instructions-view.sql`.
- **Maintenance Dispatch** — reactive/scheduled repair for work centers with comments, events, items, and linked work centers.
@@ -95,6 +95,7 @@ pnpm --filter @carbon/erp test
- `getActiveJobOperationsByLocation` — schedule board data (RPC `get_active_job_operations_by_location`, now also returns `processBatchable`/`jobOperationBatchId`/`batchReadableId`)
- `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 (invoke the `batch-operations` edge 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`
- `getUnbatchedBatchableOperationCount` — head count of open (Todo/Ready/Waiting) unbatched operations on a batchable process for live jobs, mirroring the `get_batchable_operations` candidate branch; drives the production dashboard's "Unbatched Operations" card (links to `/x/production/batches/new`)
- `getJobOperationBatches` / `getJobOperationBatchMemberStats` / `getJobOperationBatchMembers` / `getJobOperationBatchWithMembers` — the `/x/production/batches` list (filterable, member count + summed quantity merged in the loader; `getJobOperationBatchMembers` is a single grouped `.in()` read of the page's member rows — job/item/quantity — powering the table's expandable member sub-rows, mirroring the ECO change-notices table's `renderExpandedRow`) and its detail drawer
- `getPeopleAssignments` / `getPeopleAbsences` (single date) and `getPeopleAssignmentsRange` / `getPeopleAbsencesRange` (week) — people board/matrix reads; `upsertPeopleAssignment` (move semantics, optional partial-day `hours`) / `movePeopleAssignment` (station move with same-station merge, Kysely txn; returns `previousWorkCenterId` so `people.update.tsx` reschedules BOTH the source and destination work centers — otherwise the station the person LEFT keeps a stale booking) / `setPeopleAssignmentHours` (per-station hours; null = whole shift — lowering releases the remainder to the board's free-hours pool) / `setPeopleAssignmentOvertime` / `setPeopleOvertimeBulk` (one date or a `date`→`toDate` range — the board's Week horizon applies a whole week; optional department/shift scope, single UPDATE) / `deletePeopleAssignment` / `setPeopleAbsence` / `setPeopleAbsenceRange` (vacation as one action — a row per date, duplicates skipped) / `clearPeopleAbsence` / `copyPeopleBoard` (day; copies splits, not overtime) / `copyPeopleWeek` (whole Monday-start week, same skip rules) / `assignPeopleWeek` / `unassignPeopleWeek` / `movePeopleWeek` (week-basis manning for the Board's Week range: one row per working day from the shift's weekday flags, Mon–Fri fallback) / `setPeopleDay` (atomic reconciliation of a person's whole day — the `PeopleHoursModal` Working-hours editor's Save, also anchored on Matrix cells) — people mutations
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index 7a767c8f32..c38d641a21 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -1048,6 +1048,30 @@ export const createJobOperationBatchValidator = z.object({
z
.array(z.string().min(1))
.min(1, { message: "Select at least one operation" })
+ ),
+ // Output lot identity is planned here, never typed on the floor. The
+ // batch-operations edge fn enforces the rules (one item to merge, unique
+ // numbers when split); these only carry the planner's choice through.
+ mergeOutput: zfd.checkbox(),
+ outputLotNumber: zfd.text(z.string().trim().optional()),
+ // JSON-encoded [{ jobOperationId, lotNumber }] — FormData has no nesting.
+ lotNumbers: z.preprocess(
+ (value) => {
+ if (typeof value !== "string" || value === "") return undefined;
+ try {
+ return JSON.parse(value);
+ } catch {
+ return value;
+ }
+ },
+ z
+ .array(
+ z.object({
+ jobOperationId: z.string().min(1),
+ lotNumber: z.string().trim().min(1)
+ })
+ )
+ .optional()
)
});
diff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.ts
index 65a2e3d5d7..4e1341fc97 100644
--- a/apps/erp/app/modules/production/production.server.ts
+++ b/apps/erp/app/modules/production/production.server.ts
@@ -1,4 +1,16 @@
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Database } from "@carbon/database";
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
import { ASSEMBLER_SERVICE_URL } from "@carbon/env";
+import { datetime } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { getEdgeFunctionErrorMessage } from "~/utils/error";
+import {
+ getJobReleaseReadiness,
+ recalculateJobRequirements,
+ runMRP,
+ updateJobStatus
+} from "./production.service";
// The geometry (assembler) service backs model conversion and motion planning.
// When it's unreachable those actions can't run, so loaders probe its health and
@@ -48,3 +60,175 @@ export async function isAssemblerServiceHealthy(): Promise<boolean> {
};
return healthy;
}
+
+// Release jobs to the floor: the one path the job page and batch release share.
+// Per job, in order: refresh requirements, run MRP, flip to Ready, put outside
+// operations on purchase orders, stamp releasedDate. Scheduling is the
+// caller's (one location run, or a notify, after all jobs are released).
+//
+// `purchaseOrdersBySupplierId` maps a supplier to "new" or a Draft PO id; a
+// supplier's first "new" PO is reused for the jobs after it, so a batch puts
+// each supplier's outside operations from every member job on one PO.
+// Validation (getJobReleaseReadiness) is the caller's, BEFORE this runs.
+export async function releaseJobs({
+ client,
+ db,
+ jobIds,
+ companyId,
+ userId,
+ purchaseOrdersBySupplierId
+}: {
+ client: SupabaseClient<Database>;
+ db: Kysely<KyselyDatabase>;
+ jobIds: string[];
+ companyId: string;
+ userId: string;
+ purchaseOrdersBySupplierId: Record<string, string>;
+}): Promise<{ error: string | null }> {
+ const serviceRole = getCarbonServiceRole();
+ const purchaseOrders = { ...purchaseOrdersBySupplierId };
+
+ for (const id of jobIds) {
+ const recalc = await recalculateJobRequirements(serviceRole, {
+ id,
+ companyId,
+ userId
+ });
+ if (recalc.error) return { error: `Failed to recalculate job ${id}` };
+
+ await runMRP(serviceRole, db, { type: "job", id, companyId, userId });
+
+ const update = await updateJobStatus(client, {
+ id,
+ companyId,
+ status: "Ready",
+ updatedBy: userId
+ });
+ if (update.error) return { error: `Failed to release job ${id}` };
+
+ const purchaseOrder = await serviceRole.functions.invoke<{
+ purchaseOrderIdsBySupplierId?: Record<string, string>;
+ }>("create", {
+ body: {
+ type: "purchaseOrderFromJob",
+ jobId: id,
+ purchaseOrdersBySupplierId: purchaseOrders,
+ companyId,
+ userId
+ }
+ });
+ if (purchaseOrder.error) {
+ return {
+ error: await getEdgeFunctionErrorMessage(
+ purchaseOrder.error,
+ `Failed to create purchase orders for job ${id}`
+ )
+ };
+ }
+ Object.assign(
+ purchaseOrders,
+ purchaseOrder.data?.purchaseOrderIdsBySupplierId ?? {}
+ );
+
+ await client
+ .from("job")
+ .update({ releasedDate: datetime.timestamp() })
+ .eq("id", id)
+ .eq("companyId", companyId);
+ }
+ return { error: null };
+}
+
+// Releasing a batch releases its Draft/Planned member jobs through the same
+// path as the job page: every one is validated first and ANY problem refuses the
+// whole batch before anything changes. `purchaseOrdersBySupplierId` is the
+// planner's PO choice from the Release dialog; unattended callers (bulk release)
+// pass none, and a batch that needs a choice — a supplier with Draft POs to pick
+// from — is refused so the planner can release it from its dialog.
+export async function releaseBatchMemberJobs({
+ client,
+ db,
+ jobIds,
+ companyId,
+ userId,
+ purchaseOrdersBySupplierId
+}: {
+ client: SupabaseClient<Database>;
+ db: Kysely<KyselyDatabase>;
+ jobIds: string[];
+ companyId: string;
+ userId: string;
+ purchaseOrdersBySupplierId?: Record<string, string>;
+}): Promise<{ error: string | null }> {
+ const jobs = await client
+ .from("job")
+ .select("id, status")
+ .in("id", [...new Set(jobIds)])
+ .eq("companyId", companyId);
+ if (jobs.error) return { error: "Failed to load the batch's jobs" };
+
+ const toRelease = (jobs.data ?? [])
+ .filter((job) => job.status === "Draft" || job.status === "Planned")
+ .map((job) => job.id);
+ if (toRelease.length === 0) return { error: null };
+
+ const readiness = await getJobReleaseReadiness(client, toRelease, companyId);
+ if (readiness.error || !readiness.data) {
+ return { error: "Failed to validate the batch's jobs" };
+ }
+
+ const problems = readiness.data.jobs.flatMap((job) => [
+ ...(job.manufacturingBlocked
+ ? [`${job.jobId}: manufacturing is blocked`]
+ : []),
+ ...(job.missingAssemblies.length > 0
+ ? [
+ `${job.jobId}: no operations on ${job.missingAssemblies
+ .map((m) => m.description)
+ .join(", ")}`
+ ]
+ : []),
+ // No per-operation supplier picker here: an ambiguous or missing supplier
+ // is settled on the job's own Release.
+ ...job.outsideOperationsWithoutSupplier.map((op) =>
+ op.missing === "choose"
+ ? `${job.jobId}: choose a supplier for ${op.description} on the job`
+ : `${job.jobId}: ${op.description} has no supplier`
+ )
+ ]);
+ if (problems.length > 0) {
+ return { error: `Fix these jobs before releasing: ${problems.join("; ")}` };
+ }
+
+ if (
+ !purchaseOrdersBySupplierId &&
+ readiness.data.suppliers.some((s) => s.draftPurchaseOrders.length > 0)
+ ) {
+ return {
+ error:
+ "Outside operations need a purchase order choice — open the batch to release it"
+ };
+ }
+
+ // Only a Draft PO of that supplier is a valid target; anything else is "new".
+ const purchaseOrders = Object.fromEntries(
+ readiness.data.suppliers.map((supplier) => {
+ const picked = purchaseOrdersBySupplierId?.[supplier.supplierId];
+ return [
+ supplier.supplierId,
+ picked && supplier.draftPurchaseOrders.some((po) => po.id === picked)
+ ? picked
+ : "new"
+ ];
+ })
+ );
+
+ return releaseJobs({
+ client,
+ db,
+ jobIds: toRelease,
+ companyId,
+ userId,
+ purchaseOrdersBySupplierId: purchaseOrders
+ });
+}
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 71c32f94fd..6df58e745f 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -8,7 +8,12 @@ import { asJobSource, trackWorkEvent } from "@carbon/lib/telemetry";
import { raiseMoment } from "@carbon/lib/workflows";
import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
-import { nameSimilarity, scrapAllowance, tiptapToText } from "@carbon/utils";
+import {
+ groupBy,
+ nameSimilarity,
+ scrapAllowance,
+ tiptapToText
+} from "@carbon/utils";
import type {
AssemblyGraph,
AssemblyGraphIndex,
@@ -101,6 +106,11 @@ import type {
JobMaterialPurchaseOrderLine,
JobMaterialSupplyJobLine
} from "./types";
+import {
+ makeMethodsMissingOperations,
+ outsideOperationsNeedingPurchaseOrders,
+ resolveOperationSupplier
+} from "./ui/Jobs/job-release-logic";
export { mapBalloonIdsToFeatureIdsForDocument };
@@ -2733,6 +2743,218 @@ export async function updateJobBatchNumber(
.select("id, readableId");
}
+export type JobReleaseReadiness = {
+ jobs: {
+ id: string;
+ jobId: string;
+ status: (typeof jobStatus)[number] | null;
+ manufacturingBlocked: boolean;
+ missingAssemblies: { makeMethodId: string; description: string }[];
+ // Outside operations release cannot put on a PO: the process has no
+ // supplier, or several and none chosen on the operation.
+ outsideOperationsWithoutSupplier: {
+ id: string;
+ description: string;
+ missing: "none" | "choose";
+ }[];
+ }[];
+ // Suppliers whose outside operations release will put on a purchase order,
+ // with the Draft POs the planner may add them to instead of a new one.
+ suppliers: {
+ supplierId: string;
+ draftPurchaseOrders: { id: string; purchaseOrderId: string }[];
+ }[];
+};
+
+// What stands between these jobs and release, read in one query per table for
+// any number of jobs. The job Release dialog and batch release both read it, so
+// a job released through a batch is held to the job page's rules.
+export async function getJobReleaseReadiness(
+ client: SupabaseClient<Database>,
+ jobIds: string[],
+ companyId: string
+): Promise<{ data: JobReleaseReadiness | null; error: PostgrestError | null }> {
+ if (jobIds.length === 0)
+ return { data: { jobs: [], suppliers: [] }, error: null };
+
+ const [jobs, roots, materials, operations] = await Promise.all([
+ client
+ .from("job")
+ .select(
+ "id, jobId, status, item(itemReplenishment(manufacturingBlocked))"
+ )
+ .in("id", jobIds)
+ .eq("companyId", companyId),
+ client
+ .from("jobMakeMethod")
+ .select("id, jobId")
+ .in("jobId", jobIds)
+ .eq("companyId", companyId)
+ .is("parentMaterialId", null),
+ client
+ .from("jobMaterialWithMakeMethodId")
+ .select(
+ "jobId, jobMaterialMakeMethodId, methodType, kit, description, itemReadableId"
+ )
+ .in("jobId", jobIds)
+ .eq("companyId", companyId),
+ client
+ .from("jobOperation")
+ .select(
+ "id, jobId, jobMakeMethodId, operationType, operationSupplierProcessId, processId, description"
+ )
+ .in("jobId", jobIds)
+ .eq("companyId", companyId)
+ ]);
+ const failed =
+ jobs.error ?? roots.error ?? materials.error ?? operations.error;
+ if (failed) return { data: null, error: failed };
+
+ const outsideOperationIds = (operations.data ?? [])
+ .filter((op) => op.operationType === "Outside Processing")
+ .map((op) => op.id);
+ const purchaseOrderLines = outsideOperationIds.length
+ ? await client
+ .from("purchaseOrderLine")
+ .select("jobOperationId")
+ .in("jobOperationId", outsideOperationIds)
+ .eq("companyId", companyId)
+ : { data: [], error: null };
+ if (purchaseOrderLines.error)
+ return { data: null, error: purchaseOrderLines.error };
+
+ const needingPurchaseOrders = outsideOperationsNeedingPurchaseOrders(
+ operations.data ?? [],
+ new Set(
+ (purchaseOrderLines.data ?? [])
+ .map((line) => line.jobOperationId)
+ .filter((id): id is string => !!id)
+ )
+ );
+ const ownSupplierProcessIds = [
+ ...new Set(
+ needingPurchaseOrders
+ .map((op) => op.operationSupplierProcessId)
+ .filter((id): id is string => !!id)
+ )
+ ];
+ const processIds = [
+ ...new Set(
+ needingPurchaseOrders
+ .map((op) => op.processId)
+ .filter((id): id is string => !!id)
+ )
+ ];
+ const [ownSupplierProcesses, processSupplierProcesses] = await Promise.all([
+ ownSupplierProcessIds.length
+ ? client
+ .from("supplierProcess")
+ .select("id, supplierId, processId")
+ .in("id", ownSupplierProcessIds)
+ .eq("companyId", companyId)
+ : { data: [], error: null },
+ processIds.length
+ ? client
+ .from("supplierProcess")
+ .select("id, supplierId, processId")
+ .in("processId", processIds)
+ .eq("companyId", companyId)
+ : { data: [], error: null }
+ ]);
+ const supplierProcessError =
+ ownSupplierProcesses.error ?? processSupplierProcesses.error;
+ if (supplierProcessError) return { data: null, error: supplierProcessError };
+
+ const supplierProcessById = new Map(
+ [
+ ...(ownSupplierProcesses.data ?? []),
+ ...(processSupplierProcesses.data ?? [])
+ ].map((sp) => [sp.id, sp])
+ );
+ const supplierProcessesByProcessId = new Map(
+ Object.entries(
+ groupBy(processSupplierProcesses.data ?? [], (sp) => sp.processId)
+ )
+ );
+ const resolved = needingPurchaseOrders.map((op) => ({
+ op,
+ supplier: resolveOperationSupplier(
+ op,
+ supplierProcessById,
+ supplierProcessesByProcessId
+ )
+ }));
+ const supplierIds = [
+ ...new Set(
+ resolved.flatMap(({ supplier }) =>
+ "supplierProcess" in supplier
+ ? [supplier.supplierProcess.supplierId]
+ : []
+ )
+ )
+ ];
+ const withoutSupplierByJob = groupBy(
+ resolved.filter(({ supplier }) => "missing" in supplier),
+ ({ op }) => op.jobId
+ );
+ const drafts = supplierIds.length
+ ? await client
+ .from("purchaseOrder")
+ .select("id, purchaseOrderId, supplierId")
+ .eq("status", "Draft")
+ .in("supplierId", supplierIds)
+ .eq("companyId", companyId)
+ : { data: [], error: null };
+ if (drafts.error) return { data: null, error: drafts.error };
+
+ const materialsByJob = groupBy(materials.data ?? [], (m) => m.jobId ?? "");
+ const operationsByJob = groupBy(operations.data ?? [], (op) => op.jobId);
+ const rootByJob = new Map((roots.data ?? []).map((r) => [r.jobId, r.id]));
+ const descriptionByMakeMethod = new Map(
+ (materials.data ?? []).map((m) => [
+ m.jobMaterialMakeMethodId,
+ m.description || m.itemReadableId || ""
+ ])
+ );
+
+ return {
+ data: {
+ jobs: (jobs.data ?? []).map((job) => ({
+ id: job.id,
+ jobId: job.jobId,
+ status: job.status,
+ manufacturingBlocked:
+ job.item?.itemReplenishment?.manufacturingBlocked === true,
+ missingAssemblies: makeMethodsMissingOperations(
+ rootByJob.get(job.id) ?? null,
+ materialsByJob[job.id] ?? [],
+ operationsByJob[job.id] ?? []
+ ).map((makeMethodId) => ({
+ makeMethodId,
+ description:
+ makeMethodId === rootByJob.get(job.id)
+ ? job.jobId
+ : (descriptionByMakeMethod.get(makeMethodId) ?? makeMethodId)
+ })),
+ outsideOperationsWithoutSupplier: (
+ withoutSupplierByJob[job.id] ?? []
+ ).map(({ op, supplier }) => ({
+ id: op.id,
+ description: op.description ?? op.id,
+ missing: "missing" in supplier ? supplier.missing : "none"
+ }))
+ })),
+ suppliers: supplierIds.map((supplierId) => ({
+ supplierId,
+ draftPurchaseOrders: (drafts.data ?? [])
+ .filter((po) => po.supplierId === supplierId)
+ .map((po) => ({ id: po.id, purchaseOrderId: po.purchaseOrderId }))
+ }))
+ },
+ error: null
+ };
+}
+
export async function updateJobStatus(
client: SupabaseClient<Database>,
params: {
@@ -6002,6 +6224,39 @@ export async function getJobOperationBatchMembers(
return { data: members, error: null };
}
+// The MERGEABLE output lots a completed batch's members produced: each member's
+// WIP tracked entity (tagged with its jobMakeMethod), narrowed to lots still
+// Available with stock. Drives the drawer's "Merge output lots" action — >=2 of
+// one item are mergeable, and a merged batch returns none (parents Consumed).
+export async function getBatchOutputLots(
+ client: SupabaseClient<Database>,
+ batchId: string,
+ companyId: string
+) {
+ const members = await client
+ .from("jobOperation")
+ .select("id, jobMakeMethodId")
+ .eq("jobOperationBatchId", batchId)
+ .eq("companyId", companyId);
+ const makeMethodIds = [
+ ...new Set(
+ (members.data ?? [])
+ .map((m) => m.jobMakeMethodId)
+ .filter(Boolean) as string[]
+ )
+ ];
+ if (makeMethodIds.length === 0) {
+ return { data: [], error: members.error };
+ }
+ return client
+ .from("trackedEntity")
+ .select("id, readableId, itemId")
+ .in("attributes->>Job Make Method", makeMethodIds)
+ .eq("companyId", companyId)
+ .eq("status", "Available")
+ .gt("quantity", 0);
+}
+
export async function getJobOperationBatchWithMembers(
client: SupabaseClient<Database>,
batchId: string,
@@ -6017,7 +6272,7 @@ export async function getJobOperationBatchWithMembers(
const members = await client
.from("jobOperation")
.select(
- "id, description, operationQuantity, quantityComplete, quantityScrapped, status, setupTime, setupUnit, laborTime, laborUnit, machineTime, machineUnit, workCenter(name), job(id, jobId, customerId, salesOrderId), jobMakeMethod(item(readableIdWithRevision, name, thumbnailPath))"
+ "id, description, operationQuantity, quantityComplete, quantityScrapped, status, setupTime, setupUnit, laborTime, laborUnit, machineTime, machineUnit, workCenter(name), job(id, jobId, customerId, salesOrderId, status), jobMakeMethod(item(readableIdWithRevision, name, thumbnailPath))"
)
.eq("jobOperationBatchId", batchId)
.eq("companyId", companyId);
@@ -6093,6 +6348,9 @@ export async function createJobOperationBatch(
// Create & Release: insert the batch already 'Active' (on the floor);
// omitted/false creates it 'Planned'.
release?: boolean;
+ mergeOutput?: boolean;
+ outputLotNumber?: string | null;
+ lotNumbers?: { jobOperationId: string; lotNumber: string }[];
companyId: string;
userId: string;
}
diff --git a/apps/erp/app/modules/production/types.ts b/apps/erp/app/modules/production/types.ts
index b8a7b3c84a..296b22f64e 100644
--- a/apps/erp/app/modules/production/types.ts
+++ b/apps/erp/app/modules/production/types.ts
@@ -248,8 +248,14 @@ export type BatchCandidate = {
jobReadableId: string | null;
jobDueDate: string | null;
jobStatus: string | null;
+ itemId: string | null;
itemReadableId: string | null;
itemDescription: string | null;
+ // The produced item's lot tracking and the job's live WIP entity, whose
+ // readableId is the lot number (pre-fills the builder's Output card).
+ requiresBatchTracking: boolean | null;
+ trackedEntityId: string | null;
+ lotNumber: string | null;
description: string | null;
operationQuantity: number | null;
status: string | null;
diff --git a/apps/erp/app/modules/production/ui/Batches/BatchBuilder.tsx b/apps/erp/app/modules/production/ui/Batches/BatchBuilder.tsx
index 4cdf1c487f..16fca91dc7 100644
--- a/apps/erp/app/modules/production/ui/Batches/BatchBuilder.tsx
+++ b/apps/erp/app/modules/production/ui/Batches/BatchBuilder.tsx
@@ -65,10 +65,19 @@ import {
} from "react-icons/lu";
import { useFetcher, useNavigate } from "react-router";
import { Enumerable, ItemThumbnail, Table } from "~/components";
+import { EnumerableGroup } from "~/components/EnumerableGroup";
import { path } from "~/utils/path";
import type { jobStatus } from "../../production.models";
import type { BatchCandidate } from "../../types";
import JobStatus from "../Jobs/JobStatus";
+import {
+ BatchOutputLots,
+ initialOutputLots,
+ type OutputLotsState,
+ outputLotsPayload,
+ outputLotsProblem
+} from "./BatchOutputLots";
+import { BatchReleaseModal } from "./BatchReleaseModal";
import {
type BatchAddTarget,
batchPlanBreakdown,
@@ -194,7 +203,11 @@ function CandidateJobStatus({ status }: { status: string | null }) {
// The material chips shown on a candidate row: one per distinct BOM line —
// property string when present, else the material item's readable id.
function materialChips(candidate: BatchCandidate): string[] {
- const chips = new Set<string>();
+ // Property signatures first, bare readable-id fallbacks last: compatibility
+ // is judged on the signatures, so they are the chips worth showing inline
+ // when the list is collapsed behind a +N.
+ const signatures = new Set<string>();
+ const fallbacks = new Set<string>();
for (const m of candidate.materials ?? []) {
const parts = [
m.substanceName,
@@ -203,10 +216,13 @@ function materialChips(candidate: BatchCandidate): string[] {
m.formName,
m.finishName
].filter(Boolean);
- const chip = parts.length ? parts.join(" ") : m.itemReadableId;
- if (chip) chips.add(chip);
+ if (parts.length) {
+ signatures.add(parts.join(" "));
+ } else if (m.itemReadableId) {
+ fallbacks.add(m.itemReadableId);
+ }
}
- return [...chips];
+ return [...signatures, ...fallbacks];
}
// Numbered wizard step marker (StockTransferWizard precedent).
@@ -317,6 +333,8 @@ export function BatchBuilder({
const [dueWindow, setDueWindow] = useState<number | null>(null);
const [workCenterId, setWorkCenterId] = useState<string | null>(null);
const [notes, setNotes] = useState("");
+ const [outputLots, setOutputLots] =
+ useState<OutputLotsState>(initialOutputLots);
const view: BuilderView = stored.view ?? "table";
// Selection is held here (not via the Table's index-keyed rowSelection, which
@@ -479,7 +497,8 @@ export function BatchBuilder({
grade: t`grade`,
dimension: t`dimension`,
form: t`form`,
- finish: t`finish`
+ finish: t`finish`,
+ producedItem: t`produced item`
}),
[t]
);
@@ -710,7 +729,14 @@ export function BatchBuilder({
}
}, [submitFetcher.state, submitFetcher.data, isAddMode, batch?.id, navigate]);
- const submit = (targetBatchId?: string, opts?: { release?: boolean }) => {
+ const [createReleaseOpen, setCreateReleaseOpen] = useState(false);
+ const submit = (
+ targetBatchId?: string,
+ opts?: {
+ release?: boolean;
+ purchaseOrdersBySupplierId?: Record<string, string>;
+ }
+ ) => {
const fd = new FormData();
if (isAddMode || targetBatchId) {
addTargetRef.current = targetBatchId ?? null;
@@ -722,9 +748,22 @@ export function BatchBuilder({
fd.set("locationId", locationId);
if (workCenterId) fd.set("workCenterId", workCenterId);
if (notes.trim()) fd.set("notes", notes.trim());
+ const lots = outputLotsPayload(selected, outputLots);
+ if (lots.mergeOutput) {
+ fd.set("mergeOutput", "on");
+ fd.set("outputLotNumber", lots.outputLotNumber ?? "");
+ } else if (lots.lotNumbers?.length) {
+ fd.set("lotNumbers", JSON.stringify(lots.lotNumbers));
+ }
// Create & Release: the create validator's zfd.checkbox reads "on" and
// the edge fn inserts the batch already Active (on the floor).
if (opts?.release) fd.set("release", "on");
+ if (opts?.purchaseOrdersBySupplierId) {
+ fd.set(
+ "purchaseOrdersBySupplierId",
+ JSON.stringify(opts.purchaseOrdersBySupplierId)
+ );
+ }
}
for (const id of selectedById.keys()) fd.append("jobOperationIds", id);
submitFetcher.submit(fd, {
@@ -734,6 +773,8 @@ export function BatchBuilder({
};
const isSubmitting = submitFetcher.state !== "idle";
+ // Output lots are planned here; a batch never reaches the floor without them.
+ const lotPlanIncomplete = outputLotsProblem(selected, outputLots) !== null;
const isLoading = candidatesFetcher.state !== "idle";
const locationOptions = useMemo(
@@ -904,6 +945,8 @@ export function BatchBuilder({
}
notes={notes}
onNotesChange={setNotes}
+ outputLots={outputLots}
+ onOutputLotsChange={setOutputLots}
/>
}
/>
@@ -930,8 +973,12 @@ export function BatchBuilder({
// Released batch that lacks it.
<Button
variant="secondary"
- isDisabled={selected.length === 0 || isSubmitting}
- onClick={() => submit(undefined, { release: true })}
+ isDisabled={
+ selected.length === 0 || isSubmitting || lotPlanIncomplete
+ }
+ // Opens the Release dialog: the selected jobs are checked and
+ // any outside-operation POs chosen before the batch is created.
+ onClick={() => setCreateReleaseOpen(true)}
>
{t`Create & Release`}
</Button>
@@ -939,7 +986,11 @@ export function BatchBuilder({
<Button
leftIcon={<LuLayers />}
isLoading={isSubmitting}
- isDisabled={selected.length === 0 || isSubmitting}
+ isDisabled={
+ selected.length === 0 ||
+ isSubmitting ||
+ (!isAddMode && lotPlanIncomplete)
+ }
onClick={() => submit()}
>
{isAddMode
@@ -949,6 +1000,18 @@ export function BatchBuilder({
</HStack>
</DrawerFooter>
</DrawerContent>
+ {createReleaseOpen && (
+ <BatchReleaseModal
+ target={{ jobIds: [...new Set(selected.map((c) => c.jobId))] }}
+ title={t`Create & release batch`}
+ confirmLabel={t`Create & Release`}
+ onClose={() => setCreateReleaseOpen(false)}
+ onConfirm={(purchaseOrdersBySupplierId) => {
+ submit(undefined, { release: true, purchaseOrdersBySupplierId });
+ setCreateReleaseOpen(false);
+ }}
+ />
+ )}
</Drawer>
);
}
@@ -1792,16 +1855,11 @@ function CandidateTable({
{t`No materials`}
</span>
) : (
- chips.map((chip) => (
- <Badge
- key={chip}
- variant="outline"
- className="max-w-[200px] font-normal text-muted-foreground"
- title={chip}
- >
- <span className="truncate">{chip}</span>
- </Badge>
- ))
+ <EnumerableGroup
+ chip="outline"
+ chipClassName="max-w-[200px] font-normal text-muted-foreground"
+ items={chips.map((chip) => ({ label: chip }))}
+ />
)}
<CompatBadge candidateId={row.original.id} compat={compat} />
</HStack>
@@ -2184,7 +2242,9 @@ function ReviewPanel({
batchCapacity,
minimumBatchQuantity,
notes,
- onNotesChange
+ onNotesChange,
+ outputLots,
+ onOutputLotsChange
}: {
isAddMode: boolean;
existingMembers: BatchBuilderBatch["members"];
@@ -2207,6 +2267,8 @@ function ReviewPanel({
minimumBatchQuantity: number | null;
notes: string;
onNotesChange: (v: string) => void;
+ outputLots: OutputLotsState;
+ onOutputLotsChange: (next: OutputLotsState) => void;
}) {
const { t } = useLingui();
@@ -2366,6 +2428,14 @@ function ReviewPanel({
</VStack>
)}
+ {!isAddMode && (
+ <BatchOutputLots
+ selected={selected}
+ value={outputLots}
+ onChange={onOutputLotsChange}
+ />
+ )}
+
<div className="flex-1 min-h-0 w-full overflow-y-auto">
<VStack spacing={0} className="p-3">
{isAddMode &&
diff --git a/apps/erp/app/modules/production/ui/Batches/BatchDetailDrawer.tsx b/apps/erp/app/modules/production/ui/Batches/BatchDetailDrawer.tsx
index b397f8c4b4..5478b7a2b7 100644
--- a/apps/erp/app/modules/production/ui/Batches/BatchDetailDrawer.tsx
+++ b/apps/erp/app/modules/production/ui/Batches/BatchDetailDrawer.tsx
@@ -29,11 +29,16 @@ import {
toast,
VStack
} from "@carbon/react";
-import { formatDurationMilliseconds } from "@carbon/utils";
+import {
+ formatDurationMilliseconds,
+ getItemReadableId,
+ groupBy
+} from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
-import { useEffect, useMemo, useRef } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import {
LuCirclePlay,
+ LuCombine,
LuCopy,
LuEllipsisVertical,
LuHammer,
@@ -44,6 +49,7 @@ import {
LuStickyNote,
LuTimer,
LuTrash,
+ LuTriangleAlert,
LuUndo2
} from "react-icons/lu";
import { Link, useFetcher } from "react-router";
@@ -54,14 +60,16 @@ import {
ItemThumbnail
} from "~/components";
import { useWorkCenters } from "~/components/Form/WorkCenter";
-import { useCustomers } from "~/stores";
+import { useCustomers, useItems } from "~/stores";
import { path } from "~/utils/path";
import { copyToClipboard } from "~/utils/string";
import type {
JobOperationBatchDetail,
JobOperationBatchEvent
} from "../../types";
+import JobStatus from "../Jobs/JobStatus";
import { BatchStatus } from "./BatchesTable";
+import { BatchReleaseModal } from "./BatchReleaseModal";
import { batchPlanBreakdown } from "./batch-builder-logic";
const EVENT_TYPES = ["Setup", "Labor", "Machine"] as const;
@@ -79,10 +87,18 @@ const EVENT_ICONS: Record<
export function BatchDetailDrawer({
batch,
events,
+ outputLots = [],
onClose
}: {
batch: JobOperationBatchDetail;
events: JobOperationBatchEvent[];
+ // The members' MERGEABLE output lots (the service filters to Available with
+ // stock) — >=2 of one item make a Completed batch mergeable.
+ outputLots?: {
+ id: string;
+ readableId: string | null;
+ itemId: string | null;
+ }[];
onClose: () => void;
}) {
const { t } = useLingui();
@@ -100,6 +116,42 @@ export function BatchDetailDrawer({
// production-event guard is what actually freezes a started batch.
const isPreStart = batch.status === "Planned" || batch.status === "Active";
+ // A Completed batch can merge each item's lots into one — every item with
+ // >=2 Available lots is its own merge (a mixed batch A, A, B merges the As).
+ // After a merge those lots are Consumed, so its button disappears on
+ // revalidation.
+ const [items] = useItems();
+ const mergeableItemIds = useMemo(() => {
+ if (batch.status !== "Completed") return [];
+ return Object.entries(
+ groupBy(
+ outputLots.filter((lot) => lot.itemId),
+ (lot) => lot.itemId as string
+ )
+ )
+ .filter(([, lots]) => lots.length >= 2)
+ .map(([itemId]) => itemId);
+ }, [batch.status, outputLots]);
+
+ const mergeFetcher = useFetcher<{ success?: boolean; message?: string }>();
+ const wasMerging = useRef(false);
+ useEffect(() => {
+ if (mergeFetcher.state !== "idle") {
+ wasMerging.current = true;
+ return;
+ }
+ if (!wasMerging.current) return;
+ wasMerging.current = false;
+ const d = mergeFetcher.data;
+ if (d?.message) {
+ if (d.success === false) {
+ toast.error(d.message);
+ } else {
+ toast.success(d.message);
+ }
+ }
+ }, [mergeFetcher.state, mergeFetcher.data]);
+
// Release (Planned → Active) / Unrelease (Active → Planned). The server's
// refusal (no work center, production already recorded) comes back as
// { success: false, message } and lands in the toast; success revalidates
@@ -122,9 +174,19 @@ export function BatchDetailDrawer({
}
}, [releaseFetcher.state, releaseFetcher.data]);
- const submitBatchIntent = (intent: "release" | "unrelease") => {
+ const [releaseOpen, setReleaseOpen] = useState(false);
+ const submitBatchIntent = (
+ intent: "release" | "unrelease",
+ purchaseOrdersBySupplierId?: Record<string, string>
+ ) => {
releaseFetcher.submit(
- { intent, batchId: batch.id },
+ {
+ intent,
+ batchId: batch.id,
+ ...(purchaseOrdersBySupplierId && {
+ purchaseOrdersBySupplierId: JSON.stringify(purchaseOrdersBySupplierId)
+ })
+ },
{ method: "post", action: path.to.priorityBatchingUpdate }
);
};
@@ -174,6 +236,9 @@ export function BatchDetailDrawer({
);
const memberCount = batch.members.length;
+ const pendingJobs = batch.members.filter(
+ (m) => m.job?.status && !["Completed", "Cancelled"].includes(m.job.status)
+ );
const totalQuantity = batch.members.reduce(
(sum, m) => sum + (m.operationQuantity ?? 0),
0
@@ -276,6 +341,22 @@ export function BatchDetailDrawer({
<div className="grid h-full min-h-0 w-full grid-cols-1 lg:grid-cols-3">
{/* Operations — the batch's contents */}
<section className="flex min-h-0 flex-col lg:col-span-2">
+ {/* Members whose batched operation was their LAST auto-complete
+ and receive with the batch; this nudge covers the rest — a
+ member with operations still remaining has made its lot but
+ put nothing on hand until the job finishes. */}
+ {batch.status === "Completed" && pendingJobs.length > 0 && (
+ <div className="mx-6 mt-5 flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-400">
+ <LuTriangleAlert className="mt-0.5 size-3.5 shrink-0" />
+ <span>
+ <Trans>
+ {pendingJobs.length} of {memberCount} member jobs are not
+ completed yet — their output stays out of stock until each
+ job is completed.
+ </Trans>
+ </span>
+ </div>
+ )}
<div className="flex items-center gap-2 px-6 pt-5 pb-3">
<h2 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
<Trans>Operations</Trans>
@@ -315,16 +396,23 @@ export function BatchDetailDrawer({
return (
<Tr key={member.id}>
<Td className="font-medium">
- {member.job?.id ? (
- <Link
- to={path.to.jobDetails(member.job.id)}
- className="hover:underline"
- >
- {member.job.jobId}
- </Link>
- ) : (
- member.job?.jobId
- )}
+ <HStack spacing={2}>
+ {member.job?.id ? (
+ <Link
+ to={path.to.jobDetails(member.job.id)}
+ className="hover:underline"
+ >
+ {member.job.jobId}
+ </Link>
+ ) : (
+ member.job?.jobId
+ )}
+ {batch.status === "Completed" &&
+ member.job?.status &&
+ member.job.status !== "Completed" && (
+ <JobStatus status={member.job.status} />
+ )}
+ </HStack>
</Td>
<Td>
<HStack spacing={2}>
@@ -597,6 +685,28 @@ export function BatchDetailDrawer({
</Link>
</Button>
)}
+ {mergeableItemIds.map((itemId) => (
+ <Button
+ key={itemId}
+ variant="primary"
+ leftIcon={<LuCombine />}
+ isLoading={
+ mergeFetcher.state !== "idle" &&
+ mergeFetcher.formData?.get("itemId") === itemId
+ }
+ isDisabled={mergeFetcher.state !== "idle"}
+ onClick={() =>
+ mergeFetcher.submit(
+ { intent: "mergeOutputs", batchId: batch.id, itemId },
+ { method: "post", action: path.to.priorityBatchingUpdate }
+ )
+ }
+ >
+ {mergeableItemIds.length === 1
+ ? t`Merge output lots`
+ : t`Merge ${getItemReadableId(items, itemId) ?? itemId} lots`}
+ </Button>
+ ))}
{batch.status === "Planned" && (
// Never gated on a work center: the scheduler auto-selects one
// (earliest finish among the process's work centers — the same
@@ -607,7 +717,7 @@ export function BatchDetailDrawer({
leftIcon={<LuCirclePlay />}
isLoading={releaseFetcher.state !== "idle"}
isDisabled={releaseFetcher.state !== "idle"}
- onClick={() => submitBatchIntent("release")}
+ onClick={() => setReleaseOpen(true)}
>
{t`Release`}
</Button>
@@ -615,6 +725,18 @@ export function BatchDetailDrawer({
</HStack>
</DrawerFooter>
</DrawerContent>
+ {releaseOpen && (
+ <BatchReleaseModal
+ target={{ batchId: batch.id }}
+ title={t`Release batch ${batch.readableId}`}
+ confirmLabel={t`Release Batch`}
+ onClose={() => setReleaseOpen(false)}
+ onConfirm={(purchaseOrders) => {
+ submitBatchIntent("release", purchaseOrders);
+ setReleaseOpen(false);
+ }}
+ />
+ )}
</Drawer>
);
}
diff --git a/apps/erp/app/modules/production/ui/Batches/BatchOutputLots.tsx b/apps/erp/app/modules/production/ui/Batches/BatchOutputLots.tsx
new file mode 100644
index 0000000000..0eae4eb380
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Batches/BatchOutputLots.tsx
@@ -0,0 +1,193 @@
+import { HStack, Input, Switch, VStack } from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { LuLayers } from "react-icons/lu";
+import type { BatchCandidate } from "../../types";
+
+export type OutputLotsState = {
+ mergeOutput: boolean;
+ outputLotNumber: string;
+ // jobOperationId -> lot number the planner typed; absent falls back to the
+ // job's current lot number (its WIP entity's readableId)
+ lotNumbers: Record<string, string>;
+};
+
+export const initialOutputLots: OutputLotsState = {
+ mergeOutput: false,
+ outputLotNumber: "",
+ lotNumbers: {}
+};
+
+function trackedMembers(selected: BatchCandidate[]) {
+ return selected.filter((c) => c.requiresBatchTracking && c.trackedEntityId);
+}
+
+// Merging needs every selected operation to produce ONE batch-tracked item —
+// the edge fn enforces the same rule, this just hides an option it would refuse.
+export function canCombineOutput(selected: BatchCandidate[]) {
+ const tracked = trackedMembers(selected);
+ if (tracked.length < 2 || tracked.length !== selected.length) return false;
+ return new Set(tracked.map((c) => c.itemId)).size === 1;
+}
+
+export function lotNumberFor(
+ candidate: BatchCandidate,
+ state: OutputLotsState
+) {
+ return (state.lotNumbers[candidate.id] ?? candidate.lotNumber ?? "").trim();
+}
+
+// What the create request carries: the planner's choice, resolved.
+export function outputLotsPayload(
+ selected: BatchCandidate[],
+ state: OutputLotsState
+) {
+ const merge = state.mergeOutput && canCombineOutput(selected);
+ if (merge) {
+ return { mergeOutput: true, outputLotNumber: state.outputLotNumber.trim() };
+ }
+ return {
+ mergeOutput: false,
+ lotNumbers: trackedMembers(selected).map((c) => ({
+ jobOperationId: c.id,
+ lotNumber: lotNumberFor(c, state)
+ }))
+ };
+}
+
+// Null when the planned lots are complete; otherwise why Create is disabled.
+export function outputLotsProblem(
+ selected: BatchCandidate[],
+ state: OutputLotsState
+): "missing" | "duplicate" | null {
+ const payload = outputLotsPayload(selected, state);
+ if (payload.mergeOutput) {
+ return payload.outputLotNumber ? null : "missing";
+ }
+ const numbers = (payload.lotNumbers ?? []).map((l) => l.lotNumber);
+ if (numbers.some((n) => !n)) return "missing";
+ const seen = new Set<string>();
+ for (const n of numbers) {
+ const key = n.toLowerCase();
+ if (seen.has(key)) return "duplicate";
+ seen.add(key);
+ }
+ return null;
+}
+
+export function BatchOutputLots({
+ selected,
+ value,
+ onChange
+}: {
+ selected: BatchCandidate[];
+ value: OutputLotsState;
+ onChange: (next: OutputLotsState) => void;
+}) {
+ const { t } = useLingui();
+ const tracked = trackedMembers(selected);
+ if (tracked.length === 0) return null;
+
+ const combinable = canCombineOutput(selected);
+ const merge = value.mergeOutput && combinable;
+ const problem = outputLotsProblem(selected, value);
+
+ const counts = new Map<string, number>();
+ if (!merge) {
+ for (const c of tracked) {
+ const key = lotNumberFor(c, value).toLowerCase();
+ if (key) counts.set(key, (counts.get(key) ?? 0) + 1);
+ }
+ }
+
+ return (
+ <VStack
+ spacing={2}
+ className="px-4 py-3 border-b w-full flex-shrink-0 items-stretch"
+ >
+ <HStack spacing={2}>
+ <LuLayers className="size-4 text-muted-foreground" />
+ <span className="text-sm font-medium">
+ <Trans>Output</Trans>
+ </span>
+ {combinable && (
+ <span className="ml-auto text-xs text-muted-foreground truncate">
+ {t`all make ${tracked[0]?.itemReadableId ?? ""}`}
+ </span>
+ )}
+ </HStack>
+
+ {combinable && (
+ <Switch
+ variant="small"
+ checked={value.mergeOutput}
+ onCheckedChange={(checked) =>
+ onChange({ ...value, mergeOutput: checked })
+ }
+ label={t`Combine output into one lot`}
+ />
+ )}
+
+ {merge ? (
+ <Input
+ size="sm"
+ value={value.outputLotNumber}
+ onChange={(e) =>
+ onChange({ ...value, outputLotNumber: e.target.value })
+ }
+ placeholder={t`Lot number`}
+ className="font-mono"
+ />
+ ) : (
+ <VStack spacing={1} className="items-stretch">
+ {tracked.map((c) => {
+ const number = lotNumberFor(c, value);
+ const clashes =
+ number && (counts.get(number.toLowerCase()) ?? 0) > 1;
+ return (
+ <HStack key={c.id} spacing={2}>
+ <span className="w-24 flex-shrink-0 text-sm tabular-nums truncate">
+ {c.jobReadableId}
+ </span>
+ <Input
+ size="sm"
+ value={value.lotNumbers[c.id] ?? c.lotNumber ?? ""}
+ onChange={(e) =>
+ onChange({
+ ...value,
+ lotNumbers: {
+ ...value.lotNumbers,
+ [c.id]: e.target.value
+ }
+ })
+ }
+ placeholder={t`Lot number`}
+ aria-invalid={!number || Boolean(clashes)}
+ className="font-mono"
+ />
+ </HStack>
+ );
+ })}
+ </VStack>
+ )}
+
+ <p className="text-xs text-muted-foreground text-pretty">
+ {problem === "duplicate" ? (
+ <span className="text-destructive">
+ <Trans>
+ Each job needs its own lot number — or combine them into one lot.
+ </Trans>
+ </span>
+ ) : merge ? (
+ <Trans>
+ Everything this run makes lands in one lot. The shop floor can't
+ change it.
+ </Trans>
+ ) : (
+ <Trans>
+ Each job keeps its own lot. The shop floor can't change these.
+ </Trans>
+ )}
+ </p>
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx b/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx
new file mode 100644
index 0000000000..7e356738d8
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx
@@ -0,0 +1,226 @@
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+ Button,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ Spinner,
+ VStack
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useEffect, useState } from "react";
+import { LuShoppingCart, LuTriangleAlert } from "react-icons/lu";
+import { Link, useFetcher } from "react-router";
+import Select from "~/components/Select";
+import SupplierAvatar from "~/components/SupplierAvatar";
+import { path } from "~/utils/path";
+import type { JobReleaseReadiness } from "../../production.service";
+
+// Releasing a batch releases its Draft/Planned member jobs, so this is the job
+// Release dialog for all of them at once: the same checks (every assembly has an
+// operation, manufacturing not blocked — any failure blocks the whole batch) and
+// the same purchase-order choice, made once per supplier across every job.
+export function BatchReleaseModal({
+ target,
+ title,
+ confirmLabel,
+ isSubmitting,
+ onConfirm,
+ onClose
+}: {
+ target: { batchId: string } | { jobIds: string[] };
+ title: string;
+ confirmLabel: string;
+ isSubmitting?: boolean;
+ onConfirm: (purchaseOrdersBySupplierId?: Record<string, string>) => void;
+ onClose: () => void;
+}) {
+ const { t } = useLingui();
+ const readinessFetcher = useFetcher<
+ JobReleaseReadiness | { error: string }
+ >();
+ const [purchaseOrders, setPurchaseOrders] = useState<Record<string, string>>(
+ {}
+ );
+
+ const url = path.to.api.batchReleaseReadiness(target);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: load once per target
+ useEffect(() => {
+ readinessFetcher.load(url);
+ }, [url]);
+
+ const result = readinessFetcher.data;
+ const readiness = result && "jobs" in result ? result : null;
+ const loadError = result && "error" in result ? result.error : null;
+
+ useEffect(() => {
+ if (!readiness) return;
+ setPurchaseOrders(
+ Object.fromEntries(readiness.suppliers.map((s) => [s.supplierId, "new"]))
+ );
+ }, [readiness]);
+
+ const blocked = (readiness?.jobs ?? []).filter(
+ (job) =>
+ job.manufacturingBlocked ||
+ job.missingAssemblies.length > 0 ||
+ job.outsideOperationsWithoutSupplier.length > 0
+ );
+ const jobIds = (readiness?.jobs ?? []).map((job) => job.jobId);
+ const canRelease = !!readiness && blocked.length === 0 && !isSubmitting;
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <ModalContent size={readiness?.suppliers.length ? "large" : "medium"}>
+ <ModalHeader>
+ <ModalTitle>{title}</ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ {loadError ? (
+ <Alert variant="destructive">
+ <LuTriangleAlert />
+ <AlertTitle>{loadError}</AlertTitle>
+ </Alert>
+ ) : !readiness ? (
+ <div className="flex h-[118px] w-full flex-col items-center justify-center gap-2">
+ <Spinner className="size-8" />
+ <p className="text-sm">
+ <Trans>Checking the batch's jobs...</Trans>
+ </p>
+ </div>
+ ) : (
+ <VStack spacing={4}>
+ {blocked.length > 0 ? (
+ <Alert variant="warning">
+ <LuTriangleAlert />
+ <AlertTitle>
+ <Trans>Fix these jobs before releasing</Trans>
+ </AlertTitle>
+ <AlertDescription>
+ <Trans>
+ Releasing the batch releases its jobs, and each one must
+ be ready for the floor.
+ </Trans>
+ <ul className="mt-2 list-disc pl-4 space-y-1">
+ {blocked.map((job) => (
+ <li key={job.id}>
+ <Link
+ to={path.to.job(job.id)}
+ className="font-medium underline-offset-2 hover:underline"
+ >
+ {job.jobId}
+ </Link>
+ {" — "}
+ {[
+ job.manufacturingBlocked &&
+ t`manufacturing is blocked`,
+ job.missingAssemblies.length > 0 &&
+ t`no operations on ${job.missingAssemblies
+ .map((m) => m.description)
+ .join(", ")}`,
+ ...job.outsideOperationsWithoutSupplier.map((op) =>
+ op.missing === "choose"
+ ? t`choose a supplier for ${op.description} on the job`
+ : t`${op.description} has no supplier`
+ )
+ ]
+ .filter(Boolean)
+ .join("; ")}
+ </li>
+ ))}
+ </ul>
+ </AlertDescription>
+ </Alert>
+ ) : (
+ <p className="text-sm text-pretty">
+ {jobIds.length > 0 ? (
+ <Trans>
+ This also releases {jobIds.length} jobs (
+ {jobIds.join(", ")}). They become available to the shop
+ floor and drive purchasing and production.
+ </Trans>
+ ) : (
+ <Trans>
+ The batch goes to the shop floor. Its jobs are already
+ released.
+ </Trans>
+ )}
+ </p>
+ )}
+
+ {blocked.length === 0 && readiness.suppliers.length > 0 && (
+ <>
+ <Alert>
+ <LuShoppingCart />
+ <AlertTitle>
+ <Trans>Purchase orders required</Trans>
+ </AlertTitle>
+ <AlertDescription>
+ <Trans>
+ Each supplier's outside operations from every job go on
+ one new purchase order, or on an existing draft you
+ choose.
+ </Trans>
+ </AlertDescription>
+ </Alert>
+ {readiness.suppliers.map((supplier) => (
+ <div
+ key={supplier.supplierId}
+ className="flex w-full items-center justify-between rounded-lg border p-4 text-sm"
+ >
+ <SupplierAvatar supplierId={supplier.supplierId} />
+ <Select
+ size="sm"
+ value={purchaseOrders[supplier.supplierId] ?? "new"}
+ isReadOnly={supplier.draftPurchaseOrders.length === 0}
+ options={[
+ { value: "new", label: t`Create New` },
+ ...supplier.draftPurchaseOrders.map((po) => ({
+ value: po.id,
+ label: po.purchaseOrderId
+ }))
+ ]}
+ onChange={(value) =>
+ setPurchaseOrders((prev) => ({
+ ...prev,
+ [supplier.supplierId]: value
+ }))
+ }
+ />
+ </div>
+ ))}
+ </>
+ )}
+ </VStack>
+ )}
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button
+ isDisabled={!canRelease}
+ isLoading={isSubmitting}
+ onClick={() =>
+ onConfirm(
+ readiness?.suppliers.length ? purchaseOrders : undefined
+ )
+ }
+ >
+ {confirmLabel}
+ </Button>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+}
diff --git a/apps/erp/app/modules/production/ui/Batches/BatchesTable.tsx b/apps/erp/app/modules/production/ui/Batches/BatchesTable.tsx
index a01ccd2469..0d33faa7bd 100644
--- a/apps/erp/app/modules/production/ui/Batches/BatchesTable.tsx
+++ b/apps/erp/app/modules/production/ui/Batches/BatchesTable.tsx
@@ -12,7 +12,7 @@ import {
import { BATCH_STATUS_COLOR_MAP } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { ColumnDef } from "@tanstack/react-table";
-import { memo, useCallback, useEffect, useMemo, useRef } from "react";
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
LuCalendar,
LuCirclePlay,
@@ -32,6 +32,7 @@ import { usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
import type { JobOperationBatch } from "../../types";
+import { BatchReleaseModal } from "./BatchReleaseModal";
type BatchesTableProps = {
data: JobOperationBatch[];
@@ -95,14 +96,32 @@ const BatchesTable = memo(({ data, count }: BatchesTableProps) => {
}, [releaseFetcher.state, releaseFetcher.data]);
const submitBatchIntent = useCallback(
- (intent: "release" | "unrelease", batchId: string) => {
+ (
+ intent: "release" | "unrelease",
+ batchId: string,
+ purchaseOrdersBySupplierId?: Record<string, string>
+ ) => {
releaseFetcher.submit(
- { intent, batchId },
+ {
+ intent,
+ batchId,
+ ...(purchaseOrdersBySupplierId && {
+ purchaseOrdersBySupplierId: JSON.stringify(
+ purchaseOrdersBySupplierId
+ )
+ })
+ },
{ method: "post", action: path.to.priorityBatchingUpdate }
);
},
[releaseFetcher]
);
+ // The row action opens the Release dialog (member-job checks + PO choice)
+ // instead of releasing straight away.
+ const [releaseTarget, setReleaseTarget] = useState<{
+ id: string;
+ readableId: string;
+ } | null>(null);
// "Delete" is the edge fn's dissolve — offered while the batch is Planned or
// Active (a started batch must be completed; Completed batches are history).
@@ -119,7 +138,9 @@ const BatchesTable = memo(({ data, count }: BatchesTableProps) => {
// that lacks it.
<MenuItem
disabled={!canUpdate}
- onClick={() => submitBatchIntent("release", row.id)}
+ onClick={() =>
+ setReleaseTarget({ id: row.id, readableId: row.readableId })
+ }
>
<MenuIcon icon={<LuCirclePlay />} />
{t`Release Batch`}
@@ -432,23 +453,37 @@ const BatchesTable = memo(({ data, count }: BatchesTableProps) => {
);
return (
- <Table<JobOperationBatch>
- data={data}
- columns={columns}
- count={count}
- primaryAction={
- permissions.can("create", "production") && (
- <New label={t`Batch`} to={path.to.newOperationBatch} />
- )
- }
- renderActions={renderActions}
- renderContextMenu={renderContextMenu}
- renderExpandedRow={renderExpandedRow}
- canExpandRow={canExpandRow}
- withSelectableRows={canUpdate}
- getRowId={(row) => row.id}
- title={t`Batches`}
- />
+ <>
+ <Table<JobOperationBatch>
+ data={data}
+ columns={columns}
+ count={count}
+ primaryAction={
+ permissions.can("create", "production") && (
+ <New label={t`Batch`} to={path.to.newOperationBatch} />
+ )
+ }
+ renderActions={renderActions}
+ renderContextMenu={renderContextMenu}
+ renderExpandedRow={renderExpandedRow}
+ canExpandRow={canExpandRow}
+ withSelectableRows={canUpdate}
+ getRowId={(row) => row.id}
+ title={t`Batches`}
+ />
+ {releaseTarget && (
+ <BatchReleaseModal
+ target={{ batchId: releaseTarget.id }}
+ title={t`Release batch ${releaseTarget.readableId}`}
+ confirmLabel={t`Release Batch`}
+ onClose={() => setReleaseTarget(null)}
+ onConfirm={(purchaseOrders) => {
+ submitBatchIntent("release", releaseTarget.id, purchaseOrders);
+ setReleaseTarget(null);
+ }}
+ />
+ )}
+ </>
);
});
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 15a80207e9..7e57df9255 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
@@ -56,7 +56,14 @@ export function materialSignature(
const s = lineSignature(m, rules);
if (s) sigs.add(s);
}
- return [...sigs].sort().join(" + ");
+ const parts = [...sigs].sort();
+ // Candidate-level dimension: when the process cares about the produced item,
+ // it splits groups (and shows in the mixed warning) like any other dimension.
+ // Default is "ignore", so an unconfigured process's signature is unchanged.
+ if (rules.producedItem !== "ignore" && candidate.itemReadableId) {
+ parts.push(`→ ${candidate.itemReadableId}`);
+ }
+ return parts.join(" + ");
}
// The GROUPING key: the material signature, falling back to the produced item
@@ -87,7 +94,10 @@ export function candidateValueSets(candidate: BatchCandidate): MemberValueSets {
if (m.formName) form.push(m.formName);
if (m.finishName) finish.push(m.finishName);
}
- return { item, substance, grade, dimension, form, finish };
+ const producedItem = candidate.itemReadableId
+ ? [candidate.itemReadableId]
+ : [];
+ return { item, substance, grade, dimension, form, finish, producedItem };
}
export function setupDurationOf(candidate: BatchCandidate): number {
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
index a8b02b973b..9c369c8fc1 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
@@ -95,6 +95,7 @@ import {
getReceivableSerialUnits,
type JobReceiptSnapshot
} from "./job-complete-logic";
+import { makeMethodsMissingOperations } from "./job-release-logic";
const JobHeader = () => {
const navigate = useNavigate();
@@ -816,27 +817,6 @@ export function JobStartModal({
)
);
- const kittedMakeMethodIds = new Set(
- materials.data
- ?.filter((m) => m.jobMaterialMakeMethodId && m.kit)
- .map((m) => m.jobMaterialMakeMethodId) ?? []
- );
-
- // make methods for materials
- const uniqueMakeMethodIds = new Set(
- materials.data
- ?.filter(
- (m) =>
- m.jobMaterialMakeMethodId &&
- m.methodType === "Make to Order" &&
- !kittedMakeMethodIds.has(m.jobMaterialMakeMethodId)
- )
- .map((m) => m.jobMaterialMakeMethodId) ?? []
- );
-
- // top-level make method
- uniqueMakeMethodIds.add(makeMethod.data?.id!);
-
const flatMethod =
methodTree.data && methodTree.data.length > 0
? flattenTree(methodTree.data[0])
@@ -852,21 +832,16 @@ export function JobStartModal({
])
);
- const missingAssemblies = Array.from(uniqueMakeMethodIds)
- .filter(
- (makeMethodId) =>
- !(
- operations.data?.some(
- (op) => op.jobMakeMethodId === makeMethodId
- ) ?? false
- )
- )
- .map((makeMethodId) => {
- const info = bomInfoByMakeMethodId.get(makeMethodId ?? "");
- return info
- ? { bomId: info.bomId, description: info.description }
- : { bomId: "?", description: makeMethodId ?? "Unknown" };
- });
+ const missingAssemblies = makeMethodsMissingOperations(
+ makeMethod.data?.id ?? null,
+ materials.data ?? [],
+ operations.data ?? []
+ ).map((makeMethodId) => {
+ const info = bomInfoByMakeMethodId.get(makeMethodId ?? "");
+ return info
+ ? { bomId: info.bomId, description: info.description }
+ : { bomId: "?", description: makeMethodId ?? "Unknown" };
+ });
flushSync(() => {
setMissingOperationAssemblies(missingAssemblies);
diff --git a/apps/erp/app/modules/production/ui/Jobs/job-release-logic.ts b/apps/erp/app/modules/production/ui/Jobs/job-release-logic.ts
new file mode 100644
index 0000000000..8182fe2b55
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Jobs/job-release-logic.ts
@@ -0,0 +1,84 @@
+// Release checks shared by the job Release dialog and batch release, so a job
+// released as part of a batch is held to exactly the rules the job page applies.
+// Pure — no JSX/lingui — and unit-tested by apps/erp/test/job-release-logic.test.ts.
+
+export type ReleaseMaterial = {
+ jobMaterialMakeMethodId: string | null;
+ methodType: string | null;
+ kit: boolean | null;
+};
+
+export type ReleaseOperation = {
+ id: string;
+ jobMakeMethodId: string | null;
+ operationType: string | null;
+ operationSupplierProcessId: string | null;
+ processId?: string | null;
+};
+
+export type SupplierProcessRef = {
+ id: string;
+ supplierId: string;
+ processId: string;
+};
+
+// The job's own make method plus every Make-to-Order sub-assembly that is not
+// kitted must carry at least one operation, or nothing on the floor builds it.
+export function makeMethodsMissingOperations(
+ rootMakeMethodId: string | null,
+ materials: ReleaseMaterial[],
+ operations: ReleaseOperation[]
+): string[] {
+ const kitted = new Set(
+ materials
+ .filter((m) => m.jobMaterialMakeMethodId && m.kit)
+ .map((m) => m.jobMaterialMakeMethodId)
+ );
+ const required = new Set<string>();
+ for (const m of materials) {
+ if (
+ m.jobMaterialMakeMethodId &&
+ m.methodType === "Make to Order" &&
+ !kitted.has(m.jobMaterialMakeMethodId)
+ ) {
+ required.add(m.jobMaterialMakeMethodId);
+ }
+ }
+ if (rootMakeMethodId) required.add(rootMakeMethodId);
+
+ const withOperations = new Set(operations.map((op) => op.jobMakeMethodId));
+ return [...required].filter((id) => !withOperations.has(id));
+}
+
+// Outside operations release still has to purchase: no PO line exists yet.
+// Which supplier each goes to is resolveOperationSupplier's question.
+export function outsideOperationsNeedingPurchaseOrders<
+ T extends ReleaseOperation
+>(operations: T[], operationIdsWithPurchaseOrderLines: Set<string>): T[] {
+ return operations.filter(
+ (op) =>
+ op.operationType === "Outside Processing" &&
+ !operationIdsWithPurchaseOrderLines.has(op.id)
+ );
+}
+
+// An outside operation's supplier on release: its own supplier process, else
+// the sole supplier configured for its process — the same resolution as the
+// job Release dialog and `create` purchaseOrderFromJob. A process with no
+// supplier is "none"; one with several is "choose" (the job Release dialog
+// asks; batch release has no per-operation picker, so it refuses instead).
+export function resolveOperationSupplier(
+ op: Pick<ReleaseOperation, "operationSupplierProcessId" | "processId">,
+ supplierProcessById: Map<string, SupplierProcessRef>,
+ supplierProcessesByProcessId: Map<string, SupplierProcessRef[]>
+): { supplierProcess: SupplierProcessRef } | { missing: "none" | "choose" } {
+ if (op.operationSupplierProcessId) {
+ const own = supplierProcessById.get(op.operationSupplierProcessId);
+ return own ? { supplierProcess: own } : { missing: "none" };
+ }
+ const candidates = op.processId
+ ? (supplierProcessesByProcessId.get(op.processId) ?? [])
+ : [];
+ if (candidates.length === 1) return { supplierProcess: candidates[0]! };
+ return { missing: candidates.length === 0 ? "none" : "choose" };
+}
diff --git a/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx b/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx
index 7af0e074fd..2b261529f9 100644
--- a/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx
+++ b/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx
@@ -15,6 +15,7 @@ import {
import { useNavigate } from "react-router";
import { DateTime, EmployeeAvatar, Hyperlink, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import { EnumerableGroup } from "~/components/EnumerableGroup";
import { usePermissions } from "~/hooks";
import { useItems } from "~/stores";
import { usePeople } from "~/stores/people";
@@ -114,17 +115,16 @@ const ActionsTable = memo(
id: "items",
header: t`Items`,
cell: ({ row }) => (
- <span className="flex gap-2 items-center flex-wrap py-2">
- {((row.original.items ?? []) as Array<string>).map((i) => {
- const item = items.find((x) => x.id === i);
- if (!item) return null;
- return (
- <Badge variant="outline" key={item?.id}>
- {item?.readableIdWithRevision}
- </Badge>
- );
- })}
- </span>
+ <EnumerableGroup
+ chip="outline"
+ items={((row.original.items ?? []) as Array<string>).flatMap(
+ (i) => {
+ const item = items.find((x) => x.id === i);
+ if (!item) return [];
+ return { label: item.readableIdWithRevision ?? item.id };
+ }
+ )}
+ />
),
meta: {
icon: <LuBlocks />,
diff --git a/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsx b/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsx
index 99846bf326..58fc07b004 100644
--- a/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsx
@@ -20,6 +20,7 @@ import {
import { useNavigate } from "react-router";
import { DateTime, EmployeeAvatar, Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import { EnumerableGroup } from "~/components/EnumerableGroup";
import { useLocations } from "~/components/Form/Location";
import { ConfirmDelete } from "~/components/Modals";
import { usePermissions } from "~/hooks";
@@ -223,17 +224,16 @@ const IssuesTable = memo(({ data, types, count }: IssuesTableProps) => {
id: "items",
header: t`Items`,
cell: ({ row }) => (
- <span className="flex gap-2 items-center flex-wrap py-2">
- {((row.original.items ?? []) as Array<string>).map((i) => {
- const item = items.find((x) => x.id === i);
- if (!item) return null;
- return (
- <Badge variant="outline" key={item?.id}>
- {item?.readableIdWithRevision}
- </Badge>
- );
- })}
- </span>
+ <EnumerableGroup
+ chip="outline"
+ items={((row.original.items ?? []) as Array<string>).flatMap(
+ (i) => {
+ const item = items.find((x) => x.id === i);
+ if (!item) return [];
+ return { label: item.readableIdWithRevision ?? item.id };
+ }
+ )}
+ />
),
meta: {
icon: <LuBlocks />,
diff --git a/apps/erp/app/modules/resources/resources.models.ts b/apps/erp/app/modules/resources/resources.models.ts
index 4698ee1da4..ba6eed8787 100644
--- a/apps/erp/app/modules/resources/resources.models.ts
+++ b/apps/erp/app/modules/resources/resources.models.ts
@@ -22,7 +22,8 @@ export function batchRuleInitialValues(raw: BatchRules | null | undefined) {
batchRuleGrade: r.grade,
batchRuleDimension: r.dimension,
batchRuleForm: r.form,
- batchRuleFinish: r.finish
+ batchRuleFinish: r.finish,
+ batchRuleProducedItem: r.producedItem
};
}
@@ -353,7 +354,8 @@ export const processValidator = z
batchRuleGrade: z.enum(batchRuleLevels).optional(),
batchRuleDimension: z.enum(batchRuleLevels).optional(),
batchRuleForm: z.enum(batchRuleLevels).optional(),
- batchRuleFinish: z.enum(batchRuleLevels).optional()
+ batchRuleFinish: z.enum(batchRuleLevels).optional(),
+ batchRuleProducedItem: z.enum(batchRuleLevels).optional()
})
.refine((data) => {
if (data.processType !== "Outside Processing" && !data.workCenters) {
diff --git a/apps/erp/app/modules/resources/resources.service.ts b/apps/erp/app/modules/resources/resources.service.ts
index 8582a65219..50ced4539e 100644
--- a/apps/erp/app/modules/resources/resources.service.ts
+++ b/apps/erp/app/modules/resources/resources.service.ts
@@ -1849,6 +1849,7 @@ function extractBatchRules<
batchRuleDimension?: BatchRules["dimension"];
batchRuleForm?: BatchRules["form"];
batchRuleFinish?: BatchRules["finish"];
+ batchRuleProducedItem?: BatchRules["producedItem"];
}
>(source: T) {
const {
@@ -1858,6 +1859,7 @@ function extractBatchRules<
batchRuleDimension,
batchRuleForm,
batchRuleFinish,
+ batchRuleProducedItem,
...rest
} = source;
const batchRules = compactBatchRules(
@@ -1867,7 +1869,8 @@ function extractBatchRules<
grade: batchRuleGrade,
dimension: batchRuleDimension,
form: batchRuleForm,
- finish: batchRuleFinish
+ finish: batchRuleFinish,
+ producedItem: batchRuleProducedItem
})
) as Json;
return { batchRules, rest };
diff --git a/apps/erp/app/modules/resources/ui/Processes/ProcessForm.tsx b/apps/erp/app/modules/resources/ui/Processes/ProcessForm.tsx
index 025a17730f..cf1f86e22c 100644
--- a/apps/erp/app/modules/resources/ui/Processes/ProcessForm.tsx
+++ b/apps/erp/app/modules/resources/ui/Processes/ProcessForm.tsx
@@ -266,6 +266,11 @@ function BatchCompatibilityRules() {
name: "batchRuleItem",
label: t`Material item`,
description: t`The exact material part, not just its properties`
+ },
+ {
+ name: "batchRuleProducedItem",
+ label: t`Produced item`,
+ description: t`The item each job produces — require it to match to merge output lots`
}
];
diff --git a/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx b/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx
index 688badb6ee..69169fc816 100644
--- a/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx
+++ b/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx
@@ -37,6 +37,7 @@ import {
Table
} from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import { EnumerableGroup } from "~/components/EnumerableGroup";
import { useWorkCenters } from "~/components/Form/WorkCenter";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
@@ -139,21 +140,18 @@ const ProcessesTable = memo(({ data, count }: ProcessesTableProps) => {
id: "workCenters",
header: t`Work Centers`,
cell: ({ row }) => (
- <span className="flex gap-2 items-center flex-wrap py-2">
- {((row.original.workCenters ?? []) as Array<string>).map((wc) => {
- const workCenter = workCenters.find((w) => w.value === wc);
- return (
- <Enumerable
- key={workCenter?.label}
- onClick={() =>
- navigate(path.to.workCenter(workCenter?.value!))
- }
- className="cursor-pointer"
- value={workCenter?.label ?? null}
- />
- );
- })}
- </span>
+ <EnumerableGroup
+ items={((row.original.workCenters ?? []) as Array<string>).flatMap(
+ (wc) => {
+ const workCenter = workCenters.find((w) => w.value === wc);
+ if (!workCenter) return [];
+ return {
+ label: workCenter.label,
+ onClick: () => navigate(path.to.workCenter(workCenter.value))
+ };
+ }
+ )}
+ />
),
meta: {
icon: <LuBuilding2 />,
diff --git a/apps/erp/app/modules/resources/ui/Suggestions/SuggestionDetails.tsx b/apps/erp/app/modules/resources/ui/Suggestions/SuggestionDetails.tsx
index 21a8de7ec0..94d13f5c4d 100644
--- a/apps/erp/app/modules/resources/ui/Suggestions/SuggestionDetails.tsx
+++ b/apps/erp/app/modules/resources/ui/Suggestions/SuggestionDetails.tsx
@@ -14,9 +14,8 @@ import {
VStack
} from "@carbon/react";
import data from "@emoji-mart/data";
-import Picker from "@emoji-mart/react";
import { Trans, useLingui } from "@lingui/react/macro";
-import { useCallback, useState } from "react";
+import { lazy, Suspense, useCallback, useState } from "react";
import { useFetcher, useNavigate } from "react-router";
import z from "zod";
import { DateTime } from "~/components";
@@ -25,6 +24,11 @@ import { useTags } from "~/hooks/useTags";
import type { Suggestion } from "~/modules/resources";
import { path } from "~/utils/path";
+// Lazy, not a static import: @emoji-mart/react is CommonJS, so under SSR its
+// default import is `{ default: Picker }` and dev React warns "type is
+// invalid" the moment the element is created, even in a closed popover.
+const Picker = lazy(() => import("@emoji-mart/react"));
+
type SuggestionDetailsProps = {
suggestion: Suggestion;
tags: { name: string }[];
@@ -106,15 +110,17 @@ export default function SuggestionDetails({
align="start"
sideOffset={8}
>
- <Picker
- data={data}
- onEmojiSelect={onUpdateEmoji}
- theme={pickerTheme}
- previewPosition="none"
- skinTonePosition="none"
- navPosition="bottom"
- perLine={8}
- />
+ <Suspense>
+ <Picker
+ data={data}
+ onEmojiSelect={onUpdateEmoji}
+ theme={pickerTheme}
+ previewPosition="none"
+ skinTonePosition="none"
+ navPosition="bottom"
+ perLine={8}
+ />
+ </Suspense>
</PopoverContent>
</Popover>
</VStack>
diff --git a/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx b/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx
index 7b3b327b9c..035dc34a8e 100644
--- a/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx
+++ b/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx
@@ -39,6 +39,7 @@ import {
import { useFetcher, useNavigate } from "react-router";
import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import { EnumerableGroup } from "~/components/EnumerableGroup";
import { useProcesses } from "~/components/Form/Process";
import { Confirm } from "~/components/Modals";
import {
@@ -135,19 +136,18 @@ const WorkCentersTable = memo(
id: "processes",
header: t`Processes`,
cell: ({ row }) => (
- <span className="flex gap-2 items-center flex-wrap py-2">
- {((row.original.processes ?? []) as Array<string>).map((p) => {
- const process = processes.find((proc) => proc.value === p);
- return (
- <Enumerable
- key={process?.label}
- value={process?.label ?? null}
- onClick={() => navigate(path.to.process(process?.value!))}
- className="cursor-pointer"
- />
- );
- })}
- </span>
+ <EnumerableGroup
+ items={((row.original.processes ?? []) as Array<string>).flatMap(
+ (p) => {
+ const process = processes.find((proc) => proc.value === p);
+ if (!process) return [];
+ return {
+ label: process.label,
+ onClick: () => navigate(path.to.process(process.value))
+ };
+ }
+ )}
+ />
),
meta: {
icon: <LuRedoDot />,
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 dff142b9d4..b2bf15ee76 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
@@ -1,5 +1,5 @@
{
- "totalTools": 1543,
+ "totalTools": 1546,
"modules": 15,
"tools": [
{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},
@@ -45,7 +45,7 @@
{"name":"accounting_getAccountingPeriods","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"bd245bd0358c","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getAccountingSyncTieOut","classification":"READ","paramCount":3,"schema":"4feda8437359","response":"5483e69d7515","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getAccountingSyncTieOutCell","classification":"READ","paramCount":1,"schema":"1a84bfebf9e9","response":"a5febf12f4bd","injectAuth":"companyId","permission":"accounting:view","paginates":false},
- {"name":"accounting_getAccountLedger","classification":"READ","paramCount":6,"schema":"8ad7f551d78b","response":"edb6b7287c4d","injectAuth":"companyId","permission":"accounting:view","paginates":true},
+ {"name":"accounting_getAccountLedger","classification":"READ","paramCount":6,"schema":"8ad7f551d78b","response":"310315a786ca","injectAuth":"companyId","permission":"accounting:view","paginates":true},
{"name":"accounting_getAccountLedgerSummary","classification":"READ","paramCount":3,"schema":"aad65f7c3f63","response":"0a28a92b28ff","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getAccountPeriodSeries","classification":"READ","paramCount":2,"schema":"d5db2abee293","response":"2c75339d9fde","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getAccounts","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"84821cb96b68","injectAuth":"companyId","permission":"accounting:view","paginates":true},
@@ -96,9 +96,9 @@
{"name":"accounting_getGroupAccounts","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"a9a2c5be8164","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getIntercompanyBalance","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f2f76b33a3df","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getIntercompanyEliminationLines","classification":"READ","paramCount":1,"schema":"b9efe4d053a7","response":"e23adccbd115","injectAuth":"companyId","permission":"accounting:view","paginates":false},
- {"name":"accounting_getIntercompanyTransactions","classification":"READ","paramCount":3,"schema":"5ba9d4ce2300","response":"1821a0904335","injectAuth":"companyId","permission":"accounting:view","paginates":true},
+ {"name":"accounting_getIntercompanyTransactions","classification":"READ","paramCount":3,"schema":"5ba9d4ce2300","response":"0de20e25f12b","injectAuth":"companyId","permission":"accounting:view","paginates":true},
{"name":"accounting_getJournalEntries","classification":"READ","paramCount":4,"schema":"099269e45600","response":"0e88fc6d20f7","injectAuth":"companyId","permission":"accounting:view","paginates":true},
- {"name":"accounting_getJournalEntry","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"5e9ad810dd12","injectAuth":"companyId","permission":"accounting:view","paginates":false},
+ {"name":"accounting_getJournalEntry","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"80ba8fa9bef5","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getJournalLineDimensions","classification":"READ","paramCount":1,"schema":"4a6413e2bb5a","response":"b731368c1d3c","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getJournalSyncCompleteness","classification":"READ","paramCount":3,"schema":"6eb0a36bbd4b","response":"58d45b19b00c","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getOrCreateAccountingPeriod","classification":"READ","paramCount":2,"schema":"7dd9558cffe4","response":"00404e686415","injectAuth":"companyId","permission":"accounting:view","paginates":false},
@@ -198,18 +198,18 @@
{"name":"inventory_getInventoryCount","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"b707251b11c4","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getInventoryCountLines","classification":"READ","paramCount":2,"schema":"05dd6f9fd306","response":"e4219573b12b","injectAuth":"companyId","permission":"inventory:view","paginates":true},
{"name":"inventory_getInventoryCountLineSummary","classification":"READ","paramCount":1,"schema":"e354150046fe","response":"7a06e37fcf2a","injectAuth":"companyId","permission":"inventory:view","paginates":false},
- {"name":"inventory_getInventoryCountMovements","classification":"READ","paramCount":1,"schema":"e354150046fe","response":"1458ef5ad269","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getInventoryCountMovements","classification":"READ","paramCount":1,"schema":"e354150046fe","response":"8948b38be02b","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getInventoryCounts","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"43536f2bda72","injectAuth":"companyId","permission":"inventory:view","paginates":true},
{"name":"inventory_getInventoryItems","classification":"READ","paramCount":2,"schema":"68cb4a73d5a9","response":"5baddb3a890c","injectAuth":"companyId","permission":"inventory:view","paginates":true},
{"name":"inventory_getInventoryItemsCount","classification":"READ","paramCount":2,"schema":"68cb4a73d5a9","response":"8394fbabd845","injectAuth":"companyId","permission":"inventory:view","paginates":true},
{"name":"inventory_getInventoryValuation","classification":"READ","paramCount":2,"schema":"288f0d29701b","response":"4005e935f8f1","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getInventoryValuationTieOut","classification":"READ","paramCount":1,"schema":"cb789596bf56","response":"20aee38c95a3","injectAuth":"companyId","permission":"inventory:view","paginates":false},
- {"name":"inventory_getItemLedgerActivity","classification":"READ","paramCount":5,"schema":"b898b72c5939","response":"cbbaf0a67356","injectAuth":"companyId","permission":"inventory:view","paginates":false},
- {"name":"inventory_getItemLedgerPage","classification":"READ","paramCount":4,"schema":"de680470ebb1","response":"cbbaf0a67356","injectAuth":"companyId","permission":"inventory:view","paginates":true},
+ {"name":"inventory_getItemLedgerActivity","classification":"READ","paramCount":5,"schema":"b898b72c5939","response":"8d500cb0a03f","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getItemLedgerPage","classification":"READ","paramCount":4,"schema":"de680470ebb1","response":"8d500cb0a03f","injectAuth":"companyId","permission":"inventory:view","paginates":true},
{"name":"inventory_getKanban","classification":"READ","paramCount":1,"schema":"369f807bc840","response":"c5aa7a081ed4","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getKanbans","classification":"READ","paramCount":2,"schema":"68cb4a73d5a9","response":"fa96e94d8dda","injectAuth":"companyId","permission":"inventory:view","paginates":true},
{"name":"inventory_getPickingList","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"227255936b96","injectAuth":"companyId","permission":"inventory:view","paginates":false},
- {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"a908bc59a2d8","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"2993181a02e6","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"b51ad23d436f","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListLines","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"07d244c0f017","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListLineTrackedEntities","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"51dd622ce168","injectAuth":"companyId","permission":"inventory:view","paginates":false},
@@ -239,7 +239,7 @@
{"name":"inventory_getShippingMethodsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getShippingTermsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getStockMovementEffectiveQuantity","classification":"READ","paramCount":1,"schema":"a40494d32d29","response":"2e1967d88231","injectAuth":"companyId","permission":"inventory:view","paginates":false},
- {"name":"inventory_getStockMovements","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"1458ef5ad269","injectAuth":"companyId","permission":"inventory:view","paginates":true},
+ {"name":"inventory_getStockMovements","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"8948b38be02b","injectAuth":"companyId","permission":"inventory:view","paginates":true},
{"name":"inventory_getStockTransfer","classification":"READ","paramCount":1,"schema":"38111ae0fa2a","response":"0f59b3fa09f8","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getStockTransferLine","classification":"READ","paramCount":1,"schema":"0bbd6a946791","response":"a34287fc1477","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getStockTransferLines","classification":"READ","paramCount":1,"schema":"38111ae0fa2a","response":"bcb01288cc29","injectAuth":"companyId","permission":"inventory:view","paginates":false},
@@ -274,6 +274,7 @@
{"name":"inventory_insertManualInventoryAdjustment","classification":"WRITE","paramCount":12,"schema":"dc3fda774cf4","response":"3797626bd17e","injectAuth":"companyId+createdBy","permission":"inventory:create","paginates":false},
{"name":"inventory_insertStockTransfer","classification":"DESTRUCTIVE","paramCount":4,"schema":"623ca286b237","response":"910187eb9b58","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create","paginates":false},
{"name":"inventory_insertWarehouseTransfer","classification":"WRITE","paramCount":9,"schema":"b92377ee6a4f","response":"8e9431d157a2","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create","paginates":false},
+ {"name":"inventory_mergeTrackedEntities","classification":"WRITE","paramCount":2,"schema":"b12fee74a91e","response":"eeecb06dc790","injectAuth":"companyId","permission":"inventory:update","paginates":false},
{"name":"inventory_pickPickingListLine","classification":"WRITE","paramCount":3,"schema":"0371c6fecc9c","response":"3797626bd17e","injectAuth":"companyId","permission":"inventory:update","paginates":false},
{"name":"inventory_reconcileReceiptSerialEntities","classification":"DESTRUCTIVE","paramCount":2,"schema":"317d393d5b4a","response":"none","injectAuth":"companyId","permission":"inventory:update","paginates":false},
{"name":"inventory_searchStorageUnitsWithAncestors","classification":"READ","paramCount":2,"schema":"bf8906da76a5","response":"04385ce721d8","injectAuth":"companyId","permission":"inventory:view","paginates":false},
@@ -302,7 +303,7 @@
{"name":"inventory_upsertWarehouseTransfer","classification":"WRITE","paramCount":10,"schema":"8af29a9b1929","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},
{"name":"inventory_upsertWarehouseTransferLine","classification":"WRITE","paramCount":1,"schema":"93538fae689b","response":"237082879d41","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},
{"name":"invoicing_applyCreditsToInvoices","classification":"DESTRUCTIVE","paramCount":4,"schema":"404db2e47d09","response":"none","injectAuth":"companyId+createdBy","permission":"invoicing:update","paginates":false},
- {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"a908bc59a2d8","injectAuth":"companyId","permission":"invoicing:view","paginates":false},
+ {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"2993181a02e6","injectAuth":"companyId","permission":"invoicing:view","paginates":false},
{"name":"invoicing_computeInvoiceDateDue","classification":"READ","paramCount":2,"schema":"c07433aded5b","response":"174e29b899b9","injectAuth":"companyId","permission":"invoicing:view","paginates":false},
{"name":"invoicing_createPurchaseInvoiceFromPurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},
{"name":"invoicing_createSalesInvoiceFromSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},
@@ -407,7 +408,7 @@
{"name":"items_findChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"10c8230a9f49","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_findOtherOpenChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"8a1da983320d","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getBomHasShelfLifeManagedInput","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"7cb541e84f22","injectAuth":"companyId","permission":"parts:view","paginates":false},
- {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"a908bc59a2d8","injectAuth":"companyId","permission":"parts:view","paginates":false},
+ {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"2993181a02e6","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getChangeNotice","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"09c0b464284c","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getChangeNoticeActions","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"949f86b5cda3","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getChangeNoticeAffectedItems","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"5483e69d7515","injectAuth":"companyId","permission":"parts:view","paginates":false},
@@ -429,7 +430,7 @@
{"name":"items_getItem","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"87a9b87208d5","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getItemChangeNoticeData","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"a9f8d291a4dd","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getItemCost","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"38fa8e41fdd1","injectAuth":"companyId","permission":"parts:view","paginates":false},
- {"name":"items_getItemCostHistory","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"dca700d54845","injectAuth":"companyId","permission":"parts:view","paginates":false},
+ {"name":"items_getItemCostHistory","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"37830a1bad13","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getItemCustomerPart","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"4c6e08919580","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getItemCustomerParts","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"458a8cdb47f2","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getItemDemand","classification":"READ","paramCount":3,"schema":"ba3de97105ef","response":"d669af1cc644","injectAuth":"companyId","permission":"parts:view","paginates":false},
@@ -635,7 +636,7 @@
{"name":"production_copyPeopleWeek","classification":"WRITE","paramCount":4,"schema":"bd6e745b6883","response":"cbf943bfb8ed","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},
{"name":"production_createAssemblyPlanJob","classification":"WRITE","paramCount":1,"schema":"277f7d872d8c","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},
{"name":"production_createJobDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"6d2b672646dc","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},
- {"name":"production_createJobOperationBatch","classification":"WRITE","paramCount":5,"schema":"ae3153e945a1","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},
+ {"name":"production_createJobOperationBatch","classification":"WRITE","paramCount":8,"schema":"fffa9134447f","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},
{"name":"production_deleteAssemblyComponentMapping","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},
{"name":"production_deleteAssemblyInstruction","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},
{"name":"production_deleteAssemblyInstructionStep","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},
@@ -683,8 +684,9 @@
{"name":"production_getAssemblyPlanJson","classification":"READ","paramCount":1,"schema":"277f7d872d8c","response":"b4083e6fbe8b","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getAssemblyUnits","classification":"READ","paramCount":1,"schema":"277f7d872d8c","response":"7224ef8546c1","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getBalloons","classification":"READ","paramCount":1,"schema":"c25fe011e891","response":"3fec0abbc97d","injectAuth":"companyId","permission":"production:view","paginates":false},
- {"name":"production_getBatchableOperations","classification":"READ","paramCount":2,"schema":"4cebb10b56d4","response":"55b8408b15c3","injectAuth":"companyId","permission":"production:view","paginates":false},
+ {"name":"production_getBatchableOperations","classification":"READ","paramCount":2,"schema":"4cebb10b56d4","response":"62622425cf9e","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getBatchableProcesses","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"b0ab8957f96e","injectAuth":"companyId","permission":"production:view","paginates":false},
+ {"name":"production_getBatchOutputLots","classification":"READ","paramCount":1,"schema":"979f64cb9229","response":"7783e113d7a1","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getCapacityReservationsByJob","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"8ea855e0971b","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getCapacityReservationsForResources","classification":"READ","paramCount":2,"schema":"c0f9784197a0","response":"fc576887f258","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getDemandForecasts","classification":"READ","paramCount":3,"schema":"c24ad31f1eaa","response":"21892ee9e3b8","injectAuth":"companyId","permission":"production:view","paginates":false},
@@ -715,11 +717,11 @@
{"name":"production_getJobMethodTreeArray","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"74f0f766ca05","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobOperation","classification":"READ","paramCount":1,"schema":"6889e2589fdc","response":"ac4a3201b981","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobOperationAttachments","classification":"READ","paramCount":1,"schema":"0715cdbaa5fb","response":"9a8b9c571a6b","injectAuth":"companyId","permission":"production:view","paginates":false},
- {"name":"production_getJobOperationBatches","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"0a8712951dc1","injectAuth":"companyId","permission":"production:view","paginates":true},
+ {"name":"production_getJobOperationBatches","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"e4a233e30c55","injectAuth":"companyId","permission":"production:view","paginates":true},
{"name":"production_getJobOperationBatchEvents","classification":"READ","paramCount":1,"schema":"979f64cb9229","response":"8feaefdf02c8","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobOperationBatchMembers","classification":"READ","paramCount":1,"schema":"9bbe23a57535","response":"66bcdc105c00","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobOperationBatchMemberStats","classification":"READ","paramCount":1,"schema":"9bbe23a57535","response":"03aaee65a70b","injectAuth":"companyId","permission":"production:view","paginates":false},
- {"name":"production_getJobOperationBatchWithMembers","classification":"READ","paramCount":1,"schema":"979f64cb9229","response":"a6494db9c633","injectAuth":"companyId","permission":"production:view","paginates":false},
+ {"name":"production_getJobOperationBatchWithMembers","classification":"READ","paramCount":1,"schema":"979f64cb9229","response":"4a805fcbf28d","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobOperationDependencies","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"9214ed6d51dd","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobOperations","classification":"READ","paramCount":2,"schema":"d772b12a956e","response":"720a58fe2501","injectAuth":"companyId","permission":"production:view","paginates":true},
{"name":"production_getJobOperationsAssignedToEmployee","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"20f7748935c7","injectAuth":"companyId","permission":"production:view","paginates":false},
@@ -731,6 +733,7 @@
{"name":"production_getJobPromiseDate","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"f6521bc077a4","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobPurchaseOrderLines","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"309dea2a265c","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobReceiptSnapshot","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"af63ddd51939","injectAuth":"companyId","permission":"production:view","paginates":false},
+ {"name":"production_getJobReleaseReadiness","classification":"READ","paramCount":1,"schema":"267b4780c1d3","response":"e79774d3c8e8","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobs","classification":"READ","paramCount":1,"schema":"75e0e9e0be40","response":"630059095fdc","injectAuth":"companyId","permission":"production:view","paginates":true},
{"name":"production_getJobsByDateRange","classification":"READ","paramCount":3,"schema":"00794c516592","response":"737259a0d747","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobsBySalesOrderLine","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"630059095fdc","injectAuth":"companyId","permission":"production:view","paginates":false},
@@ -785,13 +788,13 @@
{"name":"production_insertJob","classification":"WRITE","paramCount":2,"schema":"fea224e085b1","response":"ad63dfd9d877","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},
{"name":"production_invalidateAssemblyModelCache","classification":"DESTRUCTIVE","paramCount":1,"schema":"277f7d872d8c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_issueMaterial","classification":"WRITE","paramCount":7,"schema":"0408bd8c9bde","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"a908bc59a2d8","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"2993181a02e6","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_movePeopleAssignment","classification":"DESTRUCTIVE","paramCount":2,"schema":"a726aa587ccc","response":"fe5e1dc03da5","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_movePeopleWeek","classification":"DESTRUCTIVE","paramCount":5,"schema":"fec8ebf1add4","response":"3badaa1686e8","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_notifyScheduleInputsChanged","classification":"WRITE","paramCount":3,"schema":"172bee52ed70","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planAssemblyStepMarkerRemap","classification":"WRITE","paramCount":2,"schema":"e8a18fd41775","response":"a908bc59a2d8","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"9228829e193c","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planOrphanStepAdoption","classification":"WRITE","paramCount":3,"schema":"aae2658d9922","response":"a908bc59a2d8","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planAssemblyStepMarkerRemap","classification":"WRITE","paramCount":2,"schema":"e8a18fd41775","response":"2993181a02e6","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"597005ef967c","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planOrphanStepAdoption","classification":"WRITE","paramCount":3,"schema":"aae2658d9922","response":"2993181a02e6","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_pullJobMaterialMakeMethod","classification":"WRITE","paramCount":2,"schema":"e27f48bbab4c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_reassignAssemblyStepComponents","classification":"DESTRUCTIVE","paramCount":4,"schema":"99f3d689165d","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_recalculateJobMakeMethodRequirements","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
@@ -1181,7 +1184,7 @@
{"name":"resources_upsertMaintenanceSchedule","classification":"WRITE","paramCount":20,"schema":"89ff27d11274","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},
{"name":"resources_upsertMaintenanceScheduleItem","classification":"WRITE","paramCount":5,"schema":"00e2e6d24e50","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},
{"name":"resources_upsertPartner","classification":"WRITE","paramCount":3,"schema":"4730e805ea1b","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},
- {"name":"resources_upsertProcess","classification":"DESTRUCTIVE","paramCount":16,"schema":"77bb0f4d5cd8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},
+ {"name":"resources_upsertProcess","classification":"DESTRUCTIVE","paramCount":17,"schema":"dfd1f2ba4547","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},
{"name":"resources_upsertTraining","classification":"WRITE","paramCount":4,"schema":"be53f09f9856","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},
{"name":"resources_upsertTrainingAssignment","classification":"WRITE","paramCount":3,"schema":"9f8996544bb7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},
{"name":"resources_upsertTrainingQuestion","classification":"WRITE","paramCount":12,"schema":"f27342252292","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},
diff --git a/apps/erp/app/routes/api+/production.release-readiness.ts b/apps/erp/app/routes/api+/production.release-readiness.ts
new file mode 100644
index 0000000000..5c659ea1aa
--- /dev/null
+++ b/apps/erp/app/routes/api+/production.release-readiness.ts
@@ -0,0 +1,59 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { LoaderFunctionArgs } from "react-router";
+import { data } from "react-router";
+import type { JobReleaseReadiness } from "~/modules/production";
+import { getJobReleaseReadiness } from "~/modules/production";
+
+// What releasing a batch would release, and what stands in its way: the
+// Draft/Planned jobs behind `?batchId=` (an existing batch) or `?jobId=`
+// (the builder's selection, before the batch exists). Already-released jobs are
+// left out — their outside operations were handled when they were released.
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "production"
+ });
+
+ const url = new URL(request.url);
+ const batchId = url.searchParams.get("batchId");
+ let jobIds = url.searchParams.getAll("jobId");
+
+ if (batchId) {
+ const members = await client
+ .from("jobOperation")
+ .select("jobId")
+ .eq("jobOperationBatchId", batchId)
+ .eq("companyId", companyId);
+ if (members.error) {
+ return data(
+ { error: "Failed to load the batch's jobs" },
+ { status: 500 }
+ );
+ }
+ jobIds = (members.data ?? []).map((m) => m.jobId);
+ }
+
+ const unreleased = jobIds.length
+ ? await client
+ .from("job")
+ .select("id")
+ .in("id", [...new Set(jobIds)])
+ .in("status", ["Draft", "Planned"])
+ .eq("companyId", companyId)
+ : { data: [], error: null };
+ if (unreleased.error) {
+ return data({ error: "Failed to load the batch's jobs" }, { status: 500 });
+ }
+
+ const readiness = await getJobReleaseReadiness(
+ client,
+ (unreleased.data ?? []).map((job) => job.id),
+ companyId
+ );
+ if (readiness.error || !readiness.data) {
+ return data(
+ { error: "Failed to validate the batch's jobs" },
+ { status: 500 }
+ );
+ }
+ return readiness.data satisfies JobReleaseReadiness;
+}
diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.test.ts b/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
index 52fa84c749..1ec04578d7 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
+++ b/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
@@ -50,14 +50,34 @@ vi.mock("~/modules/production", () => ({
"Closed",
"Cancelled"
],
+ getJobReleaseReadiness: vi.fn(),
recalculateJobRequirements: vi.fn(async () => ({ data: null, error: null })),
returnPickedRemaindersForJob: vi.fn(),
runMRP: vi.fn(async () => ({ data: null, error: null })),
updateJobStatus: vi.fn()
}));
+// The Release dialog goes through the shared releaseJobs path; delegate its
+// status flip to the mocked updateJobStatus so the ordering guard still sees it.
+vi.mock("~/modules/production/production.server", async () => {
+ const production = await import("~/modules/production");
+ return {
+ releaseJobs: vi.fn(async ({ jobIds, companyId, userId }) => {
+ for (const id of jobIds) {
+ await production.updateJobStatus({} as any, {
+ id,
+ companyId,
+ status: "Ready",
+ updatedBy: userId
+ });
+ }
+ return { error: null };
+ })
+ };
+});
import { cancelOpenPickingListsForJob } from "~/modules/inventory";
import {
+ getJobReleaseReadiness,
returnPickedRemaindersForJob,
updateJobStatus
} from "~/modules/production";
@@ -117,6 +137,22 @@ function setup() {
events.push("updateJobStatus");
return { data: { id: "job-1" }, error: null } as any;
});
+ vi.mocked(getJobReleaseReadiness).mockResolvedValue({
+ data: {
+ jobs: [
+ {
+ id: "job-1",
+ jobId: "J000001",
+ status: "Draft",
+ manufacturingBlocked: false,
+ missingAssemblies: [],
+ outsideOperationsWithoutSupplier: []
+ }
+ ],
+ suppliers: []
+ },
+ error: null
+ });
vi.mocked(runLocationSchedule).mockImplementation(async () => {
events.push("runLocationSchedule");
return undefined as any;
@@ -187,6 +223,33 @@ describe("Job release status action", () => {
events.indexOf("runLocationSchedule")
);
});
+
+ it("refuses release when an assembly has no operations", async () => {
+ vi.mocked(getJobReleaseReadiness).mockResolvedValue({
+ data: {
+ jobs: [
+ {
+ id: "job-1",
+ jobId: "J000001",
+ status: "Draft",
+ manufacturingBlocked: false,
+ missingAssemblies: [
+ { makeMethodId: "mm-2", description: "Bracket" }
+ ],
+ outsideOperationsWithoutSupplier: []
+ }
+ ],
+ suppliers: []
+ },
+ error: null
+ });
+
+ await expect(runRelease()).rejects.toBeInstanceOf(Response);
+
+ expect(updateJobStatus).not.toHaveBeenCalled();
+ expect(runLocationSchedule).not.toHaveBeenCalled();
+ expect(success).not.toHaveBeenCalled();
+ });
});
describe("Job cancel status action", () => {
diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.tsx b/apps/erp/app/routes/x+/job+/$jobId.status.tsx
index 9296c8c7b1..5321c7fd42 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.status.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.status.tsx
@@ -8,12 +8,14 @@ import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { cancelOpenPickingListsForJob } from "~/modules/inventory";
import {
+ getJobReleaseReadiness,
jobStatus,
recalculateJobRequirements,
returnPickedRemaindersForJob,
runMRP,
updateJobStatus
} from "~/modules/production";
+import { releaseJobs } from "~/modules/production/production.server";
import { getDatabaseClient } from "~/services/database.server";
import { path, requestReferrer } from "~/utils/path";
@@ -62,6 +64,75 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
}
+ // The Release dialog: the shared release path (also run by batch release),
+ // re-checking what the dialog checked, then one schedule run for the location.
+ if (status === "Ready" && shouldSchedule) {
+ const readiness = await getJobReleaseReadiness(client, [id], companyId);
+ const missing = readiness.data?.jobs[0]?.missingAssemblies ?? [];
+ if (readiness.error || missing.length > 0) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(id),
+ await flash(
+ request,
+ error(
+ readiness.error,
+ readiness.error
+ ? "Failed to validate job"
+ : `Assign an operation to each assembly before releasing: ${missing
+ .map((m) => m.description)
+ .join(", ")}`
+ )
+ )
+ );
+ }
+
+ try {
+ await stampSupplierChoices({
+ jobId: id,
+ companyId,
+ userId,
+ choices: JSON.parse(selectedSupplierProcessByOperationId ?? "{}")
+ });
+ } catch (err) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(id),
+ await flash(request, error(err, "Failed to save the supplier choice"))
+ );
+ }
+
+ const released = await releaseJobs({
+ client,
+ db: getDatabaseClient(),
+ jobIds: [id],
+ companyId,
+ userId,
+ purchaseOrdersBySupplierId: JSON.parse(
+ selectedPurchaseOrdersBySupplierId ?? "{}"
+ )
+ });
+ if (released.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(id),
+ await flash(request, error(null, released.error))
+ );
+ }
+
+ try {
+ await scheduleJobLocation({ id, companyId, userId });
+ } catch (err) {
+ logger.error("Error", { error: err });
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(id),
+ await flash(request, error(err, "Failed to schedule job"))
+ );
+ }
+
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(id),
+ await flash(request, success("Updated job status"))
+ );
+ }
+
if (["Planned", "Ready"].includes(status)) {
const serviceRole = getCarbonServiceRole();
await recalculateJobRequirements(serviceRole, {
@@ -134,119 +205,21 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- if (["Ready", "Planned"].includes(status) && shouldSchedule) {
+ if (status === "Planned" && shouldSchedule) {
try {
const purchaseOrdersBySupplierId = JSON.parse(
selectedPurchaseOrdersBySupplierId ?? "{}"
);
-
- const serviceRole = getCarbonServiceRole();
-
- // Persist any supplier the user chose in the release modal for an outside
- // operation whose process has multiple suppliers. Stamping it on the
- // operation lets purchaseOrderFromJob resolve it (below) and keeps the
- // choice on the operation. Must complete BEFORE the edge function reads.
- const operationSupplierChoices = Object.entries(
- JSON.parse(selectedSupplierProcessByOperationId ?? "{}") as Record<
- string,
- string
- >
- );
- if (operationSupplierChoices.length > 0) {
- // Both ids come from the form and drive a service-role (RLS-bypassing)
- // write that purchaseOrderFromJob later consumes, so validate them before
- // persisting: the operation must belong to THIS job, and the chosen
- // supplier process must belong to that operation's own process. Otherwise
- // a crafted submit could retarget another job or create a PO for an
- // unrelated supplier.
- const operationIds = operationSupplierChoices.map(
- ([operationId]) => operationId
- );
- const supplierProcessIds = operationSupplierChoices.map(([, sp]) => sp);
-
- const [
- { data: jobOperations, error: jobOperationsError },
- { data: supplierProcesses, error: supplierProcessesError }
- ] = await Promise.all([
- serviceRole
- .from("jobOperation")
- .select("id, processId")
- .eq("jobId", id)
- .eq("companyId", companyId)
- .in("id", operationIds),
- serviceRole
- .from("supplierProcess")
- .select("id, processId")
- .eq("companyId", companyId)
- .in("id", supplierProcessIds)
- ]);
- if (jobOperationsError) throw new Error(jobOperationsError.message);
- if (supplierProcessesError)
- throw new Error(supplierProcessesError.message);
-
- const operationProcessById = new Map(
- (jobOperations ?? []).map((op) => [op.id, op.processId])
- );
- const supplierProcessProcessById = new Map(
- (supplierProcesses ?? []).map((sp) => [sp.id, sp.processId])
- );
-
- for (const [
- operationId,
- supplierProcessId
- ] of operationSupplierChoices) {
- const operationProcessId = operationProcessById.get(operationId);
- if (!operationProcessId) {
- throw new Error(
- `Operation ${operationId} does not belong to this job`
- );
- }
- if (
- supplierProcessProcessById.get(supplierProcessId) !==
- operationProcessId
- ) {
- throw new Error(
- "Selected supplier does not belong to the operation's process"
- );
- }
- }
-
- const updateResults = await Promise.all(
- operationSupplierChoices.map(([operationId, supplierProcessId]) =>
- serviceRole
- .from("jobOperation")
- .update({
- operationSupplierProcessId: supplierProcessId,
- updatedBy: userId
- })
- .eq("id", operationId)
- .eq("companyId", companyId)
- )
- );
- const failedUpdate = updateResults.find((result) => result.error);
- if (failedUpdate?.error) throw new Error(failedUpdate.error.message);
- }
-
- // Forecast-first scheduling regenerates the whole location the job is in.
- const { data: jobLocation } = await serviceRole
- .from("job")
- .select("locationId")
- .eq("id", id)
- .single();
- if (!jobLocation?.locationId) {
- throw new Error("Job has no location to schedule");
- }
- // Regenerate the whole location IN-PROCESS (Node) — no edge cold-start or
- // HTTP hop. Throws on failure (caught below), in parallel with PO creation.
+ await stampSupplierChoices({
+ jobId: id,
+ companyId,
+ userId,
+ choices: JSON.parse(selectedSupplierProcessByOperationId ?? "{}")
+ });
+ // Regenerate the whole location in parallel with PO creation.
await Promise.all([
- runLocationSchedule({
- db: getDatabaseClient(),
- client: serviceRole,
- locationId: jobLocation.locationId,
- companyId,
- userId
- }),
- serviceRole.functions.invoke("create", {
+ scheduleJobLocation({ id, companyId, userId }),
+ getCarbonServiceRole().functions.invoke("create", {
body: {
type: "purchaseOrderFromJob",
jobId: id,
@@ -256,15 +229,6 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
})
]);
-
- if (status === "Ready") {
- await client
- .from("job")
- .update({
- releasedDate: new Date().toISOString()
- })
- .eq("id", id);
- }
} catch (err) {
logger.error("Error", { error: err });
throw redirect(
@@ -293,3 +257,117 @@ export async function action({ request, params }: ActionFunctionArgs) {
await flash(request, success("Updated job status"))
);
}
+
+// Forecast-first scheduling regenerates the whole location the job is in,
+// in-process (Node) — no edge cold-start or HTTP hop. Throws on failure.
+async function scheduleJobLocation({
+ id,
+ companyId,
+ userId
+}: {
+ id: string;
+ companyId: string;
+ userId: string;
+}) {
+ const serviceRole = getCarbonServiceRole();
+ const { data: jobLocation } = await serviceRole
+ .from("job")
+ .select("locationId")
+ .eq("id", id)
+ .single();
+ if (!jobLocation?.locationId) {
+ throw new Error("Job has no location to schedule");
+ }
+ await runLocationSchedule({
+ db: getDatabaseClient(),
+ client: serviceRole,
+ locationId: jobLocation.locationId,
+ companyId,
+ userId
+ });
+}
+
+// The release dialog's supplier pick for an outside operation whose process has
+// several suppliers, stamped on the operation so purchaseOrderFromJob resolves
+// it. Must land BEFORE the purchase orders are created.
+async function stampSupplierChoices({
+ jobId,
+ companyId,
+ userId,
+ choices
+}: {
+ jobId: string;
+ companyId: string;
+ userId: string;
+ choices: Record<string, string>;
+}) {
+ const serviceRole = getCarbonServiceRole();
+ const operationSupplierChoices = Object.entries(choices);
+ if (operationSupplierChoices.length > 0) {
+ // Both ids come from the form and drive a service-role (RLS-bypassing)
+ // write that purchaseOrderFromJob later consumes, so validate them before
+ // persisting: the operation must belong to THIS job, and the chosen
+ // supplier process must belong to that operation's own process. Otherwise
+ // a crafted submit could retarget another job or create a PO for an
+ // unrelated supplier.
+ const operationIds = operationSupplierChoices.map(
+ ([operationId]) => operationId
+ );
+ const supplierProcessIds = operationSupplierChoices.map(([, sp]) => sp);
+
+ const [
+ { data: jobOperations, error: jobOperationsError },
+ { data: supplierProcesses, error: supplierProcessesError }
+ ] = await Promise.all([
+ serviceRole
+ .from("jobOperation")
+ .select("id, processId")
+ .eq("jobId", jobId)
+ .eq("companyId", companyId)
+ .in("id", operationIds),
+ serviceRole
+ .from("supplierProcess")
+ .select("id, processId")
+ .eq("companyId", companyId)
+ .in("id", supplierProcessIds)
+ ]);
+ if (jobOperationsError) throw new Error(jobOperationsError.message);
+ if (supplierProcessesError) throw new Error(supplierProcessesError.message);
+
+ const operationProcessById = new Map(
+ (jobOperations ?? []).map((op) => [op.id, op.processId])
+ );
+ const supplierProcessProcessById = new Map(
+ (supplierProcesses ?? []).map((sp) => [sp.id, sp.processId])
+ );
+
+ for (const [operationId, supplierProcessId] of operationSupplierChoices) {
+ const operationProcessId = operationProcessById.get(operationId);
+ if (!operationProcessId) {
+ throw new Error(`Operation ${operationId} does not belong to this job`);
+ }
+ if (
+ supplierProcessProcessById.get(supplierProcessId) !== operationProcessId
+ ) {
+ throw new Error(
+ "Selected supplier does not belong to the operation's process"
+ );
+ }
+ }
+
+ const updateResults = await Promise.all(
+ operationSupplierChoices.map(([operationId, supplierProcessId]) =>
+ serviceRole
+ .from("jobOperation")
+ .update({
+ operationSupplierProcessId: supplierProcessId,
+ updatedBy: userId
+ })
+ .eq("id", operationId)
+ .eq("companyId", companyId)
+ )
+ );
+ const failedUpdate = updateResults.find((result) => result.error);
+ if (failedUpdate?.error) throw new Error(failedUpdate.error.message);
+ }
+}
diff --git a/apps/erp/app/routes/x+/priority+/batching.update.tsx b/apps/erp/app/routes/x+/priority+/batching.update.tsx
index dec79fad7e..f7653327b8 100644
--- a/apps/erp/app/routes/x+/priority+/batching.update.tsx
+++ b/apps/erp/app/routes/x+/priority+/batching.update.tsx
@@ -1,60 +1,23 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import type { Database } from "@carbon/database";
import { validationError, validator } from "@carbon/form";
-import type { SupabaseClient } from "@supabase/supabase-js";
import type { ActionFunctionArgs } from "react-router";
+import { mergeTrackedEntities } from "~/modules/inventory";
import {
createJobOperationBatch,
createJobOperationBatchValidator,
+ getBatchOutputLots,
notifyScheduleInputsChanged,
- recalculateJobRequirements,
releaseJobOperationBatch,
unreleaseJobOperationBatch,
updateJobOperationBatch,
updateJobOperationBatchValidator
} from "~/modules/production";
+import { releaseBatchMemberJobs } from "~/modules/production/production.server";
+import { getDatabaseClient } from "~/services/database.server";
import { getEdgeFunctionErrorMessage } from "~/utils/error";
-// Releasing a batch can pull a Draft/Planned job's operation onto the floor, so
-// refresh those jobs' requirements first — the same safety recalc job release
-// performs (no MRP; procurement stays a job-level decision). Returns an error
-// message, or null when every recalc succeeded.
-async function recalculateUnreleasedMemberJobs(
- client: SupabaseClient<Database>,
- jobIds: string[],
- companyId: string,
- userId: string
-): Promise<string | null> {
- const uniqueJobIds = [...new Set(jobIds)];
- if (uniqueJobIds.length === 0) return null;
-
- const jobs = await client
- .from("job")
- .select("id, status")
- .in("id", uniqueJobIds)
- .eq("companyId", companyId);
- if (jobs.error) {
- return "Failed to load the batch's jobs";
- }
-
- const serviceRole = getCarbonServiceRole();
- for (const job of jobs.data ?? []) {
- if (job.status === "Draft" || job.status === "Planned") {
- const recalc = await recalculateJobRequirements(serviceRole, {
- id: job.id,
- companyId,
- userId
- });
- if (recalc.error) {
- return `Failed to recalculate requirements for job ${job.id}`;
- }
- }
- }
- return null;
-}
-
// Fetcher-driven board action (mirrors operations.update.tsx): return
// { success, message } so BatchingBoard can toast the specific failure reason.
export async function action({ request }: ActionFunctionArgs) {
@@ -114,6 +77,60 @@ export async function action({ request }: ActionFunctionArgs) {
return { success: true };
}
+ // Merge a Completed batch's same-item output lots into one lot. The batch
+ // completion prompt covers the common case in MES; this is the ERP catch-up
+ // for batches whose prompt was skipped. Outputs are re-derived server-side —
+ // client-supplied entity ids are never trusted.
+ if (intent === "mergeOutputs") {
+ const batchId = String(formData.get("batchId") ?? "");
+ if (!batchId) {
+ return { success: false, message: "Invalid merge request" };
+ }
+ const batch = await client
+ .from("jobOperationBatch")
+ .select("id, status")
+ .eq("id", batchId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (batch.error || batch.data?.status !== "Completed") {
+ return {
+ success: false,
+ message: "Only a completed batch's output lots can be merged"
+ };
+ }
+ // One item's lots per merge: a mixed batch (A, A, B) merges its As.
+ const itemId = formData.get("itemId");
+ const outputs = await getBatchOutputLots(client, batchId, companyId);
+ if (outputs.error) {
+ return { success: false, message: "Failed to load the output lots" };
+ }
+ const lots = (outputs.data ?? []).filter(
+ (lot) => typeof itemId === "string" && lot.itemId === itemId
+ );
+ if (lots.length < 2) {
+ return { success: false, message: "No mergeable output lots" };
+ }
+ const serviceRole = await getCarbonServiceRole();
+ const merge = await mergeTrackedEntities(serviceRole, {
+ trackedEntityIds: lots.map((lot) => lot.id),
+ companyId,
+ userId
+ });
+ if (merge.error || merge.data?.error) {
+ return {
+ success: false,
+ message:
+ (merge.data?.error as string | undefined) ?? "Failed to merge lots"
+ };
+ }
+ return {
+ success: true,
+ message: merge.data?.readableId
+ ? `Lots merged into ${merge.data.readableId}`
+ : "Lots merged"
+ };
+ }
+
if (intent === "create") {
const validation = await validator(
createJobOperationBatchValidator
@@ -131,14 +148,16 @@ export async function action({ request }: ActionFunctionArgs) {
if (ops.error) {
return { success: false, message: "Failed to load the operations" };
}
- const recalcError = await recalculateUnreleasedMemberJobs(
+ const releasedJobs = await releaseBatchMemberJobs({
client,
- (ops.data ?? []).map((op) => op.jobId),
+ db: getDatabaseClient(),
+ jobIds: (ops.data ?? []).map((op) => op.jobId),
companyId,
- userId
- );
- if (recalcError) {
- return { success: false, message: recalcError };
+ userId,
+ purchaseOrdersBySupplierId: parsePurchaseOrderChoice(formData)
+ });
+ if (releasedJobs.error) {
+ return { success: false, message: releasedJobs.error };
}
}
@@ -211,16 +230,18 @@ export async function action({ request }: ActionFunctionArgs) {
if (members.error) {
return { success: false, message: "Failed to load the batch members" };
}
- // Requirements refresh BEFORE the flip (mirrors job release's ordering);
- // a failure stops the release rather than dispatching stale BOMs.
- const recalcError = await recalculateUnreleasedMemberJobs(
+ // Member jobs release BEFORE the batch flips, through the job page's
+ // release path; an invalid job refuses the whole batch untouched.
+ const releasedJobs = await releaseBatchMemberJobs({
client,
- (members.data ?? []).map((op) => op.jobId),
+ db: getDatabaseClient(),
+ jobIds: (members.data ?? []).map((op) => op.jobId),
companyId,
- userId
- );
- if (recalcError) {
- return { success: false, message: recalcError };
+ userId,
+ purchaseOrdersBySupplierId: parsePurchaseOrderChoice(formData)
+ });
+ if (releasedJobs.error) {
+ return { success: false, message: releasedJobs.error };
}
const released = await releaseJobOperationBatch(client, {
@@ -285,3 +306,18 @@ export async function action({ request }: ActionFunctionArgs) {
}
return { success: true };
}
+
+// The Release dialog's per-supplier PO choice ("new" or a Draft PO id), posted
+// as JSON. Absent when nothing needed choosing.
+function parsePurchaseOrderChoice(
+ formData: FormData
+): Record<string, string> | undefined {
+ const raw = formData.get("purchaseOrdersBySupplierId");
+ if (typeof raw !== "string" || !raw) return undefined;
+ try {
+ const parsed = JSON.parse(raw);
+ return parsed && typeof parsed === "object" ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+}
diff --git a/apps/erp/app/routes/x+/production+/batches.$batchId.tsx b/apps/erp/app/routes/x+/production+/batches.$batchId.tsx
index d0acf73437..a2a3919731 100644
--- a/apps/erp/app/routes/x+/production+/batches.$batchId.tsx
+++ b/apps/erp/app/routes/x+/production+/batches.$batchId.tsx
@@ -4,6 +4,7 @@ import { flash } from "@carbon/auth/session.server";
import type { LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData, useNavigate } from "react-router";
import {
+ getBatchOutputLots,
getJobOperationBatchEvents,
getJobOperationBatchWithMembers
} from "~/modules/production";
@@ -19,9 +20,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { batchId } = params;
if (!batchId) throw notFound("batchId not found");
- const [batch, events] = await Promise.all([
+ const [batch, events, outputLots] = await Promise.all([
getJobOperationBatchWithMembers(client, batchId, companyId),
- getJobOperationBatchEvents(client, batchId, companyId)
+ getJobOperationBatchEvents(client, batchId, companyId),
+ getBatchOutputLots(client, batchId, companyId)
]);
if (batch.error || !batch.data) {
throw redirect(
@@ -30,17 +32,22 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
- return { batch: batch.data, events: events.data ?? [] };
+ return {
+ batch: batch.data,
+ events: events.data ?? [],
+ outputLots: outputLots.data ?? []
+ };
}
export default function BatchRoute() {
- const { batch, events } = useLoaderData<typeof loader>();
+ const { batch, events, outputLots } = useLoaderData<typeof loader>();
const navigate = useNavigate();
return (
<BatchDetailDrawer
batch={batch}
events={events}
+ outputLots={outputLots}
onClose={() => navigate(-1)}
/>
);
diff --git a/apps/erp/app/routes/x+/production+/batches.release.tsx b/apps/erp/app/routes/x+/production+/batches.release.tsx
index ffa059733f..c6382865d4 100644
--- a/apps/erp/app/routes/x+/production+/batches.release.tsx
+++ b/apps/erp/app/routes/x+/production+/batches.release.tsx
@@ -1,54 +1,14 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import type { Database } from "@carbon/database";
-import type { SupabaseClient } from "@supabase/supabase-js";
import type { ActionFunctionArgs } from "react-router";
import {
notifyScheduleInputsChanged,
- recalculateJobRequirements,
releaseJobOperationBatch
} from "~/modules/production";
+import { releaseBatchMemberJobs } from "~/modules/production/production.server";
+import { getDatabaseClient } from "~/services/database.server";
import { getEdgeFunctionErrorMessage } from "~/utils/error";
-// Releasing a batch can pull a Draft/Planned job's operation onto the floor, so
-// refresh those jobs' requirements first — the same safety recalc job release
-// and the single-batch `batching.update` action perform (no MRP). Returns an
-// error message, or null when every recalc succeeded.
-async function recalculateUnreleasedMemberJobs(
- client: SupabaseClient<Database>,
- jobIds: string[],
- companyId: string,
- userId: string
-): Promise<string | null> {
- const uniqueJobIds = [...new Set(jobIds)];
- if (uniqueJobIds.length === 0) return null;
-
- const jobs = await client
- .from("job")
- .select("id, status")
- .in("id", uniqueJobIds)
- .eq("companyId", companyId);
- if (jobs.error) {
- return "Failed to load the batch's jobs";
- }
-
- const serviceRole = getCarbonServiceRole();
- for (const job of jobs.data ?? []) {
- if (job.status === "Draft" || job.status === "Planned") {
- const recalc = await recalculateJobRequirements(serviceRole, {
- id: job.id,
- companyId,
- userId
- });
- if (recalc.error) {
- return `Failed to recalculate requirements for job ${job.id}`;
- }
- }
- }
- return null;
-}
-
// Bulk release — one release per selected Planned batch. Each is independent:
// a batch the edge fn refuses (no members, already recorded production) is
// reported in `failed` while the rest still release. Only Planned batches are
@@ -102,16 +62,21 @@ export async function action({ request }: ActionFunctionArgs) {
continue;
}
- // Requirements refresh BEFORE the flip (mirrors job release's ordering); a
- // failure stops this batch's release rather than dispatching stale BOMs.
- const recalcError = await recalculateUnreleasedMemberJobs(
+ // Member jobs release first, through the job page's release path. With no
+ // dialog here, a batch with an invalid job or a PO choice to make is
+ // skipped and named — the planner releases it from its drawer.
+ const releasedJobs = await releaseBatchMemberJobs({
client,
- (members.data ?? []).map((op) => op.jobId),
+ db: getDatabaseClient(),
+ jobIds: (members.data ?? []).map((op) => op.jobId),
companyId,
userId
- );
- if (recalcError) {
- failed.push({ readableId: batch.readableId, message: recalcError });
+ });
+ if (releasedJobs.error) {
+ failed.push({
+ readableId: batch.readableId,
+ message: releasedJobs.error
+ });
continue;
}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index b0bf53cd60..6930eaa221 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -90,6 +90,14 @@ export const path = {
),
batchNumbers: (itemId: string) =>
generatePath(`${api}/inventory/batch-numbers?itemId=${itemId}`),
+ batchReleaseReadiness: (
+ target: { batchId: string } | { jobIds: string[] }
+ ) =>
+ `${api}/production/release-readiness?${
+ "batchId" in target
+ ? new URLSearchParams({ batchId: target.batchId })
+ : new URLSearchParams(target.jobIds.map((id) => ["jobId", id]))
+ }`,
billOfMaterials: (methodId: string, withOperations: boolean = false) =>
generatePath(
diff --git a/apps/erp/test/batch-suggestions.test.ts b/apps/erp/test/batch-suggestions.test.ts
index 4db75cecf5..7757cea99e 100644
--- a/apps/erp/test/batch-suggestions.test.ts
+++ b/apps/erp/test/batch-suggestions.test.ts
@@ -48,6 +48,10 @@ function makeCandidate(
id,
jobId: `job-${id}`,
jobReadableId: `J-${id}`,
+ itemId: null,
+ requiresBatchTracking: false,
+ trackedEntityId: null,
+ lotNumber: null,
jobDueDate: null,
jobStatus: "Ready",
itemReadableId: "SAT-1000",
@@ -102,6 +106,36 @@ describe("materialSignature vs groupingKey", () => {
expect(groupingKey(a)).not.toBe(groupingKey(b));
});
+ it("producedItem at guide splits signatures by produced item; default ignores it", () => {
+ const steel = makeMaterial({ substanceName: "Steel" });
+ const a = makeCandidate("a", {
+ itemReadableId: "SALAD-01",
+ materials: [steel]
+ });
+ const b = makeCandidate("b", {
+ itemReadableId: "SALAD-02",
+ materials: [steel]
+ });
+ // Default rules: produced item plays no part — same signature.
+ expect(materialSignature(a)).toBe(materialSignature(b));
+ expect(groupingKey(a)).toBe(groupingKey(b));
+ // Opted in: same materials, different produced items → different groups.
+ const rules = resolveBatchRules({ producedItem: "guide" });
+ expect(materialSignature(a, rules)).not.toBe(materialSignature(b, rules));
+ expect(groupingKey(a, rules)).not.toBe(groupingKey(b, rules));
+ // Same produced item still groups.
+ const a2 = makeCandidate("a2", {
+ itemReadableId: "SALAD-01",
+ materials: [steel]
+ });
+ expect(groupingKey(a, rules)).toBe(groupingKey(a2, rules));
+ });
+
+ it("candidateValueSets carries the produced item for must gating", () => {
+ const a = makeCandidate("a", { itemReadableId: "SALAD-01" });
+ expect(candidateValueSets(a).producedItem).toEqual(["SALAD-01"]);
+ });
+
it("ops with real materials group by properties, not by item", () => {
const steel = makeMaterial({ substanceName: "Steel", gradeName: "304" });
const a = makeCandidate("a", { itemReadableId: "P-1", materials: [steel] });
diff --git a/apps/erp/test/job-release-logic.test.ts b/apps/erp/test/job-release-logic.test.ts
new file mode 100644
index 0000000000..36afd7560e
--- /dev/null
+++ b/apps/erp/test/job-release-logic.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, it } from "vitest";
+import {
+ makeMethodsMissingOperations,
+ outsideOperationsNeedingPurchaseOrders,
+ resolveOperationSupplier,
+ type SupplierProcessRef
+} from "../app/modules/production/ui/Jobs/job-release-logic";
+
+const op = (
+ id: string,
+ jobMakeMethodId: string,
+ operationType = "Process",
+ operationSupplierProcessId: string | null = null
+) => ({ id, jobMakeMethodId, operationType, operationSupplierProcessId });
+
+describe("makeMethodsMissingOperations", () => {
+ it("flags the root and make-to-order sub-assemblies without operations", () => {
+ const materials = [
+ { jobMaterialMakeMethodId: "sub1", methodType: "Make to Order", kit: false },
+ { jobMaterialMakeMethodId: "sub2", methodType: "Make to Order", kit: false },
+ { jobMaterialMakeMethodId: null, methodType: "Pull from Inventory", kit: false }
+ ];
+ expect(
+ makeMethodsMissingOperations("root", materials, [op("o1", "sub1")]).sort()
+ ).toEqual(["root", "sub2"]);
+ });
+
+ it("does not require operations on kitted sub-assemblies", () => {
+ const materials = [
+ { jobMaterialMakeMethodId: "kit1", methodType: "Make to Order", kit: true }
+ ];
+ expect(
+ makeMethodsMissingOperations("root", materials, [op("o1", "root")])
+ ).toEqual([]);
+ });
+});
+
+describe("outsideOperationsNeedingPurchaseOrders", () => {
+ it("keeps outside operations with no PO line yet, supplier or not", () => {
+ const ops = [
+ op("a", "root", "Outside Processing", "sp1"),
+ op("b", "root", "Outside Processing", "sp2"),
+ op("c", "root", "Outside Processing", null),
+ op("d", "root", "Process", "sp3")
+ ];
+ expect(
+ outsideOperationsNeedingPurchaseOrders(ops, new Set(["b"])).map((o) => o.id)
+ ).toEqual(["a", "c"]);
+ });
+});
+
+describe("resolveOperationSupplier", () => {
+ const sp = (id: string, processId: string): SupplierProcessRef => ({
+ id,
+ supplierId: `sup-${id}`,
+ processId
+ });
+ const byId = new Map([["own", sp("own", "plating")]]);
+ const byProcess = new Map([
+ ["anodize", [sp("a1", "anodize")]],
+ ["heat", [sp("h1", "heat"), sp("h2", "heat")]]
+ ]);
+
+ it("uses the operation's own supplier process first", () => {
+ expect(
+ resolveOperationSupplier(
+ { operationSupplierProcessId: "own", processId: "heat" },
+ byId,
+ byProcess
+ )
+ ).toEqual({ supplierProcess: byId.get("own") });
+ });
+
+ it("falls back to the process's sole supplier", () => {
+ expect(
+ resolveOperationSupplier(
+ { operationSupplierProcessId: null, processId: "anodize" },
+ byId,
+ byProcess
+ )
+ ).toEqual({ supplierProcess: sp("a1", "anodize") });
+ });
+
+ it("asks for a choice when the process has several, and flags none", () => {
+ expect(
+ resolveOperationSupplier(
+ { operationSupplierProcessId: null, processId: "heat" },
+ byId,
+ byProcess
+ )
+ ).toEqual({ missing: "choose" });
+ expect(
+ resolveOperationSupplier(
+ { operationSupplierProcessId: null, processId: "paint" },
+ byId,
+ byProcess
+ )
+ ).toEqual({ missing: "none" });
+ });
+});
diff --git a/apps/mes/app/components/AssemblyView.tsx b/apps/mes/app/components/AssemblyView.tsx
index 55e10af9f4..162e0d3e14 100644
--- a/apps/mes/app/components/AssemblyView.tsx
+++ b/apps/mes/app/components/AssemblyView.tsx
@@ -82,12 +82,7 @@ import {
LuWrench,
LuX
} from "react-icons/lu";
-import {
- useFetcher,
- useNavigate,
- useRevalidator,
- useSearchParams
-} from "react-router";
+import { useFetcher, useNavigate, useSearchParams } from "react-router";
import { TrackingTypeIcon } from "~/components/Icons";
import { ImageZoomViewer } from "~/components/ImageZoomViewer";
import { OperationChat } from "~/components/JobOperation/components/Chat";
@@ -98,7 +93,7 @@ import { QuantityModal } from "~/components/JobOperation/components/QuantityModa
import { ReworkModal } from "~/components/JobOperation/components/ReworkModal";
import { SerialSelectorModal } from "~/components/JobOperation/components/SerialSelectorModal";
import { RecordModal } from "~/components/JobOperation/components/Step";
-import { useUser } from "~/hooks";
+import { useRealtimeRevalidator, useUser } from "~/hooks";
import { isSerialEntityIncompleteForOperation } from "~/services/operations.service";
import type {
JobMaterial,
@@ -524,7 +519,7 @@ export function AssemblyView({
const { carbon } = useCarbon();
const mode = useMode();
const navigate = useNavigate();
- const revalidator = useRevalidator();
+ const revalidate = useRealtimeRevalidator();
const [searchParams, setSearchParams] = useSearchParams();
// Which main panel is shown: the assembly details, the 3D model, or chat.
const [tab, setTab] = useState<"details" | "model" | "chat">("details");
@@ -569,7 +564,7 @@ export function AssemblyView({
topic: `assembly:${operationId}`,
dependencies: [operationId],
setup(channel) {
- const refresh = () => revalidator.revalidate();
+ const refresh = () => revalidate();
return channel
.on(
"postgres_changes",
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index 0b4b33042e..baeedbc03f 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -5,6 +5,9 @@ import { convertKbToString } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
Badge,
BarProgress,
BottomSheet,
@@ -66,15 +69,15 @@ import { useOptimizedModel } from "@carbon/viewer/use-optimized-model";
import { parseDate } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestSingleResponse } from "@supabase/supabase-js";
-import { Suspense, useEffect, useMemo, useState } from "react";
+import { Suspense, useCallback, useEffect, useMemo, useState } from "react";
import { flushSync } from "react-dom";
-import { FaTasks } from "react-icons/fa";
import { FaCheck, FaPlus, FaTrash } from "react-icons/fa6";
import {
LuArrowLeft,
LuAxis3D,
LuBarcode,
LuCheck,
+ LuChevronDown,
LuChevronLeft,
LuChevronRight,
LuCirclePlay,
@@ -84,8 +87,6 @@ import {
LuEllipsisVertical,
LuGitBranchPlus,
LuGitPullRequest,
- LuHammer,
- LuHardHat,
LuLayers,
LuPackageCheck,
LuPrinter,
@@ -111,7 +112,11 @@ import {
} from "~/components/Icons";
import { useDateFormatter, useUrlParams, useUser } from "~/hooks";
import type { productionEventType } from "~/services/models";
-import type { JobOperationBatch } from "~/services/operations.service";
+import type {
+ BatchMaterialTotal,
+ BatchWorkInstructions,
+ JobOperationBatch
+} from "~/services/operations.service";
import { getFileType } from "~/services/operations.service";
import type {
Job,
@@ -131,6 +136,7 @@ import { makeDurations } from "~/utils/durations";
import { getPrivateUrl, getRawModelUrl, path } from "~/utils/path";
import ItemThumbnail from "../ItemThumbnail";
import { BatchCompleteModal } from "./components/BatchCompleteModal";
+import { BatchOverview } from "./components/BatchOverview";
import { OperationChat } from "./components/Chat";
import {
Controls,
@@ -155,6 +161,8 @@ import { TableSkeleton } from "./components/TableSkeleton";
import { useFiles } from "./hooks/useFiles";
import { useOperation } from "./hooks/useOperation";
+const DOCK_COLLAPSED_KEY = "mes:operation-dock-collapsed";
+
const log = getLogger("mes", "job-operation");
type JobOperationProps = {
@@ -162,6 +170,10 @@ type JobOperationProps = {
// resolves it and swaps in the batch's events. In batch mode the timers and
// completion act on the whole batch.
batch: JobOperationBatch | null;
+ // Batch mode: the combined per-item requirement/issued across every member,
+ // so the materials panel shows the one shared pick (e.g. 6,500 seeds).
+ batchMaterialTotals?: Record<string, BatchMaterialTotal> | null;
+ batchWorkInstructions?: Promise<BatchWorkInstructions> | null;
events: ProductionEvent[];
expiredEntityPolicy?: "Warn" | "Block" | "BlockWithOverride";
autoSelectMaterialWithoutPickingList?: boolean;
@@ -279,6 +291,8 @@ function PickedBreakdown({
export const JobOperation = ({
batch,
+ batchMaterialTotals,
+ batchWorkInstructions,
events,
expiredEntityPolicy = "Block",
autoSelectMaterialWithoutPickingList = false,
@@ -310,13 +324,69 @@ export const JobOperation = ({
// Start/Stop timer, planned durations, and completion all act on the whole
// batch rather than this single member.
const isBatched = !!batch;
+ // A batched operation opens on the whole batch; "?scope=job" narrows to this
+ // job's own details. Kept in the URL so a member link can land on either.
+ const scope: "batch" | "job" =
+ isBatched && params.get("scope") !== "job" ? "batch" : "job";
const isCompleting = batch?.status === "Completing";
+ // What the header and dock say about the batch as a whole — never one
+ // member's values, which is what made the batch scope read as a job.
+ const batchFacts = useMemo(() => {
+ if (!batch) return null;
+ const members = batch.operations ?? [];
+ const jobs = members.map(
+ (m) =>
+ m.job as {
+ deadlineType?: 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
+ .filter(
+ (m, i) =>
+ m.dueDate &&
+ !["ASAP", "No Deadline"].includes(jobs[i]?.deadlineType ?? "")
+ )
+ .map((m) => m.dueDate as string)
+ .sort();
+ return {
+ customers: unique(jobs.map((j) => j?.customer?.name)),
+ items: unique(
+ members.map((m) => m.jobMakeMethod?.item?.readableIdWithRevision)
+ ),
+ dueDate: dueDates[0] ?? null,
+ deadline: dueDates[0]
+ ? null
+ : jobs.some((j) => j?.deadlineType === "ASAP")
+ ? "ASAP"
+ : "No Deadline"
+ };
+ }, [batch]);
+ // Same instant comparison the job's own deadline uses (useOperation).
+ const batchOverdue = batchFacts?.dueDate
+ ? new Date(batchFacts.dueDate) < new Date()
+ : false;
const batchCompleteModal = useDisclosure();
+ // The completion fetcher lives HERE, not in BatchCompleteModal: a successful
+ // completion flips the batch out of Active/Completing, the loader stops
+ // passing `batch`, and the modal unmounts mid-flight.
+ const batchCompleteFetcher = useFetcher<{ completed?: boolean }>();
const serialIndex =
trackedEntities.findIndex((entity) => entity.id === trackedEntityId) ?? 0;
const navigate = useNavigate();
+ useEffect(() => {
+ if (
+ batchCompleteFetcher.state === "idle" &&
+ batchCompleteFetcher.data?.completed
+ ) {
+ navigate(path.to.operations);
+ }
+ }, [batchCompleteFetcher.state, batchCompleteFetcher.data, navigate]);
const { carbon } = useCarbon();
const {
id: userId,
@@ -384,6 +454,14 @@ export const JobOperation = ({
setParams({ trackedEntityId: entity.id });
}
});
+ // Batch mode: the selected material's outstanding requirement ACROSS the
+ // batch — the shared pick is split pro-rata over every member, so defaulting
+ // to one member's share would under-serve all of them.
+ const selectedBatchRemaining = (() => {
+ if (!isBatched || !selectedMaterial?.itemId) return undefined;
+ const totals = batchMaterialTotals?.[selectedMaterial.itemId];
+ return totals ? Math.max(0, totals.required - totals.issued) : undefined;
+ })();
// 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), the
@@ -456,21 +534,56 @@ export const JobOperation = ({
: 0;
const isBehindTarget = daysBehindTarget > 0;
- const controlsHeight = useMemo(() => {
- let operations = 1;
- if (displayOperation.setupDuration > 0) operations++;
- if (displayOperation.laborDuration > 0) operations++;
- if (displayOperation.machineDuration > 0) operations++;
- return 60 + operations * 36;
- }, [
- displayOperation.laborDuration,
- displayOperation.machineDuration,
- displayOperation.setupDuration
- ]);
+ // The status bar's quantity meter counts the whole run when batched.
+ const quantityProgress = useMemo(() => {
+ if (!batch) {
+ return {
+ complete: operation.quantityComplete,
+ target: operation.targetQuantity,
+ reworked: operation.quantityReworked ?? 0,
+ scrapped: operation.quantityScrapped ?? 0
+ };
+ }
+ const members = batch.operations ?? [];
+ return {
+ complete: members.reduce((n, m) => n + (m.quantityComplete ?? 0), 0),
+ target: members.reduce((n, m) => n + (m.operationQuantity ?? 0), 0),
+ reworked: 0,
+ scrapped: members.reduce((n, m) => n + (m.quantityScrapped ?? 0), 0)
+ };
+ }, [batch, operation]);
- // The side control panel only exists on some tabs; content reserves space for
- // it via --controls-gutter so the two never overlap.
- const showControls = !["chat", "procedure"].includes(activeTab);
+ // The action panel only exists on some tabs.
+ const workTypeLabels = {
+ setup: t`Setup`,
+ labor: t`Labor`,
+ machine: t`Machine`
+ } as const;
+ const runningType = (["setup", "labor", "machine"] as const).find(
+ (type) => active[type]
+ );
+ // Chat is one job's thread, so a Chat tab left open in the job scope falls
+ // back to Details on the batch.
+ const tab = scope === "batch" && activeTab === "chat" ? "details" : activeTab;
+ const showControls = !["chat", "procedure"].includes(tab);
+ // Read after mount (never during render) so SSR and the first client
+ // render agree; storage can throw in private/locked-down browsers.
+ const [dockCollapsed, setDockCollapsed] = useState(false);
+ useEffect(() => {
+ try {
+ setDockCollapsed(localStorage.getItem(DOCK_COLLAPSED_KEY) === "true");
+ } catch {
+ // storage unavailable: keep the default (expanded)
+ }
+ }, []);
+ const onDockCollapsedChange = useCallback((collapsed: boolean) => {
+ setDockCollapsed(collapsed);
+ try {
+ localStorage.setItem(DOCK_COLLAPSED_KEY, String(collapsed));
+ } catch {
+ // storage unavailable: the choice lasts for this page only
+ }
+ }, []);
const mode = useMode();
const { operationId } = useParams();
@@ -626,23 +739,56 @@ export const JobOperation = ({
const item = items.find((it) => it.id === operation.itemId);
+ // Mounted by BOTH the per-job materials table and the batch overview —
+ // the batch scope's Pick opens the same shared-pick modal.
+ const renderIssueModal = (
+ resolvedMaterials: Awaited<typeof materials> | undefined
+ ) =>
+ issueModal.isOpen ? (
+ <IssueMaterialModal
+ operationId={operation.id}
+ // The process view issues the whole quantity at
+ // once, so picked lots may pre-fill when the
+ // parent is a single entity. The modal enforces
+ // the full rule: a picking list exists AND (the
+ // parent is not serialized OR the operation
+ // makes exactly one unit).
+ allowPrefill
+ parentUnitCount={operation.operationQuantity ?? undefined}
+ expiredEntityPolicy={expiredEntityPolicy}
+ autoSelectMaterialWithoutPickingList={
+ autoSelectMaterialWithoutPickingList
+ }
+ locationId={locationId}
+ workCenterId={operation.workCenterId ?? undefined}
+ material={selectedMaterial ?? undefined}
+ batchId={batch?.id ?? undefined}
+ batchRemainingQuantity={selectedBatchRemaining}
+ parentId={trackedEntityId ?? ""}
+ parentIdIsSerialized={method?.requiresSerialTracking ?? false}
+ trackedInputs={resolvedMaterials?.trackedInputs ?? []}
+ onClose={() => {
+ setSelectedMaterial(null);
+ issueModal.onClose();
+ }}
+ />
+ ) : null;
+
return (
<>
<Tabs
key={`operation-${operation.id}`}
- value={activeTab}
+ value={tab}
onValueChange={setActiveTab}
- // Below lg the page scrolls (Controls stacks inline). A fixed h-screen
- // box would clip that overflow; grow with content on small viewports.
- className="w-full min-w-0 min-h-screen h-auto lg:h-screen bg-card relative"
- style={
- {
- "--controls-height": `${controlsHeight}px`,
- "--controls-gutter": showControls ? "var(--controls-width)" : "0px"
- } as React.CSSProperties
- }
+ // An application shell, not a page: a grid of named areas where each
+ // pane scrolls on its own, so nothing is positioned or sized by hand.
+ // Below lg the dock is a bottom action bar; from lg it is a column
+ // beside the workspace and status bar. The outlet frame is only
+ // min-height bounded (other MES screens page-scroll), so the shell takes
+ // the viewport itself, less the frame's md:my-2 inset.
+ className="grid h-svh md:h-[calc(100svh-1rem)] min-h-0 w-full min-w-0 bg-card grid-cols-[minmax(0,1fr)] grid-rows-[auto_auto_auto_minmax(0,1fr)_auto_auto] [grid-template-areas:'header'_'context'_'sep'_'main'_'status'_'dock'] lg:grid-cols-[minmax(0,1fr)_auto] lg:grid-rows-[auto_auto_auto_minmax(0,1fr)_auto] lg:[grid-template-areas:'header_header'_'context_context'_'sep_sep'_'main_dock'_'status_dock']"
>
- <header className="flex h-[var(--header-height)] shrink-0 items-center gap-2 transition-[width,height] ease-linear group-has-[[data-collapsible=icon]]/sidebar-wrapper:h-12 border-b px-2">
+ <header className="[grid-area:header] flex h-[var(--header-height)] shrink-0 items-center gap-2 transition-[width,height] ease-linear group-has-[[data-collapsible=icon]]/sidebar-wrapper:h-12 border-b px-2">
<HStack className="w-full justify-between">
<div className="flex items-center gap-0">
<SidebarTrigger />
@@ -656,8 +802,8 @@ export const JobOperation = ({
<Trans>Schedule</Trans>
</Button>
</div>
- <div className="flex flex-shrink-0 items-center justify-end gap-2">
- <TabsList className="md:ml-auto">
+ <div className="flex min-w-0 items-center gap-2 overflow-x-auto scrollbar-hide scroll-fade-x">
+ <TabsList className="ml-auto shrink-0">
<TabsTrigger value="details">
<Trans>Details</Trans>
</TabsTrigger>
@@ -670,7 +816,9 @@ export const JobOperation = ({
<TabsTrigger value="procedure">
<Trans>Instructions</Trans>
</TabsTrigger>
- <TabsTrigger value="chat">
+ {/* Notes are kept per job operation — on the batch there is no
+ one thread to show, so Chat opens from a job. */}
+ <TabsTrigger value="chat" disabled={scope === "batch"}>
<Trans>Chat</Trans>
</TabsTrigger>
</TabsList>
@@ -678,120 +826,188 @@ export const JobOperation = ({
</HStack>
</header>
- <div className="flex flex-nowrap items-center justify-between px-4 lg:pl-6 py-2 min-h-[var(--header-height)] bg-card gap-2 md:gap-4 w-full min-w-0 overflow-hidden">
+ <div className="[grid-area:context] flex shrink-0 flex-wrap lg:flex-nowrap items-center justify-start px-4 lg:pl-6 py-2 min-h-[var(--header-height)] bg-card gap-x-2 gap-y-1 md:gap-x-4 w-full min-w-0">
<HStack className="min-w-22 shrink-0 justify-between">
- <Heading size="h4">{operation.jobReadableId}</Heading>
-
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- aria-label="More options"
- variant="ghost"
- icon={<LuEllipsisVertical />}
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start">
- <DropdownMenuItem asChild>
- <a
- href={path.to.file.jobTraveler(operation.jobMakeMethodId)}
- target="_blank"
- rel="noreferrer"
- >
- <DropdownMenuIcon icon={<LuQrCode />} />
- <Trans>Job Traveler</Trans>
- </a>
- </DropdownMenuItem>
- <DropdownMenuItem asChild>
- <Link to={path.to.jobDetail(operation.jobId)}>
- <DropdownMenuIcon icon={<LuCirclePlay />} />
- <Trans>Job Details</Trans>
- </Link>
- </DropdownMenuItem>
- {item && (
- <DropdownMenuItem asChild>
- <Link to={path.to.itemMaster(item?.id, item.type)}>
- <DropdownMenuIcon
- icon={<MethodItemTypeIcon type={item.type} />}
- />
- <Trans>Item Master</Trans>
- </Link>
- </DropdownMenuItem>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- </HStack>
-
- {batch && (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
+ {batch ? (
+ // One control for "which part of the batch am I looking at":
+ // the batch, this job, or (via the chevron) another member job.
+ <div className="flex shrink-0 items-center rounded-full border bg-card p-0.5 text-sm">
<button
type="button"
- className="flex items-center gap-1.5 rounded-full border bg-card px-3 py-1 text-sm shrink-0 active:scale-[0.98] transition-transform"
+ aria-pressed={scope === "batch"}
+ aria-label={t`Whole batch`}
+ onClick={() => setParams({ scope: "" })}
+ className={cn(
+ "flex items-center gap-1.5 rounded-full px-3 py-1 transition-[background-color,color,transform] active:scale-[0.98]",
+ scope === "batch"
+ ? "bg-accent text-foreground"
+ : "text-muted-foreground hover:text-foreground"
+ )}
>
- <LuLayers className="size-3.5 text-muted-foreground" />
+ <LuLayers className="size-3.5" />
<span className="font-medium tabular-nums">
{batch.readableId}
</span>
- <span className="text-muted-foreground">
+ <span className="opacity-60">
{t`${(batch.operations ?? []).length} jobs`}
</span>
{isCompleting && (
- <Badge variant="yellow" className="ml-1">
+ <Badge variant="yellow" className="ml-0.5">
<Trans>Completing</Trans>
</Badge>
)}
</button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-pressed={scope === "job"}
+ aria-label={t`Choose a job`}
+ className={cn(
+ "flex items-center gap-1 rounded-full py-1 pl-3 pr-2 font-medium transition-[background-color,color,transform] active:scale-[0.98]",
+ scope === "job"
+ ? "bg-accent text-foreground"
+ : "text-muted-foreground hover:text-foreground"
+ )}
+ >
+ {scope === "job" ? (
+ operation.jobReadableId
+ ) : (
+ <Trans>Jobs</Trans>
+ )}
+ <LuChevronDown className="size-3.5" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="min-w-[240px]">
+ <DropdownMenuLabel>
+ <Trans>Open a job in this batch</Trans>
+ </DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ {[...(batch.operations ?? [])]
+ .sort((a, b) =>
+ (
+ (a.job as { jobId?: string | null } | null)?.jobId ??
+ ""
+ ).localeCompare(
+ (b.job as { jobId?: string | null } | null)?.jobId ??
+ "",
+ undefined,
+ { numeric: true }
+ )
+ )
+ .map((member) => {
+ const isOpen =
+ scope === "job" && member.id === operation.id;
+ return (
+ <DropdownMenuItem key={member.id} asChild>
+ <Link
+ to={`${path.to.operation(member.id)}?scope=job`}
+ >
+ <DropdownMenuIcon
+ icon={
+ isOpen ? (
+ <LuCheck className="text-emerald-500" />
+ ) : (
+ <LuClipboardCheck />
+ )
+ }
+ />
+ <span className="truncate">
+ {(
+ member.job as { jobId?: string | null } | null
+ )?.jobId ?? member.id}
+ {member.jobMakeMethod?.item
+ ?.readableIdWithRevision
+ ? ` — ${member.jobMakeMethod.item.readableIdWithRevision}`
+ : ""}
+ </span>
+ </Link>
+ </DropdownMenuItem>
+ );
+ })}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ ) : (
+ <Heading size="h4">{operation.jobReadableId}</Heading>
+ )}
+
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More options"
+ variant="ghost"
+ icon={<LuEllipsisVertical />}
+ />
</DropdownMenuTrigger>
- <DropdownMenuContent align="start" className="min-w-[240px]">
- <DropdownMenuLabel>
- <Trans>Batched jobs</Trans>
- </DropdownMenuLabel>
- <DropdownMenuSeparator />
- {(batch.operations ?? []).map((member) => {
- const isCurrent = member.id === operation.id;
- return (
- <DropdownMenuItem key={member.id} asChild>
- <Link to={path.to.operation(member.id)}>
+ <DropdownMenuContent align="start">
+ {scope === "job" && (
+ <DropdownMenuItem asChild>
+ <a
+ href={path.to.file.jobTraveler(operation.jobMakeMethodId)}
+ target="_blank"
+ rel="noreferrer"
+ >
+ <DropdownMenuIcon icon={<LuQrCode />} />
+ <Trans>Job Traveler</Trans>
+ </a>
+ </DropdownMenuItem>
+ )}
+ {scope === "job" && (
+ <DropdownMenuItem asChild>
+ <Link to={path.to.jobDetail(operation.jobId)}>
+ <DropdownMenuIcon icon={<LuCirclePlay />} />
+ <Trans>Job Details</Trans>
+ </Link>
+ </DropdownMenuItem>
+ )}
+ {scope === "batch" && batch && (
+ <DropdownMenuItem asChild>
+ <a
+ href={path.to.file.batchList(batch.id as string)}
+ target="_blank"
+ rel="noreferrer"
+ >
+ <DropdownMenuIcon icon={<LuPrinter />} />
+ <Trans>Print batch list</Trans>
+ </a>
+ </DropdownMenuItem>
+ )}
+ {item &&
+ (scope === "job" || batchFacts?.items.length === 1) && (
+ <DropdownMenuItem asChild>
+ <Link to={path.to.itemMaster(item?.id, item.type)}>
<DropdownMenuIcon
- icon={
- isCurrent ? (
- <LuCheck className="text-emerald-500" />
- ) : (
- <LuClipboardCheck />
- )
- }
+ icon={<MethodItemTypeIcon type={item.type} />}
/>
- <span className="truncate">
- {(member.job as { jobId?: string | null } | null)
- ?.jobId ?? member.id}
- {member.description ? ` — ${member.description}` : ""}
- </span>
+ <Trans>Item Master</Trans>
</Link>
</DropdownMenuItem>
- );
- })}
- <DropdownMenuSeparator />
- <DropdownMenuItem asChild>
- <a
- href={path.to.file.batchList(batch.id as string)}
- target="_blank"
- rel="noreferrer"
- >
- <DropdownMenuIcon icon={<LuPrinter />} />
- <Trans>Print batch list</Trans>
- </a>
- </DropdownMenuItem>
+ )}
</DropdownMenuContent>
</DropdownMenu>
- )}
+ </HStack>
- <HStack className="hidden lg:flex min-w-0 flex-1 justify-end items-center gap-3 overflow-hidden">
- {job.customer?.name && (
- <HStack className="min-w-0 justify-start space-x-2">
- <LuSquareUser className="text-muted-foreground shrink-0" />
- <span className="text-sm truncate">{job.customer.name}</span>
- </HStack>
- )}
+ <HStack className="flex w-full lg:w-auto min-w-0 lg:flex-1 justify-start lg:justify-end items-center gap-3 overflow-x-auto lg:overflow-hidden scrollbar-hide scroll-fade-x [&>*]:shrink-0 lg:[&>*]:shrink">
+ {scope === "batch" && batchFacts
+ ? batchFacts.customers.length > 0 && (
+ <HStack className="min-w-0 justify-start space-x-2">
+ <LuSquareUser className="text-muted-foreground shrink-0" />
+ <span className="text-sm truncate">
+ {batchFacts.customers.length === 1
+ ? batchFacts.customers[0]
+ : t`${batchFacts.customers.length} customers`}
+ </span>
+ </HStack>
+ )
+ : job.customer?.name && (
+ <HStack className="min-w-0 justify-start space-x-2">
+ <LuSquareUser className="text-muted-foreground shrink-0" />
+ <span className="text-sm truncate">
+ {job.customer.name}
+ </span>
+ </HStack>
+ )}
{operation.description && (
<HStack className="min-w-0 justify-start space-x-2">
<LuClipboardCheck className="text-muted-foreground shrink-0" />
@@ -800,21 +1016,30 @@ export const JobOperation = ({
</span>
</HStack>
)}
- {operation.operationStatus && (
+ {scope === "batch" && batch ? (
<HStack className="min-w-0 shrink-0 justify-start space-x-2">
- <OperationStatusIcon
- status={
- operation.jobStatus === "Paused"
- ? "Paused"
- : operation.operationStatus
- }
- />
+ <LuLayers className="text-muted-foreground shrink-0" />
<span className="text-sm truncate">
- {operation.jobStatus === "Paused"
- ? "Paused"
- : operation.operationStatus}
+ {isCompleting ? t`Completing` : t`Released`}
</span>
</HStack>
+ ) : (
+ operation.operationStatus && (
+ <HStack className="min-w-0 shrink-0 justify-start space-x-2">
+ <OperationStatusIcon
+ status={
+ operation.jobStatus === "Paused"
+ ? "Paused"
+ : operation.operationStatus
+ }
+ />
+ <span className="text-sm truncate">
+ {operation.jobStatus === "Paused"
+ ? "Paused"
+ : operation.operationStatus}
+ </span>
+ </HStack>
+ )
)}
{/* Batch mode shows the batch's planned total (shared setup +
summed work); a zero plan renders nothing rather than
@@ -828,43 +1053,64 @@ export const JobOperation = ({
</span>
</HStack>
)}
- {operation.jobDeadlineType && (
+ {scope === "batch" && batchFacts ? (
<HStack className="min-w-0 shrink-0 justify-start space-x-2">
<DeadlineIcon
- deadlineType={operation.jobDeadlineType}
- overdue={isOverdue}
+ deadlineType={
+ (batchFacts.deadline ??
+ "Hard Deadline") as typeof operation.jobDeadlineType
+ }
+ overdue={batchOverdue}
/>
-
<span
className={cn(
"text-sm truncate",
- isOverdue ? "text-red-500" : ""
+ batchOverdue ? "text-red-500" : ""
)}
>
- {["ASAP", "No Deadline"].includes(operation.jobDeadlineType)
- ? operation.jobDeadlineType
- : operation.operationDueDate
- ? t`Due ${formatRelativeTime(
- convertDateStringToIsoString(
- operation.operationDueDate
- )
- )}`
- : "–"}
+ {batchFacts.dueDate
+ ? t`First due ${formatRelativeTime(
+ convertDateStringToIsoString(batchFacts.dueDate)
+ )}`
+ : batchFacts.deadline}
</span>
</HStack>
+ ) : (
+ operation.jobDeadlineType && (
+ <HStack className="min-w-0 shrink-0 justify-start space-x-2">
+ <DeadlineIcon
+ deadlineType={operation.jobDeadlineType}
+ overdue={isOverdue}
+ />
+
+ <span
+ className={cn(
+ "text-sm truncate",
+ isOverdue ? "text-red-500" : ""
+ )}
+ >
+ {["ASAP", "No Deadline"].includes(operation.jobDeadlineType)
+ ? operation.jobDeadlineType
+ : operation.operationDueDate
+ ? t`Due ${formatRelativeTime(
+ convertDateStringToIsoString(
+ operation.operationDueDate
+ )
+ )}`
+ : "–"}
+ </span>
+ </HStack>
+ )
)}
</HStack>
</div>
- <Separator />
-
- <TabsContent value="details" className="flex flex-col">
- {/*
- Native scrollport (not Radix ScrollArea): below lg height is auto so
- Files/Serials participate in page scroll with the stacked Controls.
- At lg+ a fixed height + overflow-y-auto docks beside absolute Controls.
- (#959)
- */}
- <div className="w-full min-w-0 lg:pr-[var(--controls-gutter)] h-auto lg:h-[calc(100dvh-var(--header-height)*2-var(--controls-height)-2rem)] overflow-y-visible lg:overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
+ <Separator className="[grid-area:sep]" />
+
+ <TabsContent
+ value="details"
+ className="[grid-area:main] mt-0 h-full min-h-0 overflow-y-auto scroll-fade scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
+ >
+ <div className="w-full min-w-0">
{isCompleting && (
<div className="px-4 pt-4 lg:px-6">
<Card>
@@ -885,728 +1131,595 @@ export const JobOperation = ({
</Card>
</div>
)}
- <div className="flex items-start justify-between gap-4 p-4 lg:p-6">
- <HStack className="min-w-0">
- {thumbnailPath && (
- <ItemThumbnail thumbnailPath={thumbnailPath} size="xl" />
- )}
- <div className="flex flex-col flex-grow min-w-0">
- <HStack spacing={2}>
- <Heading size="h3" className="line-clamp-1">
- {operation.description}
- </Heading>
- {operation.reworkId && <Badge variant="red">Rework</Badge>}
- </HStack>
- <p className="text-muted-foreground line-clamp-1">
- {operation.itemReadableId}
- </p>
- </div>
- </HStack>
- <div className="flex flex-col shrink-0 items-end">
- <Heading size="h2">
- {formatDurationMilliseconds(
- ((progress.setup ?? 0) +
- (progress.labor ?? 0) +
- (progress.machine ?? 0)) /
- // Batch mode: the timer is shared, so the per-piece rate
- // is elapsed over ALL members' completed parts — a
- // quantity-weighted average, matching how completion
- // slices the shared time (weight = operationQuantity).
- Math.max(
- batch
- ? (batch.operations ?? []).reduce(
- (sum, m) => sum + (m.quantityComplete ?? 0),
- 0
- )
- : operation.quantityComplete,
- 1
- ),
- {
- style: "short"
- }
- )}
- </Heading>
- <p className="text-muted-foreground line-clamp-1">
- {operation.itemUnitOfMeasure}
- </p>
+ {scope === "job" && batch && (
+ <div className="px-4 pt-4 lg:px-6">
+ <Alert>
+ <LuLayers />
+ <AlertTitle>
+ <Trans>
+ {operation.jobReadableId} runs in batch {batch.readableId}
+ </Trans>
+ </AlertTitle>
+ <AlertDescription>
+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
+ <span className="text-pretty">
+ <Trans>
+ The timer and completion are shared by all{" "}
+ {(batch.operations ?? []).length} jobs. Steps,
+ materials and files here are this job's own.
+ </Trans>
+ </span>
+ <Button
+ variant="secondary"
+ leftIcon={<LuChevronLeft />}
+ onClick={() => setParams({ scope: "" })}
+ >
+ <Trans>Back to batch</Trans>
+ </Button>
+ </div>
+ </AlertDescription>
+ </Alert>
</div>
- </div>
- <Separator />
- <div className="flex items-start p-4 lg:p-6">
- <div className="grid gap-4 grid-cols-1 md:grid-cols-2 xl:grid-cols-3 w-full min-w-0">
- <Card>
- <CardHeader className="flex flex-row items-center gap-2 justify-between">
- <CardTitle>
- <Trans>Completed</Trans>
- </CardTitle>
- <FaCheck className="h-3 w-3 text-emerald-500" />
- </CardHeader>
-
- <CardContent>
- <Heading size="h1">
- <Trans>
- {operation.quantityComplete} of{" "}
- {operation.targetQuantity}
- </Trans>
- </Heading>
- </CardContent>
- </Card>
- <Card>
- <CardHeader className="flex flex-row items-center gap-2 justify-between">
- <CardTitle>
- <Trans>Scrapped</Trans>
- </CardTitle>
- <FaTrash className="h-3 w-3 text-muted-foreground" />
- </CardHeader>
- <CardContent>
- <Heading size="h1">{operation.quantityScrapped}</Heading>
- </CardContent>
- </Card>
- <Card>
- <CardHeader className="flex flex-row items-center gap-2 justify-between">
- <CardTitle>
- <Trans>Due Date</Trans>
- </CardTitle>
- <DeadlineIcon
- deadlineType={operation.jobDeadlineType}
- overdue={isOverdue}
- />
- </CardHeader>
- <CardContent>
- <VStack className="justify-start" spacing={0}>
- <Heading
- size="h3"
- className={cn(
- "w-full truncate",
- isOverdue ? "text-red-500" : ""
+ )}
+ {scope === "batch" && batch ? (
+ <Suspense
+ key={`batch-overview-${operationId}`}
+ fallback={<TableSkeleton />}
+ >
+ <Await resolve={materials}>
+ {(resolvedMaterials) => (
+ <>
+ <BatchOverview
+ batch={batch}
+ totals={batchMaterialTotals ?? {}}
+ currentMaterials={resolvedMaterials?.materials ?? []}
+ onIssue={(material) => {
+ flushSync(() => {
+ setSelectedMaterial(material);
+ });
+ issueModal.onOpen();
+ }}
+ workInstructions={batchWorkInstructions}
+ onDownloadFile={downloadFile}
+ />
+ {renderIssueModal(resolvedMaterials)}
+ </>
+ )}
+ </Await>
+ </Suspense>
+ ) : (
+ <>
+ <div className="flex items-start justify-between gap-4 p-4 lg:p-6">
+ <HStack className="min-w-0">
+ {thumbnailPath && (
+ <ItemThumbnail thumbnailPath={thumbnailPath} size="xl" />
+ )}
+ <div className="flex flex-col flex-grow min-w-0">
+ <HStack spacing={2}>
+ <Heading size="h3" className="line-clamp-1">
+ {operation.description}
+ </Heading>
+ {operation.reworkId && (
+ <Badge variant="red">Rework</Badge>
)}
- >
- {["ASAP", "No Deadline"].includes(
- operation.jobDeadlineType
- )
- ? operation.jobDeadlineType
- : operation.operationDueDate
- ? t`Due ${formatRelativeTime(
- convertDateStringToIsoString(
- operation.operationDueDate
+ </HStack>
+ <p className="text-muted-foreground line-clamp-1">
+ {operation.itemReadableId}
+ </p>
+ </div>
+ </HStack>
+ <div className="flex flex-col shrink-0 items-end">
+ <Heading size="h2">
+ {formatDurationMilliseconds(
+ ((progress.setup ?? 0) +
+ (progress.labor ?? 0) +
+ (progress.machine ?? 0)) /
+ // Batch mode: the timer is shared, so the per-piece rate
+ // is elapsed over ALL members' completed parts — a
+ // quantity-weighted average, matching how completion
+ // slices the shared time (weight = operationQuantity).
+ Math.max(
+ batch
+ ? (batch.operations ?? []).reduce(
+ (sum, m) => sum + (m.quantityComplete ?? 0),
+ 0
)
- )}`
- : "–"}
- </Heading>
- <span className="text-muted-foreground text-sm">
- {operation.operationDueDate ? (
- <DateTime
- value={operation.operationDueDate}
- variant="date"
- />
- ) : null}
- </span>
- {projectedCompletionDate &&
- (isBehindTarget ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <Badge variant="red">
- {t`Proj. ${formatDate(
- projectedCompletionDate
- )}`}
- </Badge>
- </TooltipTrigger>
- <TooltipContent>
- {t`Behind target by ${daysBehindTarget} day(s)`}
- </TooltipContent>
- </Tooltip>
- ) : (
- <span className="text-sm text-muted-foreground">
- {t`Proj. ${formatDate(projectedCompletionDate)}`}
+ : operation.quantityComplete,
+ 1
+ ),
+ {
+ style: "short"
+ }
+ )}
+ </Heading>
+ <p className="text-muted-foreground line-clamp-1">
+ {operation.itemUnitOfMeasure}
+ </p>
+ </div>
+ </div>
+ <Separator />
+ <div className="flex items-start p-4 lg:p-6">
+ <div className="grid gap-4 grid-cols-1 md:grid-cols-2 xl:grid-cols-3 w-full min-w-0">
+ <Card>
+ <CardHeader className="flex flex-row items-center gap-2 justify-between">
+ <CardTitle>
+ <Trans>Completed</Trans>
+ </CardTitle>
+ <FaCheck className="h-3 w-3 text-emerald-500" />
+ </CardHeader>
+
+ <CardContent>
+ <Heading size="h1">
+ <Trans>
+ {operation.quantityComplete} of{" "}
+ {operation.targetQuantity}
+ </Trans>
+ </Heading>
+ </CardContent>
+ </Card>
+ <Card>
+ <CardHeader className="flex flex-row items-center gap-2 justify-between">
+ <CardTitle>
+ <Trans>Scrapped</Trans>
+ </CardTitle>
+ <FaTrash className="h-3 w-3 text-muted-foreground" />
+ </CardHeader>
+ <CardContent>
+ <Heading size="h1">
+ {operation.quantityScrapped}
+ </Heading>
+ </CardContent>
+ </Card>
+ <Card>
+ <CardHeader className="flex flex-row items-center gap-2 justify-between">
+ <CardTitle>
+ <Trans>Due Date</Trans>
+ </CardTitle>
+ <DeadlineIcon
+ deadlineType={operation.jobDeadlineType}
+ overdue={isOverdue}
+ />
+ </CardHeader>
+ <CardContent>
+ <VStack className="justify-start" spacing={0}>
+ <Heading
+ size="h3"
+ className={cn(
+ "w-full truncate",
+ isOverdue ? "text-red-500" : ""
+ )}
+ >
+ {["ASAP", "No Deadline"].includes(
+ operation.jobDeadlineType
+ )
+ ? operation.jobDeadlineType
+ : operation.operationDueDate
+ ? t`Due ${formatRelativeTime(
+ convertDateStringToIsoString(
+ operation.operationDueDate
+ )
+ )}`
+ : "–"}
+ </Heading>
+ <span className="text-muted-foreground text-sm">
+ {operation.operationDueDate ? (
+ <DateTime
+ value={operation.operationDueDate}
+ variant="date"
+ />
+ ) : null}
</span>
- ))}
- </VStack>
- </CardContent>
- </Card>
- </div>
- </div>
+ {projectedCompletionDate &&
+ (isBehindTarget ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="red">
+ {t`Proj. ${formatDate(
+ projectedCompletionDate
+ )}`}
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>
+ {t`Behind target by ${daysBehindTarget} day(s)`}
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ <span className="text-sm text-muted-foreground">
+ {t`Proj. ${formatDate(projectedCompletionDate)}`}
+ </span>
+ ))}
+ </VStack>
+ </CardContent>
+ </Card>
+ </div>
+ </div>
- <Suspense key={`non-conformance-actions-${operationId}`}>
- <Await resolve={nonConformanceActions}>
- {(resolvedNonConformanceActions) => {
- return resolvedNonConformanceActions.map((action) => {
- if (Object.keys(action.notes).length === 0) {
- return null;
- }
+ <Suspense key={`non-conformance-actions-${operationId}`}>
+ <Await resolve={nonConformanceActions}>
+ {(resolvedNonConformanceActions) => {
+ return resolvedNonConformanceActions.map((action) => {
+ if (Object.keys(action.notes).length === 0) {
+ return null;
+ }
- return (
- <>
- <Separator />
- <div className="flex flex-col items-start justify-between w-full">
- <div className="flex flex-col gap-4 p-4 lg:p-6 w-full">
- <div className="flex flex-col gap-0.5">
- <Heading size="h3">
- {action.actionTypeName}
- </Heading>
- <div>
- <Badge variant="outline">
- {action.nonConformanceId}
- </Badge>
+ return (
+ <>
+ <Separator />
+ <div className="flex flex-col items-start justify-between w-full">
+ <div className="flex flex-col gap-4 p-4 lg:p-6 w-full">
+ <div className="flex flex-col gap-0.5">
+ <Heading size="h3">
+ {action.actionTypeName}
+ </Heading>
+ <div>
+ <Badge variant="outline">
+ {action.nonConformanceId}
+ </Badge>
+ </div>
+ </div>
+ <div
+ className="prose dark:prose-invert prose-sm max-w-none"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(action.notes)
+ }}
+ />
</div>
</div>
- <div
- className="prose dark:prose-invert prose-sm max-w-none"
- dangerouslySetInnerHTML={{
- __html: generateHTML(action.notes)
- }}
- />
- </div>
- </div>
- </>
- );
- });
- }}
- </Await>
- </Suspense>
+ </>
+ );
+ });
+ }}
+ </Await>
+ </Suspense>
- <Suspense key={`attributes-${operationId}`}>
- <Await resolve={procedure}>
- {(resolvedProcedure) => {
- const { attributes, parameters } = resolvedProcedure;
+ <Suspense key={`attributes-${operationId}`}>
+ <Await resolve={procedure}>
+ {(resolvedProcedure) => {
+ const { attributes, parameters } = resolvedProcedure;
- return (
- <>
- {attributes.length > 0 && (
+ return (
<>
- <Separator />
- <div className="flex flex-col items-start justify-between w-full">
- <div className="flex flex-col gap-4 p-4 lg:p-6 w-full">
- <HStack className="justify-between w-full">
- <Heading size="h3">
- <Trans>Steps</Trans>
- </Heading>
- <div className="flex items-center gap-2">
- {attributes.length > 0 &&
- (() => {
- const maxRecords = parentIsSerial
- ? trackedEntities.length
- : operation.operationQuantity +
- operation.quantityScrapped;
-
- const isRecordSetStarted =
- recordSetIsStarted(
- attributes,
- activeStep
- );
-
- const canCreateNewRecord =
- !parentIsSerial && isRecordSetStarted;
-
- const canNavigateNext =
- isRecordSetStarted &&
- activeStep <
- operation.operationQuantity +
- operation.quantityScrapped -
- 1;
-
- const showNavigation =
- hasMultipleRecords ||
- attributes.some(
- (att) =>
- att.jobOperationStepRecord.length >
- 1
- );
-
- return (
- <div className="flex flex-col items-end justify-center gap-2">
- <div className="flex items-center gap-1">
- {showNavigation &&
- !parentIsSerial && (
- <>
- <IconButton
- aria-label="Previous record set"
- variant="secondary"
- icon={<LuChevronLeft />}
- onClick={() => {
- setActiveStep(
- activeStep - 1
- );
- }}
- isDisabled={
- activeStep === 0
- }
- />
- <span className="text-sm font-medium px-2 min-w-[60px] text-center">
+ {attributes.length > 0 && (
+ <>
+ <Separator />
+ <div className="flex flex-col items-start justify-between w-full">
+ <div className="flex flex-col gap-4 p-4 lg:p-6 w-full">
+ <HStack className="justify-between w-full">
+ <Heading size="h3">
+ <Trans>Steps</Trans>
+ </Heading>
+ <div className="flex items-center gap-2">
+ {attributes.length > 0 &&
+ (() => {
+ const maxRecords = parentIsSerial
+ ? trackedEntities.length
+ : operation.operationQuantity +
+ operation.quantityScrapped;
+
+ const isRecordSetStarted =
+ recordSetIsStarted(
+ attributes,
+ activeStep
+ );
+
+ const canCreateNewRecord =
+ !parentIsSerial &&
+ isRecordSetStarted;
+
+ const canNavigateNext =
+ isRecordSetStarted &&
+ activeStep <
+ operation.operationQuantity +
+ operation.quantityScrapped -
+ 1;
+
+ const showNavigation =
+ hasMultipleRecords ||
+ attributes.some(
+ (att) =>
+ att.jobOperationStepRecord
+ .length > 1
+ );
+
+ return (
+ <div className="flex flex-col items-end justify-center gap-2">
+ <div className="flex items-center gap-1">
+ {showNavigation &&
+ !parentIsSerial && (
+ <>
+ <IconButton
+ aria-label="Previous record set"
+ variant="secondary"
+ icon={<LuChevronLeft />}
+ onClick={() => {
+ setActiveStep(
+ activeStep - 1
+ );
+ }}
+ isDisabled={
+ activeStep === 0
+ }
+ />
+ <span className="text-sm font-medium px-2 min-w-[60px] text-center">
+ <Trans>
+ Record{" "}
+ {activeStep + 1}
+ </Trans>
+ </span>
+ <IconButton
+ aria-label="Next record set"
+ variant="secondary"
+ icon={
+ <LuChevronRight />
+ }
+ onClick={() => {
+ setActiveStep(
+ activeStep + 1
+ );
+ }}
+ isDisabled={
+ !canNavigateNext
+ }
+ />
+ </>
+ )}
+ {canCreateNewRecord &&
+ !showNavigation && (
+ <Button
+ aria-label="Add new record set"
+ variant="secondary"
+ leftIcon={
+ <LuCirclePlus />
+ }
+ onClick={() => {
+ const nextIndex =
+ activeStep + 1;
+ if (
+ nextIndex >=
+ maxRecords
+ ) {
+ toast.warning(
+ t`Maximum number of records reached`
+ );
+ return;
+ }
+ setHasMultipleRecords(
+ true
+ );
+ setActiveStep(
+ nextIndex
+ );
+ }}
+ isDisabled={
+ activeStep + 1 >=
+ maxRecords
+ }
+ >
+ <Trans>New Record</Trans>
+ </Button>
+ )}
+ {parentIsSerial && (
+ <Heading size="h2">
<Trans>
- Record {activeStep + 1}
+ {serialIndex + 1} of{" "}
+ {
+ operation.operationQuantity
+ }
</Trans>
- </span>
- <IconButton
- aria-label="Next record set"
- variant="secondary"
- icon={<LuChevronRight />}
- onClick={() => {
- setActiveStep(
- activeStep + 1
- );
- }}
- isDisabled={
- !canNavigateNext
- }
- />
- </>
- )}
- {canCreateNewRecord &&
- !showNavigation && (
- <Button
- aria-label="Add new record set"
- variant="secondary"
- leftIcon={<LuCirclePlus />}
- onClick={() => {
- const nextIndex =
- activeStep + 1;
- if (
- nextIndex >= maxRecords
- ) {
- toast.warning(
- t`Maximum number of records reached`
- );
- return;
- }
- setHasMultipleRecords(true);
- setActiveStep(nextIndex);
- }}
- isDisabled={
- activeStep + 1 >= maxRecords
- }
- >
- <Trans>New Record</Trans>
- </Button>
- )}
- {parentIsSerial && (
- <Heading size="h2">
+ </Heading>
+ )}
+ </div>
+
+ <BarProgress
+ label={t`Steps`}
+ gradient
+ invertGradient
+ progress={
+ (attributes.filter((a) =>
+ a.jobOperationStepRecord.some(
+ (r) =>
+ r.index === activeStep
+ )
+ ).length /
+ attributes.length) *
+ 100
+ }
+ />
+ <span className="text-xs text-muted-foreground">
<Trans>
- {serialIndex + 1} of{" "}
- {operation.operationQuantity}
+ {
+ attributes.filter((a) =>
+ a.jobOperationStepRecord.some(
+ (r) =>
+ r.index === activeStep
+ )
+ ).length
+ }{" "}
+ of {attributes.length}{" "}
+ complete
</Trans>
- </Heading>
- )}
- </div>
-
- <BarProgress
- label={t`Steps`}
- gradient
- invertGradient
- progress={
- (attributes.filter((a) =>
- a.jobOperationStepRecord.some(
- (r) => r.index === activeStep
- )
- ).length /
- attributes.length) *
- 100
- }
- />
- <span className="text-xs text-muted-foreground">
- <Trans>
- {
- attributes.filter((a) =>
- a.jobOperationStepRecord.some(
- (r) =>
- r.index === activeStep
- )
- ).length
- }{" "}
- of {attributes.length} complete
- </Trans>
- </span>
- </div>
- );
- })()}
+ </span>
+ </div>
+ );
+ })()}
+ </div>
+ </HStack>
+ <div className="border rounded-lg">
+ {attributes
+ .sort(
+ (a, b) =>
+ (a.sortOrder ?? 0) -
+ (b.sortOrder ?? 0)
+ )
+ .map((step, index) => (
+ <StepsListItem
+ key={`step-${step.id}`}
+ activeStep={activeStep}
+ step={step}
+ onRecord={onRecordStepRecord}
+ onDelete={onDeleteStepRecord}
+ operationId={operationId}
+ className={
+ index === attributes.length - 1
+ ? "border-none"
+ : ""
+ }
+ />
+ ))}
+ </div>
</div>
- </HStack>
- <div className="border rounded-lg">
- {attributes
- .sort(
- (a, b) =>
- (a.sortOrder ?? 0) - (b.sortOrder ?? 0)
- )
- .map((step, index) => (
- <StepsListItem
- key={`step-${step.id}`}
- activeStep={activeStep}
- step={step}
- onRecord={onRecordStepRecord}
- onDelete={onDeleteStepRecord}
- operationId={operationId}
- className={
- index === attributes.length - 1
- ? "border-none"
- : ""
- }
- />
- ))}
</div>
- </div>
- </div>
- </>
- )}
- {parameters.length > 0 && (
- <>
- <Separator />
- <div className="flex flex-col items-start justify-between w-full">
- <div className="flex flex-col gap-4 p-4 lg:p-6 w-full">
- <HStack className="justify-between w-full">
- <Heading size="h3">
- <Trans>Process Parameters</Trans>
- </Heading>
- </HStack>
- <div className="border rounded-lg">
- {parameters
- .sort((a, b) =>
- (a.key ?? "").localeCompare(b.key ?? "")
- )
- .map((p, index) => (
- <ParametersListItem
- key={`parameter-${p.id}`}
- parameter={p}
- operationId={operationId}
- className={
- index === parameters.length - 1
- ? "border-none"
- : ""
- }
- />
- ))}
+ </>
+ )}
+ {parameters.length > 0 && (
+ <>
+ <Separator />
+ <div className="flex flex-col items-start justify-between w-full">
+ <div className="flex flex-col gap-4 p-4 lg:p-6 w-full">
+ <HStack className="justify-between w-full">
+ <Heading size="h3">
+ <Trans>Process Parameters</Trans>
+ </Heading>
+ </HStack>
+ <div className="border rounded-lg">
+ {parameters
+ .sort((a, b) =>
+ (a.key ?? "").localeCompare(b.key ?? "")
+ )
+ .map((p, index) => (
+ <ParametersListItem
+ key={`parameter-${p.id}`}
+ parameter={p}
+ operationId={operationId}
+ className={
+ index === parameters.length - 1
+ ? "border-none"
+ : ""
+ }
+ />
+ ))}
+ </div>
+ </div>
</div>
- </div>
- </div>
+ </>
+ )}
</>
- )}
- </>
- );
- }}
- </Await>
- </Suspense>
-
- <Separator />
- <div className="flex flex-col items-start justify-between w-full">
- <div className="flex flex-col gap-4 p-4 lg:p-6 w-full">
- <HStack className="justify-between w-full">
- <Heading size="h3">
- <Trans>Materials</Trans>
- </Heading>
- <Button
- aria-label="Issue Material"
- leftIcon={<LuGitBranchPlus />}
- variant="secondary"
- size="lg"
- onClick={() => {
- flushSync(() => {
- setSelectedMaterial(null);
- });
- issueModal.onOpen();
- }}
- >
- <Trans>Issue Material</Trans>
- </Button>
- </HStack>
- <Suspense
- key={`materials-${operationId}`}
- fallback={<TableSkeleton />}
- >
- <Await resolve={materials}>
- {(resolvedMaterials) => {
- const baseMaterials = resolvedMaterials?.materials.filter(
- (m) => !m.isKitComponent
);
+ }}
+ </Await>
+ </Suspense>
- const kitMaterialsByParentId =
- resolvedMaterials?.materials
- .filter((m) => m.isKitComponent ?? false)
- .reduce(
- (acc, material) => {
- if (material.kitParentId) {
- if (!acc[material.kitParentId]) {
- acc[material.kitParentId] = [];
- }
- acc[material.kitParentId].push(material);
- }
- return acc;
- },
- {} as Record<string, JobMaterial[]>
- );
-
- return (
- <>
- <Table className="w-full text-base">
- <Thead>
- <Tr>
- <Th className="text-sm">
- <Trans>Part</Trans>
- </Th>
- <Th className="text-sm lg:table-cell hidden">
- <Trans>Source</Trans>
- </Th>
- <Th className="text-sm">
- <Trans>Estimated</Trans>
- </Th>
- <Th className="text-sm">
- <Trans>Actual</Trans>
- </Th>
- <Th className="text-right" />
- </Tr>
- </Thead>
- <Tbody>
- {baseMaterials.length === 0 ? (
- <Tr>
- <Td
- colSpan={24}
- className="py-8 text-muted-foreground text-center"
- >
- <Trans>No materials</Trans>
- </Td>
- </Tr>
- ) : (
- baseMaterials.map((material) => {
- const isRelatedToOperation =
- material.jobOperationId === operationId;
-
- const someRelatedMaterialIsIssued =
- baseMaterials.some(
- (m) =>
- m.itemReadableIdWithoutRevision ===
- material.itemReadableIdWithoutRevision &&
- ((m.quantityIssued ?? 0) > 0 ||
- (material.quantityIssued ?? 0) > 0)
- );
-
- const kittedChildren = material.id
- ? kitMaterialsByParentId[material.id]
- : [];
-
- return (
- <>
- <Tr
- key={`material-${material.id}`}
- className={cn(
- "[&>td]:py-3",
- !isRelatedToOperation &&
- "opacity-50 hover:opacity-100"
- )}
- >
- <Td className="max-w-[20vw]">
- <HStack
- spacing={2}
- className="justify-between min-w-0"
- >
- <VStack
- spacing={0}
- className="min-w-0"
- >
- <span className="font-semibold text-base truncate max-w-full">
- {getItemReadableId(
- items,
- material.itemId ?? ""
- )}
- </span>
- <span className="text-muted-foreground text-sm truncate max-w-full">
- {material.description}
- </span>
- <PickedBreakdown
- materialItemId={material.itemId}
- pickedByItem={
- (
- material as {
- pickedByItem?: {
- itemId: string;
- itemReadableId: string;
- quantityPicked: number;
- quantityToPick: number;
- }[];
- }
- ).pickedByItem
- }
- />
- </VStack>
- {material.requiresBatchTracking ? (
- <Badge variant="secondary">
- <TrackingTypeIcon
- type="Batch"
- className="shrink-0"
- />
- </Badge>
- ) : material.requiresSerialTracking ? (
- <Badge variant="secondary">
- <TrackingTypeIcon
- type="Serial"
- className="shrink-0"
- />
- </Badge>
- ) : null}
- {(
- material as {
- hasExpiredConsumed?: boolean;
- }
- ).hasExpiredConsumed && (
- <Badge
- variant="red"
- className="gap-1 shrink-0"
- title="A consumed batch or serial is now past its expiry date."
- >
- <LuTriangleAlert className="size-3" />
- <Trans>Consumed expired</Trans>
- </Badge>
- )}
- <PickedBadge
- quantityPicked={
- (
- material as {
- quantityPicked?:
- | number
- | null;
- }
- ).quantityPicked
- }
- quantityToPick={
- (
- material as {
- quantityToPick?:
- | number
- | null;
- }
- ).quantityToPick
- }
- />
- </HStack>
- </Td>
- <Td className="hidden lg:table-cell">
- <div className="flex flex-row items-center gap-1">
- <Badge variant="secondary">
- <MethodIcon
- type={material.methodType ?? ""}
- isKit={material.kit ?? false}
- className="mr-2"
- />
- {material.methodType ===
- "Make to Order" && material.kit
- ? t`Kit`
- : material.methodType}
- </Badge>
- <LuArrowLeft
- className={cn(
- material.methodType ===
- "Make to Order"
- ? "rotate-180"
- : ""
- )}
- />
- <Badge variant="secondary">
- <LuGitPullRequest className="size-3 mr-1" />
- {material.storageUnitName ??
- (material.methodType ===
- "Make to Order"
- ? t`WIP`
- : t`Default Storage Unit`)}
- </Badge>
- </div>
- </Td>
-
- <Td>
- {parentIsSerial &&
- (material.requiresBatchTracking ||
- material.requiresSerialTracking)
- ? `${
- material.quantity ??
- material.estimatedQuantity
- }/${
- material.estimatedQuantity ??
- material.quantity
- }`
- : (material.estimatedQuantity ??
- material.quantity)}
- </Td>
- <Td>
- {material.methodType ===
- "Make to Order" &&
- material.requiresBatchTracking ===
- false &&
- material.requiresSerialTracking ===
- false ? (
- <MethodIcon
- type="Make to Order"
- isKit={material.kit ?? false}
- />
- ) : parentIsSerial &&
- (material.requiresBatchTracking ||
- material.requiresSerialTracking) ? (
- `${material.quantityIssued}/${
- material.quantity ??
- material.estimatedQuantity
- }`
- ) : (
- material.quantityIssued
- )}
- </Td>
- <Td className="text-right">
- {material.methodType !==
- "Make to Order" &&
- material.requiresBatchTracking ===
- false &&
- material.requiresSerialTracking ===
- false && (
- <IconButton
- aria-label="Issue Material"
- variant="ghost"
- icon={<LuGitBranchPlus />}
- className="h-8 w-8"
- onClick={() => {
- flushSync(() => {
- setSelectedMaterial(
- material
- );
- });
- issueModal.onOpen();
- }}
- />
- )}
- {(material.requiresBatchTracking ||
- material.requiresSerialTracking) && (
- <Button
- className="flex-shrink-0"
- size="lg"
- variant={
- someRelatedMaterialIsIssued ||
- !isRelatedToOperation
- ? "secondary"
- : "primary"
- }
- leftIcon={<LuQrCode />}
- onClick={() => {
- flushSync(() => {
- setSelectedMaterial(material);
- });
- issueModal.onOpen();
- }}
- >
- <Trans>Issue</Trans>
- </Button>
- )}
+ <Separator />
+ <div className="flex flex-col items-start justify-between w-full">
+ <div className="flex flex-col gap-4 p-4 lg:p-6 w-full">
+ <HStack className="justify-between w-full">
+ <Heading size="h3">
+ <Trans>Materials</Trans>
+ </Heading>
+ <Button
+ aria-label="Issue Material"
+ leftIcon={<LuGitBranchPlus />}
+ variant="secondary"
+ size="lg"
+ onClick={() => {
+ flushSync(() => {
+ setSelectedMaterial(null);
+ });
+ issueModal.onOpen();
+ }}
+ >
+ <Trans>Issue Material</Trans>
+ </Button>
+ </HStack>
+ <Suspense
+ key={`materials-${operationId}`}
+ fallback={<TableSkeleton />}
+ >
+ <Await resolve={materials}>
+ {(resolvedMaterials) => {
+ const baseMaterials =
+ resolvedMaterials?.materials.filter(
+ (m) => !m.isKitComponent
+ );
+
+ const kitMaterialsByParentId =
+ resolvedMaterials?.materials
+ .filter((m) => m.isKitComponent ?? false)
+ .reduce(
+ (acc, material) => {
+ if (material.kitParentId) {
+ if (!acc[material.kitParentId]) {
+ acc[material.kitParentId] = [];
+ }
+ acc[material.kitParentId].push(material);
+ }
+ return acc;
+ },
+ {} as Record<string, JobMaterial[]>
+ );
+
+ return (
+ <>
+ <div className="w-full overflow-hidden rounded-lg border bg-card">
+ <Table className="w-full text-base">
+ <Thead className="bg-muted/40">
+ <Tr>
+ <Th className="text-sm">
+ <Trans>Part</Trans>
+ </Th>
+ <Th className="text-sm lg:table-cell hidden">
+ <Trans>Source</Trans>
+ </Th>
+ <Th className="text-sm">
+ <Trans>Estimated</Trans>
+ </Th>
+ <Th className="text-sm">
+ <Trans>Actual</Trans>
+ </Th>
+ <Th className="text-right" />
+ </Tr>
+ </Thead>
+ <Tbody className="[&>tr]:border-b [&>tr:last-child]:border-0">
+ {baseMaterials.length === 0 ? (
+ <Tr>
+ <Td
+ colSpan={24}
+ className="py-8 text-muted-foreground text-center"
+ >
+ <Trans>No materials</Trans>
</Td>
</Tr>
-
- {kittedChildren &&
- kittedChildren.map(
- (kittedChild, index) => (
+ ) : (
+ baseMaterials.map((material) => {
+ const isRelatedToOperation =
+ material.jobOperationId ===
+ operationId;
+
+ const someRelatedMaterialIsIssued =
+ baseMaterials.some(
+ (m) =>
+ m.itemReadableIdWithoutRevision ===
+ material.itemReadableIdWithoutRevision &&
+ ((m.quantityIssued ?? 0) > 0 ||
+ (material.quantityIssued ?? 0) >
+ 0)
+ );
+
+ const kittedChildren = material.id
+ ? kitMaterialsByParentId[material.id]
+ : [];
+
+ return (
+ <>
<Tr
- key={`kittedChild-${kittedChild.id}`}
+ key={`material-${material.id}`}
className={cn(
- index ===
- kittedChildren.length - 1
- ? "border-b"
- : index === 0
- ? "border-t"
- : "",
+ "[&>td]:py-3",
!isRelatedToOperation &&
"opacity-50 hover:opacity-100"
)}
>
- <Td className="pl-10 max-w-[20vw]">
+ <Td className="max-w-[20vw]">
<HStack
spacing={2}
className="justify-between min-w-0"
@@ -1615,22 +1728,22 @@ export const JobOperation = ({
spacing={0}
className="min-w-0"
>
- <span className="font-semibold truncate max-w-full">
+ <span className="font-semibold text-base truncate max-w-full">
{getItemReadableId(
items,
- kittedChild.itemId
+ material.itemId ?? ""
)}
</span>
- <span className="text-muted-foreground text-xs truncate max-w-full">
- {kittedChild.description}
+ <span className="text-muted-foreground text-sm truncate max-w-full">
+ {material.description}
</span>
<PickedBreakdown
materialItemId={
- kittedChild.itemId
+ material.itemId
}
pickedByItem={
(
- kittedChild as {
+ material as {
pickedByItem?: {
itemId: string;
itemReadableId: string;
@@ -1642,14 +1755,14 @@ export const JobOperation = ({
}
/>
</VStack>
- {kittedChild.requiresBatchTracking ? (
+ {material.requiresBatchTracking ? (
<Badge variant="secondary">
<TrackingTypeIcon
type="Batch"
className="shrink-0"
/>
</Badge>
- ) : kittedChild.requiresSerialTracking ? (
+ ) : material.requiresSerialTracking ? (
<Badge variant="secondary">
<TrackingTypeIcon
type="Serial"
@@ -1657,10 +1770,26 @@ export const JobOperation = ({
/>
</Badge>
) : null}
+ {(
+ material as {
+ hasExpiredConsumed?: boolean;
+ }
+ ).hasExpiredConsumed && (
+ <Badge
+ variant="red"
+ className="gap-1 shrink-0"
+ title="A consumed batch or serial is now past its expiry date."
+ >
+ <LuTriangleAlert className="size-3" />
+ <Trans>
+ Consumed expired
+ </Trans>
+ </Badge>
+ )}
<PickedBadge
quantityPicked={
(
- kittedChild as {
+ material as {
quantityPicked?:
| number
| null;
@@ -1669,7 +1798,7 @@ export const JobOperation = ({
}
quantityToPick={
(
- kittedChild as {
+ material as {
quantityToPick?:
| number
| null;
@@ -1679,72 +1808,116 @@ export const JobOperation = ({
/>
</HStack>
</Td>
- <Td className="lg:table-cell hidden">
- <Badge variant="secondary">
- <MethodIcon
- type={
- kittedChild.methodType ??
- ""
- }
- isKit={
- kittedChild.kit ?? false
- }
- className="mr-2"
+ <Td className="hidden lg:table-cell">
+ <div className="flex flex-row items-center gap-1">
+ <Badge variant="secondary">
+ <MethodIcon
+ type={
+ material.methodType ??
+ ""
+ }
+ isKit={
+ material.kit ?? false
+ }
+ className="mr-2"
+ />
+ {material.methodType ===
+ "Make to Order" &&
+ material.kit
+ ? t`Kit`
+ : material.methodType}
+ </Badge>
+ <LuArrowLeft
+ className={cn(
+ material.methodType ===
+ "Make to Order"
+ ? "rotate-180"
+ : ""
+ )}
/>
- {kittedChild.methodType ===
- "Make to Order" &&
- kittedChild.kit
- ? t`Kit`
- : kittedChild.methodType}
- </Badge>
+ <Badge variant="secondary">
+ <LuGitPullRequest className="size-3 mr-1" />
+ {material.storageUnitName ??
+ (material.methodType ===
+ "Make to Order"
+ ? t`WIP`
+ : t`Default Storage Unit`)}
+ </Badge>
+ </div>
</Td>
<Td>
{parentIsSerial &&
- (kittedChild.requiresBatchTracking ||
- kittedChild.requiresSerialTracking)
+ (material.requiresBatchTracking ||
+ material.requiresSerialTracking)
? `${
- kittedChild.quantity ??
- kittedChild.estimatedQuantity
+ material.quantity ??
+ material.estimatedQuantity
}/${
- kittedChild.estimatedQuantity ??
- kittedChild.quantity
+ material.estimatedQuantity ??
+ material.quantity
}`
- : (kittedChild.estimatedQuantity ??
- kittedChild.quantity)}
+ : (material.estimatedQuantity ??
+ material.quantity)}
+ {isBatched &&
+ material.itemId &&
+ batchMaterialTotals?.[
+ material.itemId
+ ] && (
+ <div className="text-xs text-muted-foreground whitespace-nowrap">
+ <Trans>Batch</Trans>:{" "}
+ {
+ batchMaterialTotals[
+ material.itemId
+ ].required
+ }
+ </div>
+ )}
</Td>
<Td>
- {kittedChild.methodType ===
+ {material.methodType ===
"Make to Order" &&
- kittedChild.requiresBatchTracking ===
+ material.requiresBatchTracking ===
false &&
- kittedChild.requiresSerialTracking ===
+ material.requiresSerialTracking ===
false ? (
<MethodIcon
type="Make to Order"
isKit={
- kittedChild.kit ?? false
+ material.kit ?? false
}
/>
) : parentIsSerial &&
- (kittedChild.requiresBatchTracking ||
- kittedChild.requiresSerialTracking) ? (
- `${
- kittedChild.quantityIssued
- }/${
- kittedChild.quantity ??
- kittedChild.estimatedQuantity
+ (material.requiresBatchTracking ||
+ material.requiresSerialTracking) ? (
+ `${material.quantityIssued}/${
+ material.quantity ??
+ material.estimatedQuantity
}`
) : (
- kittedChild.quantityIssued
+ material.quantityIssued
)}
+ {isBatched &&
+ material.itemId &&
+ batchMaterialTotals?.[
+ material.itemId
+ ] && (
+ <div className="text-xs text-muted-foreground whitespace-nowrap">
+ <Trans>Batch</Trans>:{" "}
+ {
+ batchMaterialTotals[
+ material.itemId
+ ].issued
+ }
+ </div>
+ )}
</Td>
<Td className="text-right">
- {kittedChild.methodType !==
+ {material.methodType !==
"Make to Order" &&
- kittedChild.requiresBatchTracking ===
+ material.requiresBatchTracking ===
false &&
- kittedChild.requiresSerialTracking ===
+ material.requiresSerialTracking ===
false && (
<IconButton
aria-label="Issue Material"
@@ -1754,398 +1927,602 @@ export const JobOperation = ({
onClick={() => {
flushSync(() => {
setSelectedMaterial(
- kittedChild
+ material
);
});
issueModal.onOpen();
}}
/>
)}
- {(kittedChild.requiresBatchTracking ||
- kittedChild.requiresSerialTracking) && (
- <IconButton
- aria-label="Issue Material"
- variant="secondary"
- icon={<LuQrCode />}
- className="h-8 w-8"
+ {(material.requiresBatchTracking ||
+ material.requiresSerialTracking) && (
+ <Button
+ className="flex-shrink-0"
+ size="lg"
+ variant={
+ someRelatedMaterialIsIssued ||
+ !isRelatedToOperation
+ ? "secondary"
+ : "primary"
+ }
+ leftIcon={<LuQrCode />}
onClick={() => {
flushSync(() => {
setSelectedMaterial(
- kittedChild
+ material
);
});
issueModal.onOpen();
}}
- />
+ >
+ <Trans>Issue</Trans>
+ </Button>
)}
</Td>
</Tr>
- )
- )}
- </>
- );
- })
- )}
- </Tbody>
- </Table>
- {issueModal.isOpen && (
- <IssueMaterialModal
- operationId={operation.id}
- // The process view issues the whole quantity at
- // once, so picked lots may pre-fill when the
- // parent is a single entity. The modal enforces
- // the full rule: a picking list exists AND (the
- // parent is not serialized OR the operation
- // makes exactly one unit).
- allowPrefill
- parentUnitCount={
- operation.operationQuantity ?? undefined
- }
- expiredEntityPolicy={expiredEntityPolicy}
- autoSelectMaterialWithoutPickingList={
- autoSelectMaterialWithoutPickingList
- }
- locationId={locationId}
- workCenterId={operation.workCenterId ?? undefined}
- material={selectedMaterial ?? undefined}
- parentId={trackedEntityId ?? ""}
- parentIdIsSerialized={
- method?.requiresSerialTracking ?? false
- }
- trackedInputs={
- resolvedMaterials?.trackedInputs ?? []
- }
- onClose={() => {
- setSelectedMaterial(null);
- issueModal.onClose();
- }}
- />
- )}
- </>
- );
- }}
- </Await>
- </Suspense>
- </div>
- </div>
- <Separator />
- <div className="flex flex-col items-start justify-between w-full">
- <div className="flex flex-col gap-4 p-4 lg:p-6 w-full">
- <Heading size="h3">
- <Trans>Files</Trans>
- </Heading>
- <p className="text-muted-foreground text-sm -mt-2">
- <Trans>
- Files related to the job and the opportunity line.
- </Trans>
- </p>
- <Suspense
- key={`files-${operationId}`}
- fallback={<TableSkeleton />}
- >
- <Await resolve={files}>
- {(resolvedFiles) => (
- <Table className="w-full text-base">
- <Thead>
- <Tr>
- <Th className="text-sm">
- <Trans>Name</Trans>
- </Th>
- <Th className="text-sm">
- <Trans>Size</Trans>
- </Th>
- <Th></Th>
- </Tr>
- </Thead>
- <Tbody>
- {resolvedFiles.length === 0 && !modelUpload ? (
- <Tr>
- <Td
- colSpan={24}
- className="py-8 text-muted-foreground text-center"
+ {kittedChildren &&
+ kittedChildren.map(
+ (kittedChild, index) => (
+ <Tr
+ key={`kittedChild-${kittedChild.id}`}
+ className={cn(
+ index ===
+ kittedChildren.length -
+ 1
+ ? "border-b"
+ : index === 0
+ ? "border-t"
+ : "",
+ !isRelatedToOperation &&
+ "opacity-50 hover:opacity-100"
+ )}
+ >
+ <Td className="pl-10 max-w-[20vw]">
+ <HStack
+ spacing={2}
+ className="justify-between min-w-0"
+ >
+ <VStack
+ spacing={0}
+ className="min-w-0"
+ >
+ <span className="font-semibold truncate max-w-full">
+ {getItemReadableId(
+ items,
+ kittedChild.itemId
+ )}
+ </span>
+ <span className="text-muted-foreground text-xs truncate max-w-full">
+ {
+ kittedChild.description
+ }
+ </span>
+ <PickedBreakdown
+ materialItemId={
+ kittedChild.itemId
+ }
+ pickedByItem={
+ (
+ kittedChild as {
+ pickedByItem?: {
+ itemId: string;
+ itemReadableId: string;
+ quantityPicked: number;
+ quantityToPick: number;
+ }[];
+ }
+ ).pickedByItem
+ }
+ />
+ </VStack>
+ {kittedChild.requiresBatchTracking ? (
+ <Badge variant="secondary">
+ <TrackingTypeIcon
+ type="Batch"
+ className="shrink-0"
+ />
+ </Badge>
+ ) : kittedChild.requiresSerialTracking ? (
+ <Badge variant="secondary">
+ <TrackingTypeIcon
+ type="Serial"
+ className="shrink-0"
+ />
+ </Badge>
+ ) : null}
+ <PickedBadge
+ quantityPicked={
+ (
+ kittedChild as {
+ quantityPicked?:
+ | number
+ | null;
+ }
+ ).quantityPicked
+ }
+ quantityToPick={
+ (
+ kittedChild as {
+ quantityToPick?:
+ | number
+ | null;
+ }
+ ).quantityToPick
+ }
+ />
+ </HStack>
+ </Td>
+ <Td className="lg:table-cell hidden">
+ <Badge variant="secondary">
+ <MethodIcon
+ type={
+ kittedChild.methodType ??
+ ""
+ }
+ isKit={
+ kittedChild.kit ??
+ false
+ }
+ className="mr-2"
+ />
+ {kittedChild.methodType ===
+ "Make to Order" &&
+ kittedChild.kit
+ ? t`Kit`
+ : kittedChild.methodType}
+ </Badge>
+ </Td>
+
+ <Td>
+ {parentIsSerial &&
+ (kittedChild.requiresBatchTracking ||
+ kittedChild.requiresSerialTracking)
+ ? `${
+ kittedChild.quantity ??
+ kittedChild.estimatedQuantity
+ }/${
+ kittedChild.estimatedQuantity ??
+ kittedChild.quantity
+ }`
+ : (kittedChild.estimatedQuantity ??
+ kittedChild.quantity)}
+ </Td>
+ <Td>
+ {kittedChild.methodType ===
+ "Make to Order" &&
+ kittedChild.requiresBatchTracking ===
+ false &&
+ kittedChild.requiresSerialTracking ===
+ false ? (
+ <MethodIcon
+ type="Make to Order"
+ isKit={
+ kittedChild.kit ??
+ false
+ }
+ />
+ ) : parentIsSerial &&
+ (kittedChild.requiresBatchTracking ||
+ kittedChild.requiresSerialTracking) ? (
+ `${
+ kittedChild.quantityIssued
+ }/${
+ kittedChild.quantity ??
+ kittedChild.estimatedQuantity
+ }`
+ ) : (
+ kittedChild.quantityIssued
+ )}
+ </Td>
+ <Td className="text-right">
+ {kittedChild.methodType !==
+ "Make to Order" &&
+ kittedChild.requiresBatchTracking ===
+ false &&
+ kittedChild.requiresSerialTracking ===
+ false && (
+ <IconButton
+ aria-label="Issue Material"
+ variant="ghost"
+ icon={
+ <LuGitBranchPlus />
+ }
+ className="h-8 w-8"
+ onClick={() => {
+ flushSync(() => {
+ setSelectedMaterial(
+ kittedChild
+ );
+ });
+ issueModal.onOpen();
+ }}
+ />
+ )}
+ {(kittedChild.requiresBatchTracking ||
+ kittedChild.requiresSerialTracking) && (
+ <IconButton
+ aria-label="Issue Material"
+ variant="secondary"
+ icon={<LuQrCode />}
+ className="h-8 w-8"
+ onClick={() => {
+ flushSync(() => {
+ setSelectedMaterial(
+ kittedChild
+ );
+ });
+ issueModal.onOpen();
+ }}
+ />
+ )}
+ </Td>
+ </Tr>
+ )
+ )}
+ </>
+ );
+ })
+ )}
+ </Tbody>
+ </Table>
+ </div>
+ {renderIssueModal(resolvedMaterials)}
+ </>
+ );
+ }}
+ </Await>
+ </Suspense>
+ </div>
+ </div>
+
+ <Separator />
+ <div className="flex flex-col items-start justify-between w-full">
+ <div className="flex flex-col gap-4 p-4 lg:p-6 w-full">
+ <Heading size="h3">
+ <Trans>Files</Trans>
+ </Heading>
+ <p className="text-muted-foreground text-sm -mt-2">
+ <Trans>
+ Files related to the job and the opportunity line.
+ </Trans>
+ </p>
+ <Suspense
+ key={`files-${operationId}`}
+ fallback={<TableSkeleton />}
+ >
+ <Await resolve={files}>
+ {(resolvedFiles) => (
+ <div className="w-full overflow-hidden rounded-lg border bg-card">
+ <Table className="w-full text-base">
+ <Thead className="bg-muted/40">
+ <Tr>
+ <Th className="text-sm">
+ <Trans>Name</Trans>
+ </Th>
+ <Th className="text-sm">
+ <Trans>Size</Trans>
+ </Th>
+ <Th></Th>
+ </Tr>
+ </Thead>
+ <Tbody className="[&>tr]:border-b [&>tr:last-child]:border-0">
+ {resolvedFiles.length === 0 && !modelUpload ? (
+ <Tr>
+ <Td
+ colSpan={24}
+ className="py-8 text-muted-foreground text-center"
+ >
+ <Trans>No files</Trans>
+ </Td>
+ </Tr>
+ ) : (
+ <>
+ {modelUpload?.modelName && (
+ <Tr className="[&>td]:py-3">
+ <Td>
+ <HStack>
+ <LuAxis3D className="text-emerald-500 w-6 h-6" />
+ <span>{modelUpload.modelName}</span>
+ </HStack>
+ </Td>
+ <Td className="text-sm font-mono">
+ {modelUpload.modelSize
+ ? convertKbToString(
+ Math.floor(
+ (modelUpload.modelSize ?? 0) /
+ 1024
+ )
+ )
+ : "--"}
+ </Td>
+ <Td>
+ <div className="flex justify-end w-full">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More"
+ icon={<LuEllipsisVertical />}
+ variant="secondary"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onClick={() =>
+ downloadModel(modelUpload)
+ }
+ >
+ <DropdownMenuIcon
+ icon={<LuDownload />}
+ />
+ <Trans>Download</Trans>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </Td>
+ </Tr>
+ )}
+ {resolvedFiles.map((file) => {
+ const type = getFileType(file.name);
+ return (
+ <Tr
+ key={`file-${file.id}`}
+ className="[&>td]:py-3"
+ >
+ <Td>
+ <HStack>
+ <FileIcon type={type} />
+ <span
+ className="font-medium"
+ onClick={() => {
+ if (
+ ["PDF", "Image"].includes(
+ type
+ )
+ ) {
+ window.open(
+ path.to.file.previewFile(
+ `${"private"}/${getFilePath(
+ file
+ )}`
+ ),
+ "_blank"
+ );
+ }
+ }}
+ >
+ {["PDF", "Image"].includes(
+ type
+ ) ? (
+ <FilePreview
+ bucket="private"
+ pathToFile={getFilePath(
+ file
+ )}
+ // @ts-ignore
+ type={getFileType(
+ file.name
+ )}
+ >
+ {file.name}
+ </FilePreview>
+ ) : (
+ file.name
+ )}
+ </span>
+ </HStack>
+ </Td>
+ <Td className="text-sm font-mono">
+ {convertKbToString(
+ Math.floor(
+ (file.metadata?.size ?? 0) /
+ 1024
+ )
+ )}
+ </Td>
+ <Td>
+ <div className="flex justify-end w-full">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More"
+ icon={
+ <LuEllipsisVertical />
+ }
+ variant="secondary"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onClick={() =>
+ downloadFile(file)
+ }
+ >
+ <DropdownMenuIcon
+ icon={<LuDownload />}
+ />
+ Download
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </Td>
+ </Tr>
+ );
+ })}
+ </>
+ )}
+ </Tbody>
+ </Table>
+ </div>
+ )}
+ </Await>
+ </Suspense>
+ </div>
+ </div>
+
+ {parentIsSerial && (
+ <>
+ <Separator />
+ <div className="flex flex-col items-start justify-between w-full">
+ <div className="flex flex-col gap-4 p-4 lg:p-6 w-full">
+ <HStack className="justify-between w-full">
+ <Heading size="h3">
+ <Trans>Serial Numbers</Trans>
+ </Heading>
+ {trackedEntities?.length > 0 && (
+ <HStack>
+ <PrintButton
+ sourceDocument="Operation"
+ sourceDocumentId={operationId!}
+ locationId={locationId}
+ context="workCenter"
+ workCenterId={
+ operation.workCenterId ?? undefined
+ }
+ size="lg"
+ fileRoutes={{
+ pdf: path.to.file.operationLabelsPdf,
+ zpl: path.to.file.operationLabelsZpl
+ }}
+ />
+ <Button
+ variant="secondary"
+ size="lg"
+ leftIcon={<LuBarcode />}
+ onClick={serialModal.onOpen}
>
- <Trans>No files</Trans>
- </Td>
- </Tr>
- ) : (
- <>
- {modelUpload?.modelName && (
- <Tr className="[&>td]:py-3">
- <Td>
- <HStack>
- <LuAxis3D className="text-emerald-500 w-6 h-6" />
- <span>{modelUpload.modelName}</span>
- </HStack>
- </Td>
- <Td className="text-sm font-mono">
- {modelUpload.modelSize
- ? convertKbToString(
- Math.floor(
- (modelUpload.modelSize ?? 0) / 1024
- )
- )
- : "--"}
- </Td>
- <Td>
- <div className="flex justify-end w-full">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- aria-label="More"
- icon={<LuEllipsisVertical />}
- variant="secondary"
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem
- onClick={() =>
- downloadModel(modelUpload)
- }
- >
- <DropdownMenuIcon
- icon={<LuDownload />}
- />
- <Trans>Download</Trans>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
+ <Trans>Scan</Trans>
+ </Button>
+ </HStack>
+ )}
+ </HStack>
+
+ <div className="w-full overflow-hidden rounded-lg border bg-card">
+ <Table className="w-full text-base">
+ <Thead className="bg-muted/40">
+ <Tr>
+ <Th className="text-sm">
+ <Trans>Serial</Trans>
+ </Th>
+ <Th className="text-right" />
+ </Tr>
+ </Thead>
+ <Tbody className="[&>tr]:border-b [&>tr:last-child]:border-0">
+ {trackedEntities?.length === 0 ? (
+ <Tr>
+ <Td
+ colSpan={24}
+ className="py-8 text-muted-foreground text-center"
+ >
+ <LuTriangleAlert className="text-red-500 size-4" />
+ <Trans>No serial numbers</Trans>
</Td>
</Tr>
- )}
- {resolvedFiles.map((file) => {
- const type = getFileType(file.name);
- return (
+ ) : (
+ trackedEntities?.map((entity) => (
<Tr
- key={`file-${file.id}`}
- className="[&>td]:py-3"
+ key={`serial-${entity.id}`}
+ className={cn(
+ "[&>td]:py-3",
+ entity.status === "Scrapped" &&
+ "opacity-60"
+ )}
>
<Td>
- <HStack>
- <FileIcon type={type} />
- <span
- className="font-medium"
+ <div className="flex gap-2 items-center">
+ <div className="flex flex-col min-w-0">
+ {entity.readableId ? (
+ <>
+ <span className="font-medium truncate">
+ {entity.readableId}
+ </span>
+ <span className="text-xs text-muted-foreground font-mono truncate">
+ {entity.id}
+ </span>
+ </>
+ ) : (
+ <span className="font-mono truncate">
+ {entity.id}
+ </span>
+ )}
+ </div>
+ {entity.id === trackedEntityId && (
+ <LuCheck className="text-emerald-500 size-4 shrink-0" />
+ )}
+ <Copy
+ text={entity.readableId || entity.id}
+ />
+ {entity.status === "Scrapped" && (
+ <Badge variant="red">
+ <Trans>Scrapped</Trans>
+ </Badge>
+ )}
+ </div>
+ </Td>
+
+ <Td className="text-right">
+ <div className="flex justify-end gap-2">
+ <PrintButton
+ sourceDocument="Entity"
+ sourceDocumentId={entity.id}
+ locationId={locationId}
+ context="workCenter"
+ workCenterId={
+ operation.workCenterId ?? undefined
+ }
+ size="lg"
+ fileRoutes={{
+ pdf: path.to.file
+ .trackedEntityLabelPdf,
+ zpl: path.to.file
+ .trackedEntityLabelZpl
+ }}
+ />
+ <Button
+ variant="secondary"
+ size="lg"
+ isDisabled={
+ entity.id === trackedEntityId ||
+ entity.status === "Scrapped"
+ }
onClick={() => {
- if (
- ["PDF", "Image"].includes(type)
- ) {
- window.open(
- path.to.file.previewFile(
- `${"private"}/${getFilePath(
- file
- )}`
- ),
- "_blank"
+ const entityIndex =
+ trackedEntities.findIndex(
+ (e) => e.id === entity.id
);
+ if (entityIndex !== -1) {
+ setActiveStep(entityIndex);
}
+ setParams({
+ trackedEntityId: entity.id
+ });
}}
- >
- {["PDF", "Image"].includes(type) ? (
- <FilePreview
- bucket="private"
- pathToFile={getFilePath(file)}
- // @ts-ignore
- type={getFileType(file.name)}
- >
- {file.name}
- </FilePreview>
- ) : (
- file.name
- )}
- </span>
- </HStack>
- </Td>
- <Td className="text-sm font-mono">
- {convertKbToString(
- Math.floor(
- (file.metadata?.size ?? 0) / 1024
- )
- )}
- </Td>
- <Td>
- <div className="flex justify-end w-full">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- aria-label="More"
- icon={<LuEllipsisVertical />}
- variant="secondary"
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem
- onClick={() => downloadFile(file)}
- >
- <DropdownMenuIcon
- icon={<LuDownload />}
- />
- Download
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ >
+ <Trans>Select</Trans>
+ </Button>
</div>
</Td>
</Tr>
- );
- })}
- </>
- )}
- </Tbody>
- </Table>
- )}
- </Await>
- </Suspense>
- </div>
- </div>
-
- {parentIsSerial && (
- <>
- <Separator />
- <div className="flex flex-col items-start justify-between w-full">
- <div className="flex flex-col gap-4 p-4 lg:p-6 w-full">
- <HStack className="justify-between w-full">
- <Heading size="h3">
- <Trans>Serial Numbers</Trans>
- </Heading>
- {trackedEntities?.length > 0 && (
- <HStack>
- <PrintButton
- sourceDocument="Operation"
- sourceDocumentId={operationId!}
- locationId={locationId}
- context="workCenter"
- workCenterId={operation.workCenterId ?? undefined}
- size="lg"
- fileRoutes={{
- pdf: path.to.file.operationLabelsPdf,
- zpl: path.to.file.operationLabelsZpl
- }}
- />
- <Button
- variant="secondary"
- size="lg"
- leftIcon={<LuBarcode />}
- onClick={serialModal.onOpen}
- >
- <Trans>Scan</Trans>
- </Button>
- </HStack>
- )}
- </HStack>
-
- <Table className="w-full text-base">
- <Thead>
- <Tr>
- <Th className="text-sm">
- <Trans>Serial</Trans>
- </Th>
- <Th className="text-right" />
- </Tr>
- </Thead>
- <Tbody>
- {trackedEntities?.length === 0 ? (
- <Tr>
- <Td
- colSpan={24}
- className="py-8 text-muted-foreground text-center"
- >
- <LuTriangleAlert className="text-red-500 size-4" />
- <Trans>No serial numbers</Trans>
- </Td>
- </Tr>
- ) : (
- trackedEntities?.map((entity) => (
- <Tr
- key={`serial-${entity.id}`}
- className={cn(
- "[&>td]:py-3",
- entity.status === "Scrapped" && "opacity-60"
+ ))
)}
- >
- <Td>
- <div className="flex gap-2 items-center">
- <div className="flex flex-col min-w-0">
- {entity.readableId ? (
- <>
- <span className="font-medium truncate">
- {entity.readableId}
- </span>
- <span className="text-xs text-muted-foreground font-mono truncate">
- {entity.id}
- </span>
- </>
- ) : (
- <span className="font-mono truncate">
- {entity.id}
- </span>
- )}
- </div>
- {entity.id === trackedEntityId && (
- <LuCheck className="text-emerald-500 size-4 shrink-0" />
- )}
- <Copy text={entity.readableId || entity.id} />
- {entity.status === "Scrapped" && (
- <Badge variant="red">
- <Trans>Scrapped</Trans>
- </Badge>
- )}
- </div>
- </Td>
-
- <Td className="text-right">
- <div className="flex justify-end gap-2">
- <PrintButton
- sourceDocument="Entity"
- sourceDocumentId={entity.id}
- locationId={locationId}
- context="workCenter"
- workCenterId={
- operation.workCenterId ?? undefined
- }
- size="lg"
- fileRoutes={{
- pdf: path.to.file.trackedEntityLabelPdf,
- zpl: path.to.file.trackedEntityLabelZpl
- }}
- />
- <Button
- variant="secondary"
- size="lg"
- isDisabled={
- entity.id === trackedEntityId ||
- entity.status === "Scrapped"
- }
- onClick={() => {
- const entityIndex =
- trackedEntities.findIndex(
- (e) => e.id === entity.id
- );
- if (entityIndex !== -1) {
- setActiveStep(entityIndex);
- }
- setParams({
- trackedEntityId: entity.id
- });
- }}
- >
- <Trans>Select</Trans>
- </Button>
- </div>
- </Td>
- </Tr>
- ))
- )}
- </Tbody>
- </Table>
- </div>
- </div>
+ </Tbody>
+ </Table>
+ </div>
+ </div>
+ </div>
+ </>
+ )}
</>
)}
</div>
</TabsContent>
- <TabsContent value="model">
- <div className="relative w-full min-w-0 lg:pr-[var(--controls-gutter)] h-[calc(100dvh-var(--header-height)*2-var(--controls-height)-2rem)] p-0">
+ <TabsContent
+ value="model"
+ className="[grid-area:main] mt-0 h-full min-h-0"
+ >
+ <div className="relative h-full w-full min-w-0 p-0">
{modelPath ? (
<ModelPreview
key={modelPath}
@@ -2205,370 +2582,328 @@ export const JobOperation = ({
)}
</div>
</TabsContent>
- <TabsContent value="procedure" className="flex flex-grow">
- <div className="flex h-[calc(100dvh-var(--header-height)*2-var(--controls-height)-2rem)] w-full">
- <Suspense key={`procedure-${operationId}`}>
- <Await resolve={procedure}>
- {(resolvedProcedure) => {
- const { attributes, parameters } = resolvedProcedure;
- if (attributes.length === 0 && parameters.length === 0)
- return null;
+ <TabsContent
+ value="procedure"
+ className="[grid-area:main] mt-0 flex h-full min-h-0"
+ >
+ {scope === "batch" && batch ? (
+ <div className="h-full w-full overflow-y-auto scroll-fade scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
+ <BatchOverview
+ view="instructions"
+ batch={batch}
+ totals={batchMaterialTotals ?? {}}
+ currentMaterials={[]}
+ onIssue={() => {}}
+ workInstructions={batchWorkInstructions}
+ onDownloadFile={downloadFile}
+ />
+ </div>
+ ) : (
+ <div className="flex h-full w-full">
+ <Suspense key={`procedure-${operationId}`}>
+ <Await resolve={procedure}>
+ {(resolvedProcedure) => {
+ const { attributes, parameters } = resolvedProcedure;
+ if (attributes.length === 0 && parameters.length === 0)
+ return null;
- return (
- <ScrollArea className="hidden lg:block w-1/3 border-r shrink-0 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
- <Tabs
- defaultValue="attributes"
- className="w-full flex-1 h-full flex flex-col"
- >
- <div className="w-full py-2 px-4 sticky top-0 z-10">
- <TabsList className="w-full grid grid-cols-2">
- <TabsTrigger value="attributes">
- <Trans>Steps</Trans>
- </TabsTrigger>
- <TabsTrigger value="parameters">
- <Trans>Parameters</Trans>
- </TabsTrigger>
- </TabsList>
- </div>
- <TabsContent
- value="attributes"
- className="w-full flex-1 flex flex-col overflow-y-auto data-[state=inactive]:hidden"
+ return (
+ <ScrollArea className="hidden lg:block w-1/3 border-r shrink-0 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
+ <Tabs
+ defaultValue="attributes"
+ className="w-full flex-1 h-full flex flex-col"
>
- <VStack
- className="w-full flex-1 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
- spacing={0}
+ <div className="w-full py-2 px-4 sticky top-0 z-10">
+ <TabsList className="w-full grid grid-cols-2">
+ <TabsTrigger value="attributes">
+ <Trans>Steps</Trans>
+ </TabsTrigger>
+ <TabsTrigger value="parameters">
+ <Trans>Parameters</Trans>
+ </TabsTrigger>
+ </TabsList>
+ </div>
+ <TabsContent
+ value="attributes"
+ className="w-full flex-1 flex flex-col overflow-y-auto data-[state=inactive]:hidden"
>
- {attributes.length > 0 &&
- (() => {
- const maxRecords = parentIsSerial
- ? trackedEntities.length
- : operation.operationQuantity +
- operation.quantityScrapped;
-
- const isRecordSetStarted = recordSetIsStarted(
- attributes,
- activeStep
- );
-
- const canCreateNewRecord =
- !parentIsSerial && isRecordSetStarted;
-
- const canNavigateNext =
- isRecordSetStarted &&
- activeStep <
- operation.operationQuantity +
- operation.quantityScrapped -
- 1;
-
- const showNavigation =
- hasMultipleRecords ||
- attributes.some(
- (att) =>
- att.jobOperationStepRecord.length > 1
+ <VStack
+ className="w-full flex-1 overflow-y-auto scroll-fade scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
+ spacing={0}
+ >
+ {attributes.length > 0 &&
+ (() => {
+ const maxRecords = parentIsSerial
+ ? trackedEntities.length
+ : operation.operationQuantity +
+ operation.quantityScrapped;
+
+ const isRecordSetStarted = recordSetIsStarted(
+ attributes,
+ activeStep
);
- return (
- <div className="flex items-end justify-between gap-1 w-full px-4 pb-2 border-b">
- <div className="flex items-center gap-1">
- {showNavigation && !parentIsSerial && (
- <>
- <IconButton
- aria-label="Previous record set"
- variant="secondary"
- icon={<LuChevronLeft />}
- onClick={() => {
- setActiveStep(activeStep - 1);
- }}
- isDisabled={activeStep === 0}
- />
- <span className="text-sm font-medium px-2 min-w-[60px] text-center">
+ const canCreateNewRecord =
+ !parentIsSerial && isRecordSetStarted;
+
+ const canNavigateNext =
+ isRecordSetStarted &&
+ activeStep <
+ operation.operationQuantity +
+ operation.quantityScrapped -
+ 1;
+
+ const showNavigation =
+ hasMultipleRecords ||
+ attributes.some(
+ (att) =>
+ att.jobOperationStepRecord.length > 1
+ );
+
+ return (
+ <div className="flex items-end justify-between gap-1 w-full px-4 pb-2 border-b">
+ <div className="flex items-center gap-1">
+ {showNavigation && !parentIsSerial && (
+ <>
+ <IconButton
+ aria-label="Previous record set"
+ variant="secondary"
+ icon={<LuChevronLeft />}
+ onClick={() => {
+ setActiveStep(activeStep - 1);
+ }}
+ isDisabled={activeStep === 0}
+ />
+ <span className="text-sm font-medium px-2 min-w-[60px] text-center">
+ <Trans>
+ Record {activeStep + 1}
+ </Trans>
+ </span>
+ <IconButton
+ aria-label="Next record set"
+ variant="secondary"
+ icon={<LuChevronRight />}
+ onClick={() => {
+ setActiveStep(activeStep + 1);
+ }}
+ isDisabled={!canNavigateNext}
+ />
+ </>
+ )}
+ {canCreateNewRecord &&
+ !showNavigation && (
+ <Button
+ aria-label="Add new record set"
+ variant="secondary"
+ leftIcon={<LuCirclePlus />}
+ onClick={() => {
+ const nextIndex =
+ activeStep + 1;
+ if (nextIndex >= maxRecords) {
+ toast.warning(
+ t`Maximum number of records reached`
+ );
+ return;
+ }
+ setHasMultipleRecords(true);
+ setActiveStep(nextIndex);
+ }}
+ isDisabled={
+ activeStep + 1 >= maxRecords
+ }
+ >
+ <Trans>New Record</Trans>
+ </Button>
+ )}
+ {parentIsSerial && (
+ <Heading size="h2">
<Trans>
- Record {activeStep + 1}
+ {serialIndex + 1} of{" "}
+ {operation.operationQuantity}
</Trans>
- </span>
- <IconButton
- aria-label="Next record set"
- variant="secondary"
- icon={<LuChevronRight />}
- onClick={() => {
- setActiveStep(activeStep + 1);
- }}
- isDisabled={!canNavigateNext}
- />
- </>
- )}
- {canCreateNewRecord &&
- !showNavigation && (
- <Button
- aria-label="Add new record set"
- variant="secondary"
- leftIcon={<LuCirclePlus />}
- onClick={() => {
- const nextIndex = activeStep + 1;
- if (nextIndex >= maxRecords) {
- toast.warning(
- t`Maximum number of records reached`
- );
- return;
- }
- setHasMultipleRecords(true);
- setActiveStep(nextIndex);
- }}
- isDisabled={
- activeStep + 1 >= maxRecords
- }
- >
- <Trans>New Record</Trans>
- </Button>
+ </Heading>
)}
- {parentIsSerial && (
- <Heading size="h2">
- <Trans>
- {serialIndex + 1} of{" "}
- {operation.operationQuantity}
- </Trans>
- </Heading>
- )}
- </div>
+ </div>
- <div className="flex flex-col justify-center items-end gap-1">
- <BarProgress
- label={t`Steps`}
- gradient
- invertGradient
- progress={
- (attributes.filter((a) =>
- a.jobOperationStepRecord.some(
- (r) => r.index === activeStep
- )
- ).length /
- attributes.length) *
- 100
- }
- />
- <span className="text-xs text-muted-foreground">
- <Trans>
- {
- attributes.filter((a) =>
+ <div className="flex flex-col justify-center items-end gap-1">
+ <BarProgress
+ label={t`Steps`}
+ gradient
+ invertGradient
+ progress={
+ (attributes.filter((a) =>
a.jobOperationStepRecord.some(
(r) => r.index === activeStep
)
- ).length
- }{" "}
- of {attributes.length} completed
- </Trans>
- </span>
+ ).length /
+ attributes.length) *
+ 100
+ }
+ />
+ <span className="text-xs text-muted-foreground">
+ <Trans>
+ {
+ attributes.filter((a) =>
+ a.jobOperationStepRecord.some(
+ (r) => r.index === activeStep
+ )
+ ).length
+ }{" "}
+ of {attributes.length} completed
+ </Trans>
+ </span>
+ </div>
</div>
- </div>
- );
- })()}
- {attributes.length > 0 && (
- <>
- <div className="flex flex-col items-start justify-between w-full">
- <div className="flex flex-col w-full">
- <div>
- {attributes
- .sort(
- (a, b) =>
- (a.sortOrder ?? 0) -
- (b.sortOrder ?? 0)
- )
- .map((step, index) => (
- <StepsListItem
- key={`step-${step.id}`}
- activeStep={activeStep}
- step={step}
- compact={true}
- onRecord={onRecordStepRecord}
- onDelete={onDeleteStepRecord}
- operationId={operationId}
- className={
- index === attributes.length - 1
- ? "border-none"
- : ""
- }
- />
- ))}
+ );
+ })()}
+ {attributes.length > 0 && (
+ <>
+ <div className="flex flex-col items-start justify-between w-full">
+ <div className="flex flex-col w-full">
+ <div>
+ {attributes
+ .sort(
+ (a, b) =>
+ (a.sortOrder ?? 0) -
+ (b.sortOrder ?? 0)
+ )
+ .map((step, index) => (
+ <StepsListItem
+ key={`step-${step.id}`}
+ activeStep={activeStep}
+ step={step}
+ compact={true}
+ onRecord={onRecordStepRecord}
+ onDelete={onDeleteStepRecord}
+ operationId={operationId}
+ className={
+ index === attributes.length - 1
+ ? "border-none"
+ : ""
+ }
+ />
+ ))}
+ </div>
</div>
</div>
- </div>
- </>
- )}
- </VStack>
- </TabsContent>
- <TabsContent
- value="parameters"
- className="w-full flex-1 flex flex-col overflow-y-auto data-[state=inactive]:hidden"
- >
- <VStack
- className="w-full flex-1 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
- spacing={0}
+ </>
+ )}
+ </VStack>
+ </TabsContent>
+ <TabsContent
+ value="parameters"
+ className="w-full flex-1 flex flex-col overflow-y-auto data-[state=inactive]:hidden"
>
- {parameters.length > 0 && (
- <>
- <Separator />
- <div className="flex flex-col items-start justify-between w-full">
- <div className="flex flex-col gap-4 w-full">
- <div>
- {parameters
- .sort((a, b) =>
- (a.key ?? "").localeCompare(
- b.key ?? ""
+ <VStack
+ className="w-full flex-1 overflow-y-auto scroll-fade scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
+ spacing={0}
+ >
+ {parameters.length > 0 && (
+ <>
+ <Separator />
+ <div className="flex flex-col items-start justify-between w-full">
+ <div className="flex flex-col gap-4 w-full">
+ <div>
+ {parameters
+ .sort((a, b) =>
+ (a.key ?? "").localeCompare(
+ b.key ?? ""
+ )
)
- )
- .map((p, index) => (
- <ParametersListItem
- key={`parameter-${p.id}`}
- parameter={p}
- operationId={operationId}
- className={
- index === parameters.length - 1
- ? "border-none"
- : ""
- }
- />
- ))}
+ .map((p, index) => (
+ <ParametersListItem
+ key={`parameter-${p.id}`}
+ parameter={p}
+ operationId={operationId}
+ className={
+ index === parameters.length - 1
+ ? "border-none"
+ : ""
+ }
+ />
+ ))}
+ </div>
</div>
</div>
- </div>
- </>
- )}
- </VStack>
- </TabsContent>
- </Tabs>
- </ScrollArea>
- );
- }}
- </Await>
- </Suspense>
-
- <ScrollArea className="flex-1 p-4 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
- <div
- className="prose dark:prose-invert"
- dangerouslySetInnerHTML={{
- __html: generateHTML(
- (operation.workInstruction ?? {}) as JSONContent
- )
- }}
- />
- </ScrollArea>
- </div>
+ </>
+ )}
+ </VStack>
+ </TabsContent>
+ </Tabs>
+ </ScrollArea>
+ );
+ }}
+ </Await>
+ </Suspense>
+
+ <ScrollArea className="flex-1 p-4 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
+ <div
+ className="prose dark:prose-invert"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(
+ (operation.workInstruction ?? {}) as JSONContent
+ )
+ }}
+ />
+ </ScrollArea>
+ </div>
+ )}
</TabsContent>
- <TabsContent value="chat">
+ <TabsContent
+ value="chat"
+ className="[grid-area:main] mt-0 h-full min-h-0"
+ >
<OperationChat operation={operation} />
</TabsContent>
{showControls && (
- <Controls>
- <div className="flex flex-col items-center gap-2 p-4">
- <VStack spacing={2}>
- <VStack spacing={1}>
- <span className="text-muted-foreground text-xs">
+ <Controls
+ className="[grid-area:dock]"
+ collapsed={dockCollapsed}
+ onCollapsedChange={onDockCollapsedChange}
+ >
+ <div className="flex w-full min-w-0 items-center gap-2 lg:flex-col lg:py-2">
+ <dl className="hidden w-full gap-3 rounded-lg border bg-card p-3 lg:grid lg:group-data-[collapsed=true]/dock:hidden">
+ <div className="min-w-0">
+ <dt className="text-xs text-muted-foreground">
<Trans>Work Center</Trans>
- </span>
- <Suspense
- fallback={<Heading size="h4">...</Heading>}
- key={`work-center-${operationId}`}
- >
- <Await resolve={workCenter}>
- {(resolvedWorkCenter) =>
- resolvedWorkCenter.data && (
- <Heading size="h4" className="line-clamp-1">
- {resolvedWorkCenter.data?.name}
- </Heading>
- )
- }
- </Await>
- </Suspense>
- </VStack>
-
- <VStack className="hidden tall:flex" spacing={1}>
- <span className="text-muted-foreground text-xs">
+ </dt>
+ <dd>
+ <Suspense
+ fallback={<span className="text-sm">...</span>}
+ key={`work-center-${operationId}`}
+ >
+ <Await resolve={workCenter}>
+ {(resolvedWorkCenter) =>
+ resolvedWorkCenter.data && (
+ <span className="line-clamp-1 text-sm font-medium">
+ {resolvedWorkCenter.data?.name}
+ </span>
+ )
+ }
+ </Await>
+ </Suspense>
+ </dd>
+ </div>
+ <div className="min-w-0">
+ <dt className="text-xs text-muted-foreground">
<Trans>Item</Trans>
- </span>
- <Heading size="h4" className="line-clamp-1">
- {operation.itemReadableId}
- </Heading>
- </VStack>
- </VStack>
-
- <div className="lg:hidden flex flex-col items-center gap-2 w-full">
- <VStack spacing={1}>
- <span className="text-muted-foreground text-xs">
- <Trans>Job</Trans>
- </span>
- <HStack className="justify-start space-x-2">
- <LuClipboardCheck className="text-muted-foreground" />
- <span className="text-sm truncate">
- {operation.jobReadableId}
- </span>
- </HStack>
- </VStack>
- {job.customer?.name && (
- <VStack spacing={1}>
- <span className="text-muted-foreground text-xs">
- <Trans>Customer</Trans>
- </span>
- <HStack className="justify-start space-x-2">
- <LuSquareUser className="text-muted-foreground" />
- <span className="text-sm truncate">
- {job.customer.name}
- </span>
- </HStack>
- </VStack>
- )}
-
- {operation.description && (
- <VStack spacing={1}>
- <span className="text-muted-foreground text-xs">
- <Trans>Description</Trans>
- </span>
- <HStack className="justify-start space-x-2">
- <LuClipboardCheck className="text-muted-foreground" />
- <span className="text-sm truncate">
- {operation.description}
- </span>
- </HStack>
- </VStack>
- )}
- {operation.jobDeadlineType && (
- <VStack spacing={1}>
- <span className="text-muted-foreground text-xs">
- <Trans>Deadline</Trans>
- </span>
- <HStack className="justify-start space-x-2">
- <DeadlineIcon
- deadlineType={operation.jobDeadlineType}
- overdue={isOverdue}
- />
-
- <span
- className={cn(
- "text-sm truncate",
- isOverdue ? "text-red-500" : ""
- )}
- >
- {["ASAP", "No Deadline"].includes(
- operation.jobDeadlineType
- )
- ? operation.jobDeadlineType
- : operation.operationDueDate
- ? t`Due ${formatRelativeTime(
- convertDateStringToIsoString(
- operation.operationDueDate
- )
- )}`
- : "–"}
- </span>
- </HStack>
- </VStack>
- )}
- </div>
+ </dt>
+ <dd className="line-clamp-1 text-sm font-medium">
+ {scope === "batch" && batchFacts
+ ? batchFacts.items.length === 1
+ ? batchFacts.items[0]
+ : t`${batchFacts.items.length} items`
+ : operation.itemReadableId}
+ </dd>
+ </div>
+ </dl>
<WorkTypeToggle
active={active}
operation={displayOperation}
value={eventType}
onChange={setEventType}
+ className="min-w-0 flex-1 lg:flex-none"
/>
<StartStopButton
@@ -2586,7 +2921,30 @@ export const JobOperation = ({
trackedEntityId={trackedEntityId}
batchId={batch?.id}
/>
- <div className="flex flex-row lg:flex-col items-center gap-2 justify-center">
+ {/* What the big button will do, or what is running — the dock
+ only; the rail and the phone bar stay icon-sized. */}
+ <div className="hidden flex-col items-center gap-0.5 text-center lg:flex lg:group-data-[collapsed=true]/dock:hidden">
+ {runningType ? (
+ <>
+ <span className="flex items-center gap-1.5 text-xs font-medium text-emerald-600 dark:text-emerald-400">
+ <span className="size-2 animate-pulse rounded-full bg-emerald-500" />
+ {workTypeLabels[runningType]}
+ </span>
+ <span className="font-mono text-lg tabular-nums">
+ {formatDurationMilliseconds(progress[runningType], {
+ style: "short"
+ })}
+ </span>
+ </>
+ ) : (
+ <span className="text-sm text-muted-foreground">
+ {t`Start ${workTypeLabels[
+ eventType.toLowerCase() as keyof typeof workTypeLabels
+ ].toLowerCase()}`}
+ </span>
+ )}
+ </div>
+ <div className="flex flex-row lg:hidden lg:group-data-[collapsed=true]/dock:flex lg:flex-col items-center gap-2 justify-center">
<IconButtonWithTooltip
disabled={
!isBatched &&
@@ -2618,157 +2976,129 @@ export const JobOperation = ({
onClick={actionsSheet.onOpen}
/>
</div>
+ <div className="hidden w-full flex-col gap-2 lg:flex lg:group-data-[collapsed=true]/dock:hidden">
+ <Button
+ size="lg"
+ variant="secondary"
+ className="w-full"
+ leftIcon={isBatched ? <LuPackageCheck /> : <FaPlus />}
+ isDisabled={
+ !isBatched &&
+ parentIsSerial &&
+ trackedEntities.some(
+ (entity) =>
+ entity.id === trackedEntityId &&
+ `Operation ${operationId}` in
+ (entity.attributes as TrackedEntityAttributes)
+ )
+ }
+ onClick={
+ isBatched ? batchCompleteModal.onOpen : completeModal.onOpen
+ }
+ >
+ {isBatched ? (
+ <Trans>Complete batch</Trans>
+ ) : (
+ <Trans>Log completed</Trans>
+ )}
+ </Button>
+ <Button
+ size="lg"
+ variant="ghost"
+ className="w-full"
+ leftIcon={<LuEllipsisVertical />}
+ onClick={actionsSheet.onOpen}
+ >
+ <Trans>More actions</Trans>
+ </Button>
+ </div>
</div>
</Controls>
)}
{!["chat"].includes(activeTab) && (
- <Times>
- <div className=" lg:p-6">
- <div className="w-full gap-2 grid grid-cols-[auto_auto_1fr]">
- {displayOperation.setupDuration > 0 && (
- <>
- <Tooltip>
- <TooltipTrigger>
- <LuTimer className="h-4 w-4 mr-1" />
- </TooltipTrigger>
- <TooltipContent side="right">
- <Trans>Setup</Trans>
- </TooltipContent>
- </Tooltip>
- <span className="text-xs text-muted-foreground font-mono flex-shrink-0 flex-nowrap">
- {formatDurationMilliseconds(progress.setup, {
- style: "short"
- })}
- /
- {formatDurationMilliseconds(
- displayOperation.setupDuration,
- {
- style: "short"
- }
- )}
- </span>
- <BarProgress
- gradient
- invertGradient
- progress={
- (progress.setup / displayOperation.setupDuration) * 100
- }
- activeClassName={
- progress.setup > displayOperation.setupDuration
- ? "bg-red-500"
- : "bg-emerald-500"
- }
- />
- </>
- )}
- {displayOperation.laborDuration > 0 && (
- <>
- <Tooltip>
- <TooltipTrigger>
- <LuHardHat className="h-4 w-4 mr-1" />
- </TooltipTrigger>
- <TooltipContent side="right">
- <Trans>Labor</Trans>
- </TooltipContent>
- </Tooltip>
- <span className="text-xs text-muted-foreground font-mono flex-shrink-0 flex-nowrap">
- {formatDurationMilliseconds(progress.labor, {
- style: "short"
- })}
- /
- {formatDurationMilliseconds(
- displayOperation.laborDuration,
- {
- style: "short"
- }
- )}
- </span>
+ <Times className="[grid-area:status]">
+ {/* Labelled meters: two per row on a phone, then as many columns
+ as fit (four across a desktop). */}
+ <div className="grid grid-cols-2 gap-x-4 gap-y-2 sm:gap-x-6 sm:grid-cols-[repeat(auto-fit,minmax(180px,1fr))]">
+ {(
+ [
+ {
+ type: "setup",
+ label: t`Setup`,
+ elapsed: progress.setup,
+ planned: displayOperation.setupDuration
+ },
+ {
+ type: "labor",
+ label: t`Labor`,
+ elapsed: progress.labor,
+ planned: displayOperation.laborDuration
+ },
+ {
+ type: "machine",
+ label: t`Machine`,
+ elapsed: progress.machine,
+ planned: displayOperation.machineDuration
+ }
+ ] as const
+ )
+ .filter((meter) => meter.planned > 0)
+ .map((meter) => {
+ // A batch with no planned time anywhere carries a 1ms
+ // placeholder plan (so ratios never divide by zero). That is
+ // not a plan: show elapsed time alone over an empty track.
+ const hasPlan = meter.planned > 1;
+ const elapsed = formatDurationMilliseconds(meter.elapsed, {
+ style: "short"
+ });
+ return (
<BarProgress
- gradient
- invertGradient
- progress={
- (progress.labor / displayOperation.laborDuration) * 100
- }
- activeClassName={
- progress.labor > displayOperation.laborDuration
- ? "bg-red-500"
- : "bg-emerald-500"
+ key={meter.type}
+ label={meter.label}
+ value={
+ hasPlan
+ ? `${elapsed} / ${formatDurationMilliseconds(
+ meter.planned,
+ { style: "short" }
+ )}`
+ : elapsed
}
- />
- </>
- )}
- {displayOperation.machineDuration > 0 && (
- <>
- <Tooltip>
- <TooltipTrigger>
- <LuHammer className="h-4 w-4 mr-1" />
- </TooltipTrigger>
- <TooltipContent side="right">
- <Trans>Machine</Trans>
- </TooltipContent>
- </Tooltip>
- <span className="text-xs text-muted-foreground font-mono flex-shrink-0 flex-nowrap">
- {formatDurationMilliseconds(progress.machine, {
- style: "short"
- })}
- /
- {formatDurationMilliseconds(
- displayOperation.machineDuration,
- {
- style: "short"
- }
- )}
- </span>
- <BarProgress
gradient
invertGradient
progress={
- (progress.machine / displayOperation.machineDuration) *
- 100
+ hasPlan ? (meter.elapsed / meter.planned) * 100 : 0
}
activeClassName={
- progress.machine > displayOperation.machineDuration
+ meter.elapsed > meter.planned
? "bg-red-500"
: "bg-emerald-500"
}
/>
- </>
- )}
- <>
- <Tooltip>
- <TooltipTrigger>
- <FaTasks className="h-4 w-4 mr-1" />
- </TooltipTrigger>
- <TooltipContent side="right">
- <Trans>Quantity</Trans>
- </TooltipContent>
- </Tooltip>
- <span className="text-xs text-muted-foreground font-mono flex-shrink-0 flex-nowrap min-w-[100px]">
- {operation.quantityComplete}/{operation.targetQuantity}
- </span>
- <BarProgress
- segments={[
- {
- value: operation.quantityComplete,
- className: "bg-emerald-500"
- },
- {
- value: operation.quantityReworked ?? 0,
- className: "bg-yellow-500"
- },
- {
- value: operation.quantityScrapped ?? 0,
- className: "bg-red-500"
- }
- ]}
- max={operation.targetQuantity || 1}
- progress={
- (operation.quantityComplete / operation.targetQuantity) *
- 100
- }
- />
- </>
- </div>
+ );
+ })}
+ <BarProgress
+ label={isBatched ? t`Batch quantity` : t`Quantity`}
+ value={`${quantityProgress.complete} / ${quantityProgress.target}`}
+ segments={[
+ {
+ value: quantityProgress.complete,
+ className: "bg-emerald-500"
+ },
+ {
+ value: quantityProgress.reworked,
+ className: "bg-yellow-500"
+ },
+ {
+ value: quantityProgress.scrapped,
+ className: "bg-red-500"
+ }
+ ]}
+ max={quantityProgress.target || 1}
+ progress={
+ (quantityProgress.complete / (quantityProgress.target || 1)) *
+ 100
+ }
+ />
</div>
</Times>
)}
@@ -2962,6 +3292,7 @@ export const JobOperation = ({
<BatchCompleteModal
batch={batch}
isCompleting={isCompleting}
+ fetcher={batchCompleteFetcher}
onClose={batchCompleteModal.onClose}
/>
)}
diff --git a/apps/mes/app/components/JobOperation/components/BatchCompleteModal.tsx b/apps/mes/app/components/JobOperation/components/BatchCompleteModal.tsx
index e37c33bed8..af0df0123c 100644
--- a/apps/mes/app/components/JobOperation/components/BatchCompleteModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/BatchCompleteModal.tsx
@@ -1,5 +1,8 @@
import { Hidden, Submit, ValidatedForm } from "@carbon/form";
import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
cn,
Modal,
ModalBody,
@@ -11,6 +14,8 @@ import {
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import { useState } from "react";
+import { LuLayers, LuTriangleAlert } from "react-icons/lu";
+import type { useFetcher } from "react-router";
import type { z } from "zod";
import { completeJobOperationBatchValidator } from "~/services/models";
import type { JobOperationBatch } from "~/services/operations.service";
@@ -33,14 +38,21 @@ const toNumber = (value: string) => Number(value) || 0;
export function BatchCompleteModal({
batch,
isCompleting,
+ fetcher,
onClose
}: {
batch: JobOperationBatch;
isCompleting: boolean;
+ fetcher: ReturnType<typeof useFetcher>;
onClose: () => void;
}) {
const { t } = useLingui();
const members = batch.operations ?? [];
+ // Any member producing a batch-tracked item gets a batch-number column; its
+ // WIP entity is finalized as the produced lot at completion.
+ const anyTracked = members.some((m) => m.requiresBatchTracking);
+ // A merged batch states its one lot in a banner; split lots show per row.
+ const showLotColumn = anyTracked && !batch.mergeOutput;
const initialValues = {
batchId: batch.id as string,
@@ -78,6 +90,22 @@ export function BatchCompleteModal({
(r) => toNumber(r.quantity) === 0 && toNumber(r.scrapQuantity) === 0
);
+ // Lot identity was planned when the batch was created — the floor only
+ // reads it. A merged batch has one lot for everything; otherwise each
+ // batch-tracked member carries its own number (its WIP entity's readableId).
+ const producesLot = (i: number) => {
+ const m = members[i];
+ return Boolean(
+ m?.requiresBatchTracking &&
+ m?.trackedEntityId &&
+ toNumber(rows[i]?.quantity ?? "0") > 0
+ );
+ };
+ const merged = Boolean(batch.mergeOutput && batch.outputLotNumber);
+ const unplanned = merged
+ ? []
+ : members.filter((m, i) => producesLot(i) && !m.batchNumber?.trim());
+
return (
<Modal
open
@@ -101,9 +129,45 @@ export function BatchCompleteModal({
action={path.to.batchComplete(batch.id as string)}
validator={completeJobOperationBatchValidator}
defaultValues={initialValues}
+ fetcher={fetcher}
>
<ModalBody>
<Hidden name="batchId" value={batch.id as string} />
+ {merged && (
+ <Alert variant="success" className="mb-4">
+ <LuLayers />
+ <AlertTitle>
+ <Trans>
+ All output goes to lot{" "}
+ <span className="font-mono">{batch.outputLotNumber}</span>
+ </Trans>
+ </AlertTitle>
+ <AlertDescription>
+ <Trans>Set when the batch was planned.</Trans>
+ </AlertDescription>
+ </Alert>
+ )}
+ {unplanned.length > 0 && (
+ <Alert variant="warning" className="mb-4">
+ <LuTriangleAlert />
+ <AlertTitle>
+ <Trans>Lot numbers missing</Trans>
+ </AlertTitle>
+ <AlertDescription>
+ <Trans>
+ {unplanned
+ .map(
+ (m) =>
+ (m.job as { jobId?: string | null } | null)?.jobId
+ )
+ .filter(Boolean)
+ .join(", ")}{" "}
+ has no lot number. Set it on the batch or job in Carbon,
+ then complete.
+ </Trans>
+ </AlertDescription>
+ </Alert>
+ )}
<div className="overflow-hidden rounded-lg border border-border bg-card">
<table className="w-full border-separate border-spacing-0 text-sm">
<thead>
@@ -114,9 +178,19 @@ export function BatchCompleteModal({
<th className="w-[140px] border-b border-r border-border px-3 py-2 text-right font-medium text-muted-foreground">
<Trans>Quantity</Trans>
</th>
- <th className="w-[140px] border-b border-border px-3 py-2 text-right font-medium text-muted-foreground">
+ <th
+ className={cn(
+ "w-[140px] border-b border-border px-3 py-2 text-right font-medium text-muted-foreground",
+ showLotColumn && "border-r"
+ )}
+ >
<Trans>Scrap</Trans>
</th>
+ {showLotColumn && (
+ <th className="w-[180px] border-b border-border px-3 py-2 text-left font-medium text-muted-foreground">
+ <Trans>Lot</Trans>
+ </th>
+ )}
</tr>
</thead>
<tbody>
@@ -140,6 +214,12 @@ export function BatchCompleteModal({
name={`members[${i}].excluded`}
value={isExcluded ? "true" : ""}
/>
+ {m.requiresBatchTracking && m.trackedEntityId && (
+ <Hidden
+ name={`members[${i}].trackedEntityId`}
+ value={m.trackedEntityId}
+ />
+ )}
</td>
<td
className={cn(
@@ -163,6 +243,7 @@ export function BatchCompleteModal({
<td
className={cn(
"border-border p-0 align-middle",
+ showLotColumn && "border-r",
!isLast && "border-b"
)}
>
@@ -179,6 +260,19 @@ export function BatchCompleteModal({
className={cellInputClass}
/>
</td>
+ {showLotColumn && (
+ <td
+ className={cn(
+ "border-border px-3 py-2 align-middle font-mono",
+ !isLast && "border-b",
+ !m.batchNumber?.trim() && "text-muted-foreground"
+ )}
+ >
+ {m.requiresBatchTracking && m.trackedEntityId
+ ? m.batchNumber?.trim() || "—"
+ : null}
+ </td>
+ )}
</tr>
);
})}
@@ -193,8 +287,13 @@ export function BatchCompleteModal({
</p>
</ModalBody>
<ModalFooter>
- <Submit size="lg" isDisabled={allExcluded}>
- {isCompleting ? t`Retry Completion` : t`Complete Batch`}
+ <Submit size="lg" isDisabled={allExcluded || unplanned.length > 0}>
+ {/* While the submit is in flight the realtime revalidation sees the
+ batch pass through Completing — don't flip the label mid-run;
+ "Retry" is only true once we are idle and still parked there. */}
+ {fetcher.state === "idle" && isCompleting
+ ? t`Retry Completion`
+ : t`Complete Batch`}
</Submit>
</ModalFooter>
</ValidatedForm>
diff --git a/apps/mes/app/components/JobOperation/components/BatchOverview.tsx b/apps/mes/app/components/JobOperation/components/BatchOverview.tsx
new file mode 100644
index 0000000000..7bf8ef6498
--- /dev/null
+++ b/apps/mes/app/components/JobOperation/components/BatchOverview.tsx
@@ -0,0 +1,908 @@
+import { convertKbToString } from "@carbon/files";
+import {
+ Badge,
+ Button,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ cn,
+ Heading,
+ IconButton,
+ Progress,
+ Separator,
+ Table,
+ Tbody,
+ Td,
+ Tfoot,
+ Th,
+ Thead,
+ Tr
+} from "@carbon/react";
+import { formatDate, groupBy } from "@carbon/utils";
+import { Trans, useLingui } from "@lingui/react/macro";
+import type { ReactNode } from "react";
+import { Fragment, Suspense, useCallback, useState } from "react";
+import { FaCheck, FaTrash } from "react-icons/fa";
+import {
+ LuActivity,
+ LuChevronDown,
+ LuChevronRight,
+ LuCircleCheck,
+ LuDownload,
+ LuGitBranchPlus,
+ LuLayers,
+ LuMapPin
+} from "react-icons/lu";
+import { Await, Link } from "react-router";
+import { FileIcon, FilePreview } from "~/components";
+import { ProcedureStepTypeIcon, TrackingTypeIcon } from "~/components/Icons";
+import ItemThumbnail from "~/components/ItemThumbnail";
+import type {
+ BatchFile,
+ BatchMaterialTotal,
+ BatchStep,
+ BatchWorkInstructions,
+ JobOperationBatch
+} from "~/services/operations.service";
+import { getFileType } from "~/services/operations.service";
+import type {
+ JobMaterial,
+ JobOperationStep,
+ StorageItem
+} from "~/services/types";
+import { path } from "~/utils/path";
+import { BatchRecordModal } from "./BatchRecordModal";
+import { hasStepDescription, StepMedia } from "./Step";
+import { TableSkeleton } from "./TableSkeleton";
+
+type ItemType = Parameters<typeof ItemThumbnail>[0]["type"];
+
+// The batch as the unit of work: aggregated quantities, the one shared pick
+// per material, where the output lands, and every member job. Rendered by
+// JobOperation in place of the per-job details when the "Batch" scope is on.
+export function BatchOverview({
+ batch,
+ totals,
+ currentMaterials,
+ onIssue,
+ workInstructions,
+ onDownloadFile,
+ view = "details"
+}: {
+ batch: JobOperationBatch;
+ totals: Record<string, BatchMaterialTotal>;
+ // This job's material rows — the shared pick is launched from one of them,
+ // and batch mode on the issue modal widens it to the whole batch.
+ currentMaterials: JobMaterial[];
+ onIssue: (material: JobMaterial) => void;
+ // Steps, parameters and files across every member (streams in after load).
+ workInstructions?: Promise<BatchWorkInstructions> | null;
+ onDownloadFile: (file: StorageItem) => void;
+ // Details: stats, materials, files, jobs. Instructions: the steps and
+ // process parameters every job follows — the batch's Instructions tab.
+ view?: "details" | "instructions";
+}) {
+ const { t } = useLingui();
+ const jobIdOf = (m: NonNullable<JobOperationBatch["operations"]>[number]) =>
+ (m.job as { jobId?: string | null } | null)?.jobId ?? m.id;
+ // Job-number order everywhere, so per-job splits line up with the jobs table.
+ const members = [...(batch.operations ?? [])].sort((a, b) =>
+ jobIdOf(a).localeCompare(jobIdOf(b), undefined, { numeric: true })
+ );
+ const jobIdByOperation = new Map(members.map((m) => [m.id, jobIdOf(m)]));
+
+ const quantity = members.reduce((s, m) => s + (m.operationQuantity ?? 0), 0);
+ const completed = members.reduce((s, m) => s + (m.quantityComplete ?? 0), 0);
+ const scrapped = members.reduce((s, m) => s + (m.quantityScrapped ?? 0), 0);
+
+ const materials = Object.entries(totals).sort(([, a], [, b]) =>
+ (a.itemReadableId ?? "").localeCompare(b.itemReadableId ?? "")
+ );
+ const trackedLines = materials.filter(
+ ([, m]) => m.requiresBatchTracking || m.requiresSerialTracking
+ );
+ const issuedLines = trackedLines.filter(
+ ([, m]) => m.required > 0 && m.issued >= m.required
+ );
+
+ const merged = Boolean(batch.mergeOutput && batch.outputLotNumber);
+ const materialByItem = new Map(
+ currentMaterials.map((m) => [m.itemId, m] as const)
+ );
+ const memberOrder = new Map(members.map((m, i) => [m.id, i] as const));
+ const mixedItems =
+ new Set(members.map((m) => m.jobMakeMethod?.item?.readableIdWithRevision))
+ .size > 1;
+ // A merged batch names its one lot in the section header instead.
+ const showLots = !merged && members.some((m) => m.requiresBatchTracking);
+ const remaining = (m: (typeof members)[number]) =>
+ Math.max(0, (m.operationQuantity ?? 0) - (m.quantityComplete ?? 0));
+ const inJobOrder = <T extends { jobOperationId: string }>(rows: T[]) =>
+ [...rows].sort(
+ (a, b) =>
+ (memberOrder.get(a.jobOperationId) ?? 0) -
+ (memberOrder.get(b.jobOperationId) ?? 0)
+ );
+ // Files under a sub-header per job: the batch-wide ones (the item's) first,
+ // then each job in job order.
+ const fileGroups = (files: BatchFile[]) => {
+ const byJob = groupBy(files, (file) => file.jobReadableId ?? "");
+ const order = ["", ...members.map(jobIdOf)];
+ return Object.entries(byJob).sort(
+ ([a], [b]) => order.indexOf(a) - order.indexOf(b)
+ );
+ };
+ const [recordingKey, setRecordingKey] = useState<string | null>(null);
+ const closeRecord = useCallback(() => setRecordingKey(null), []);
+ // Descriptions start open, as on the job's own step list.
+ const [collapsedSteps, setCollapsedSteps] = useState<Set<string>>(
+ () => new Set()
+ );
+ const toggleStep = (key: string) =>
+ setCollapsedSteps((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ return next;
+ });
+
+ if (view === "instructions") {
+ return (
+ <>
+ {workInstructions && (
+ <Suspense fallback={<TableSkeleton />}>
+ <Await resolve={workInstructions}>
+ {(resolved) => (
+ <>
+ {resolved.steps.length === 0 &&
+ resolved.parameters.length === 0 && (
+ <p className="p-6 text-sm text-muted-foreground">
+ <Trans>This batch has no work instructions.</Trans>
+ </p>
+ )}
+ {resolved.steps.length > 0 && (
+ <Section
+ divider={false}
+ title={t`Work instructions`}
+ description={t`Every job in the batch follows these steps. Record a step for all of them at once.`}
+ >
+ <Panel>
+ <ul className="divide-y">
+ {resolved.steps.map((step, _i, steps) => {
+ const anyDescription = steps.some((s) =>
+ hasStepDescription(
+ s.description as JobOperationStep["description"]
+ )
+ );
+ const spec = stepSpecification(step);
+ const recorded = step.perMember.filter(
+ (m) => m.recorded
+ ).length;
+ const allRecorded =
+ recorded === step.perMember.length;
+ const hasDescription = hasStepDescription(
+ step.description as JobOperationStep["description"]
+ );
+ const descriptionOpen =
+ hasDescription && !collapsedSteps.has(step.key);
+ return (
+ <li
+ key={step.key}
+ className="px-4 py-3.5 transition-colors hover:bg-muted/30 md:px-5"
+ >
+ <div className="flex flex-col gap-3 md:flex-row md:items-center md:gap-6">
+ <div className="flex min-w-0 flex-1 items-center gap-3">
+ <IconChip>
+ <ProcedureStepTypeIcon
+ type={
+ step.type as Parameters<
+ typeof ProcedureStepTypeIcon
+ >[0]["type"]
+ }
+ />
+ </IconChip>
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span className="text-sm font-medium text-pretty">
+ {step.name}
+ </span>
+ {step.required && (
+ <Badge variant="gray">
+ <Trans>Required</Trans>
+ </Badge>
+ )}
+ </div>
+ {spec && (
+ <p className="text-sm tabular-nums text-muted-foreground">
+ {spec}
+ </p>
+ )}
+ </div>
+ </div>
+ <div className="flex flex-wrap items-center gap-1.5 pl-12 md:justify-end md:pl-0">
+ {/* How far the batch is, not which job is
+ which — the record grid names the jobs. */}
+ <div
+ className="flex w-24 gap-0.5"
+ aria-hidden
+ >
+ {inJobOrder(step.perMember).map(
+ (member) => (
+ <span
+ key={member.stepId}
+ className={cn(
+ "h-1.5 flex-1 rounded-full",
+ member.recorded
+ ? "bg-emerald-500"
+ : "bg-muted-foreground/20"
+ )}
+ />
+ )
+ )}
+ </div>
+ <span className="mr-1 w-16 text-xs tabular-nums text-muted-foreground">
+ {t`${recorded}/${step.perMember.length} jobs`}
+ </span>
+ <Button
+ variant={
+ allRecorded ? "ghost" : "secondary"
+ }
+ rightIcon={<LuCircleCheck />}
+ onClick={() => setRecordingKey(step.key)}
+ >
+ {allRecorded ? (
+ <Trans>Update</Trans>
+ ) : (
+ <Trans>Record</Trans>
+ )}
+ </Button>
+ {hasDescription ? (
+ <IconButton
+ aria-label={
+ descriptionOpen
+ ? t`Hide description`
+ : t`Show description`
+ }
+ variant="ghost"
+ icon={
+ descriptionOpen ? (
+ <LuChevronDown />
+ ) : (
+ <LuChevronRight />
+ )
+ }
+ onClick={() => toggleStep(step.key)}
+ />
+ ) : (
+ anyDescription && (
+ // Keeps the progress column aligned
+ // with rows that have the toggle.
+ <span className="hidden size-8 shrink-0 md:block" />
+ )
+ )}
+ </div>
+ </div>
+ {(hasDescription || step.slides.length > 0) && (
+ <div className="pl-12">
+ <StepMedia
+ description={
+ step.description as JobOperationStep["description"]
+ }
+ slides={step.slides}
+ showDescription={descriptionOpen}
+ />
+ </div>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ </Panel>
+ {(() => {
+ const step = resolved.steps.find(
+ (s) => s.key === recordingKey
+ );
+ return step ? (
+ <BatchRecordModal
+ batchId={batch.id as string}
+ step={step}
+ members={inJobOrder(step.perMember)}
+ jobIdOf={(id) => jobIdByOperation.get(id) ?? id}
+ onClose={closeRecord}
+ />
+ ) : null;
+ })()}
+ </Section>
+ )}
+
+ {resolved.parameters.length > 0 && (
+ <Section title={t`Process parameters`}>
+ <Panel>
+ <dl className="divide-y">
+ {resolved.parameters.map((parameter) => (
+ <div
+ key={parameter.key}
+ className="flex items-center justify-between gap-4 px-4 py-3 md:px-5"
+ >
+ <dt className="flex min-w-0 items-center gap-3 text-sm font-medium">
+ <IconChip>
+ <LuActivity />
+ </IconChip>
+ <span className="truncate">
+ {parameter.key}
+ </span>
+ </dt>
+ <dd className="flex min-w-0 flex-col items-end gap-1 text-right">
+ {parameter.values.length === 1 ? (
+ <span className="font-medium tabular-nums">
+ {parameter.values[0]?.value}
+ </span>
+ ) : (
+ parameter.values.map((v) => (
+ <span
+ key={v.value}
+ className="text-sm tabular-nums"
+ >
+ <span className="font-medium">
+ {v.value}
+ </span>{" "}
+ <span className="text-muted-foreground">
+ ·{" "}
+ {v.jobOperationIds
+ .map(
+ (id) =>
+ jobIdByOperation.get(id) ?? id
+ )
+ .join(", ")}
+ </span>
+ </span>
+ ))
+ )}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ </Panel>
+ </Section>
+ )}
+ </>
+ )}
+ </Await>
+ </Suspense>
+ )}
+ </>
+ );
+ }
+
+ return (
+ <>
+ <div className="flex items-start p-4 lg:p-6">
+ <div className="grid gap-3 md:gap-4 grid-cols-2 xl:grid-cols-4 w-full min-w-0">
+ <Card>
+ <CardHeader className="flex flex-row items-center gap-2 justify-between">
+ <CardTitle>
+ <Trans>Completed</Trans>
+ </CardTitle>
+ <FaCheck className="h-3 w-3 text-emerald-500" />
+ </CardHeader>
+ <CardContent>
+ <Heading size="h1">
+ <Trans>
+ {completed} of {quantity}
+ </Trans>
+ </Heading>
+ <p className="text-sm text-muted-foreground">
+ {t`across ${members.length} jobs`}
+ </p>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader className="flex flex-row items-center gap-2 justify-between">
+ <CardTitle>
+ <Trans>Materials issued</Trans>
+ </CardTitle>
+ <LuGitBranchPlus className="h-3 w-3 text-muted-foreground" />
+ </CardHeader>
+ <CardContent>
+ <Heading size="h1">
+ <Trans>
+ {issuedLines.length} of {trackedLines.length}
+ </Trans>
+ </Heading>
+ <p className="text-sm text-muted-foreground">
+ <Trans>tracked lines</Trans>
+ </p>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader className="flex flex-row items-center gap-2 justify-between">
+ <CardTitle>
+ <Trans>Scrapped</Trans>
+ </CardTitle>
+ <FaTrash className="h-3 w-3 text-muted-foreground" />
+ </CardHeader>
+ <CardContent>
+ <Heading size="h1">{scrapped}</Heading>
+ <p className="text-sm text-muted-foreground">
+ <Trans>batch total</Trans>
+ </p>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader className="flex flex-row items-center gap-2 justify-between">
+ <CardTitle>
+ <Trans>Output lot</Trans>
+ </CardTitle>
+ <LuLayers className="h-3 w-3 text-emerald-500" />
+ </CardHeader>
+ <CardContent>
+ <Heading size="h3" className="font-mono truncate">
+ {merged ? batch.outputLotNumber : t`Separate lots`}
+ </Heading>
+ <p className="text-sm text-muted-foreground">
+ {merged ? (
+ <Trans>one combined lot · planned</Trans>
+ ) : (
+ <Trans>one per job · planned</Trans>
+ )}
+ </p>
+ </CardContent>
+ </Card>
+ </div>
+ </div>
+
+ {/* Always shown in batch mode so the operator can see the jobs, parts
+ and quantities that belong in the run — a laser nest or an oven load
+ is the same item across many jobs, and needs the per-job list even
+ when the parts don't have to be kept apart afterwards. */}
+ <Section
+ title={t`Load list`}
+ description={
+ mixedItems
+ ? t`The jobs make different items — keep each job's parts apart.`
+ : showLots
+ ? t`Each job's output is its own lot — keep each job's parts apart.`
+ : t`The jobs and parts that make up this run.`
+ }
+ >
+ <Panel>
+ <Table>
+ <Thead className="bg-muted/40">
+ <Tr>
+ <Th className={th}>
+ <Trans>Job</Trans>
+ </Th>
+ <Th className={cn(th, "hidden md:table-cell")}>
+ <Trans>Item</Trans>
+ </Th>
+ <Th className={cn(th, "hidden md:table-cell")}>
+ <Trans>Due</Trans>
+ </Th>
+ {showLots && (
+ <Th className={cn(th, "hidden md:table-cell")}>
+ <Trans>Lot</Trans>
+ </Th>
+ )}
+ <Th className={cn(th, "whitespace-nowrap text-right")}>
+ <Trans>To run</Trans>
+ </Th>
+ </Tr>
+ </Thead>
+ <Tbody className={rows}>
+ {members.map((m) => {
+ const job = m.job as {
+ deadlineType?: string | null;
+ customer?: { name?: string | null } | null;
+ } | null;
+ const toRun = remaining(m);
+ return (
+ <Tr key={m.id}>
+ <Td className={cn(td, "w-full max-w-0")}>
+ <Link
+ to={`${path.to.operation(m.id)}?scope=job`}
+ className="font-medium hover:underline"
+ >
+ {jobIdOf(m)}
+ </Link>
+ {job?.customer?.name && (
+ <p className="truncate text-sm text-muted-foreground">
+ {job.customer.name}
+ </p>
+ )}
+ </Td>
+ <Td
+ className={cn(
+ td,
+ "hidden whitespace-nowrap text-sm md:table-cell"
+ )}
+ >
+ {m.jobMakeMethod?.item?.readableIdWithRevision}
+ </Td>
+ <Td
+ className={cn(
+ td,
+ "hidden whitespace-nowrap text-sm text-muted-foreground md:table-cell"
+ )}
+ >
+ {["ASAP", "No Deadline"].includes(
+ job?.deadlineType ?? ""
+ ) || !m.dueDate
+ ? (job?.deadlineType ?? "—")
+ : formatDate(m.dueDate)}
+ </Td>
+ {showLots && (
+ <Td
+ className={cn(
+ td,
+ "hidden whitespace-nowrap font-mono text-sm md:table-cell"
+ )}
+ >
+ {m.requiresBatchTracking ? m.batchNumber || "—" : "—"}
+ </Td>
+ )}
+ <Td className={cn(td, "whitespace-nowrap text-right")}>
+ <span className="font-medium tabular-nums">{toRun}</span>
+ {toRun !== (m.operationQuantity ?? 0) && (
+ <span className="ml-1 text-xs tabular-nums text-muted-foreground">
+ {t`of ${m.operationQuantity ?? 0}`}
+ </span>
+ )}
+ </Td>
+ </Tr>
+ );
+ })}
+ </Tbody>
+ <Tfoot className="border-t bg-muted/40">
+ <Tr>
+ <Td
+ colSpan={1 + 1 + 1 + (showLots ? 1 : 0)}
+ className={cn(td, "text-sm text-muted-foreground")}
+ >
+ <Trans>Total</Trans>
+ </Td>
+ <Td
+ className={cn(
+ td,
+ "whitespace-nowrap text-right font-medium tabular-nums"
+ )}
+ >
+ {members.reduce((sum, m) => sum + remaining(m), 0)}
+ </Td>
+ </Tr>
+ </Tfoot>
+ </Table>
+ </Panel>
+ </Section>
+
+ <Section
+ title={t`Materials`}
+ description={t`One pick covers the whole batch — it is shared out to the jobs automatically.`}
+ >
+ <Panel>
+ <Table>
+ <Tbody className={rows}>
+ {materials.length === 0 ? (
+ <Tr>
+ <Td
+ colSpan={4}
+ className="py-8 text-center text-muted-foreground"
+ >
+ <Trans>No materials on this batch.</Trans>
+ </Td>
+ </Tr>
+ ) : (
+ [
+ {
+ key: "pick",
+ label: t`To pick`,
+ lines: trackedLines
+ },
+ {
+ key: "backflush",
+ label: t`Used automatically at completion`,
+ lines: materials.filter(
+ ([, m]) =>
+ !m.requiresBatchTracking && !m.requiresSerialTracking
+ )
+ }
+ ]
+ .filter((group) => group.lines.length > 0)
+ .map((group) => (
+ <Fragment key={group.key}>
+ <Tr>
+ <Td colSpan={4} className={groupHeader}>
+ {group.label}
+ </Td>
+ </Tr>
+ {group.lines.map(([itemId, m]) => {
+ const tracked = group.key === "pick";
+ const fullyIssued =
+ m.required > 0 && m.issued >= m.required;
+ const pickFrom = materialByItem.get(itemId);
+ const action = !tracked ? null : fullyIssued ? (
+ <Badge variant="green" className="gap-1">
+ <FaCheck className="size-2.5" />
+ <Trans>Issued</Trans>
+ </Badge>
+ ) : pickFrom ? (
+ <Button
+ leftIcon={<LuGitBranchPlus />}
+ onClick={() => onIssue(pickFrom)}
+ >
+ <Trans>Pick {m.required - m.issued}</Trans>
+ </Button>
+ ) : null;
+ return (
+ <Tr key={itemId}>
+ <Td className={cn(td, "w-full max-w-0")}>
+ <div className="flex min-w-0 items-center gap-3">
+ <div className="hidden shrink-0 sm:block">
+ <ItemThumbnail
+ thumbnailPath={m.thumbnailPath}
+ type={m.itemType as ItemType}
+ />
+ </div>
+ <div className="min-w-0">
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="truncate font-medium">
+ {m.itemReadableId}
+ </span>
+ {tracked && (
+ <Badge
+ variant="outline"
+ className="shrink-0 gap-1 font-medium normal-case"
+ >
+ <TrackingTypeIcon
+ type={
+ m.requiresSerialTracking
+ ? "Serial"
+ : "Batch"
+ }
+ />
+ <span className="hidden sm:inline">
+ {m.requiresSerialTracking ? (
+ <Trans>Serialized</Trans>
+ ) : (
+ <Trans>Lot tracked</Trans>
+ )}
+ </span>
+ </Badge>
+ )}
+ </div>
+ <p className="truncate text-sm text-muted-foreground">
+ {m.name}
+ </p>
+ </div>
+ </div>
+ </Td>
+ <Td
+ className={cn(
+ td,
+ "hidden whitespace-nowrap text-sm text-muted-foreground md:table-cell"
+ )}
+ >
+ {m.storageUnitName && (
+ <span className="inline-flex items-center gap-1.5">
+ <LuMapPin className="size-3.5" />
+ {m.storageUnitName}
+ </span>
+ )}
+ </Td>
+ <Td
+ className={cn(
+ td,
+ "whitespace-nowrap text-right md:w-48"
+ )}
+ >
+ {tracked ? (
+ <div className="flex flex-col items-end gap-1.5">
+ <span className="text-sm tabular-nums text-muted-foreground">
+ <span className="font-medium text-foreground">
+ {m.issued}
+ </span>{" "}
+ / {m.required} {m.unitOfMeasureCode}
+ </span>
+ <Progress
+ value={
+ m.required > 0
+ ? Math.min(
+ 100,
+ (m.issued / m.required) * 100
+ )
+ : 0
+ }
+ className="h-1.5 w-full min-w-24"
+ indicatorClassName={
+ fullyIssued
+ ? "bg-emerald-500"
+ : "bg-primary"
+ }
+ />
+ {action && (
+ <div className="sm:hidden">{action}</div>
+ )}
+ </div>
+ ) : (
+ <span className="text-sm font-medium tabular-nums">
+ {m.required} {m.unitOfMeasureCode}
+ </span>
+ )}
+ </Td>
+ <Td
+ className={cn(
+ td,
+ "hidden w-px whitespace-nowrap text-right sm:table-cell"
+ )}
+ >
+ {action}
+ </Td>
+ </Tr>
+ );
+ })}
+ </Fragment>
+ ))
+ )}
+ </Tbody>
+ </Table>
+ </Panel>
+ </Section>
+
+ {workInstructions && (
+ <Suspense fallback={null}>
+ <Await resolve={workInstructions}>
+ {(resolved) => (
+ <>
+ {resolved.files.length > 0 && (
+ <Section title={t`Files`}>
+ <Panel>
+ <Table>
+ <Tbody className={rows}>
+ {fileGroups(resolved.files).map(
+ ([jobReadableId, files]) => (
+ <Fragment key={jobReadableId || "batch"}>
+ {jobReadableId ? (
+ <Tr key={`group-${jobReadableId}`}>
+ <Td colSpan={2} className={groupHeader}>
+ {jobReadableId}
+ </Td>
+ </Tr>
+ ) : null}
+ {files.map((file) => {
+ const type = getFileType(file.name);
+ const size = convertKbToString(
+ Math.floor(
+ (file.metadata?.size ?? 0) / 1024
+ )
+ );
+ const name = (
+ <span className="block truncate font-medium">
+ {file.name}
+ </span>
+ );
+ return (
+ <Tr key={file.storagePath}>
+ <Td className={td}>
+ <div className="flex min-w-0 items-center gap-3">
+ <FileIcon type={type} />
+ <div className="min-w-0">
+ {["PDF", "Image"].includes(type) ? (
+ <FilePreview
+ bucket="private"
+ pathToFile={file.storagePath}
+ // @ts-ignore FilePreview narrows type
+ type={type}
+ >
+ {name}
+ </FilePreview>
+ ) : (
+ name
+ )}
+ <span className="text-xs text-muted-foreground tabular-nums">
+ {size}
+ </span>
+ </div>
+ </div>
+ </Td>
+ <Td className={cn(td, "w-px text-right")}>
+ <IconButton
+ aria-label={t`Download`}
+ variant="ghost"
+ icon={<LuDownload />}
+ onClick={() => onDownloadFile(file)}
+ />
+ </Td>
+ </Tr>
+ );
+ })}
+ </Fragment>
+ )
+ )}
+ </Tbody>
+ </Table>
+ </Panel>
+ </Section>
+ )}
+ </>
+ )}
+ </Await>
+ </Suspense>
+ )}
+ </>
+ );
+}
+
+// The step's acceptance rule in one line: a tolerance band, a unit, or the
+// allowed choices. Null when the step has nothing to specify.
+function stepSpecification(step: BatchStep): string | null {
+ const unit = step.unitOfMeasureCode ? ` ${step.unitOfMeasureCode}` : "";
+ if (step.minValue !== null && step.maxValue !== null) {
+ return `${step.minValue} – ${step.maxValue}${unit}`;
+ }
+ if (step.minValue !== null) return `≥ ${step.minValue}${unit}`;
+ if (step.maxValue !== null) return `≤ ${step.maxValue}${unit}`;
+ if (step.listValues?.length) return step.listValues.join(" · ");
+ return unit ? unit.trim() : null;
+}
+
+function Section({
+ title,
+ description,
+ aside,
+ divider = true,
+ children
+}: {
+ title: string;
+ description?: string;
+ aside?: ReactNode;
+ // Off for a tab's first section, which has nothing above it to divide.
+ divider?: boolean;
+ children: ReactNode;
+}) {
+ return (
+ <>
+ {divider && <Separator />}
+ <section className="flex w-full min-w-0 flex-col gap-4 p-4 lg:p-6">
+ <div className="flex flex-wrap items-end justify-between gap-x-4 gap-y-2">
+ <div className="min-w-0">
+ <Heading size="h3">{title}</Heading>
+ {description && (
+ <p className="text-sm text-muted-foreground text-pretty">
+ {description}
+ </p>
+ )}
+ </div>
+ {aside}
+ </div>
+ {children}
+ </section>
+ </>
+ );
+}
+
+// Every list on the batch view sits in the same bordered panel as the job
+// view's Steps and Parameters, with a tinted header and divided rows.
+const th = "h-10 px-4 text-xs font-medium text-muted-foreground md:px-5";
+const td = "h-auto px-4 py-3 md:px-5";
+const rows = "[&>tr]:border-b [&>tr:last-child]:border-0";
+const groupHeader =
+ "h-auto bg-muted/40 px-4 py-2 text-xs font-medium text-muted-foreground group-hover:bg-muted/40 md:px-5";
+
+function Panel({ children }: { children: ReactNode }) {
+ return (
+ <div className="w-full min-w-0 overflow-hidden rounded-lg border bg-card">
+ {children}
+ </div>
+ );
+}
+
+function IconChip({ children }: { children: ReactNode }) {
+ return (
+ <div className="flex size-9 shrink-0 items-center justify-center rounded-full border bg-muted [&>svg]:size-4">
+ {children}
+ </div>
+ );
+}
diff --git a/apps/mes/app/components/JobOperation/components/BatchRecordModal.tsx b/apps/mes/app/components/JobOperation/components/BatchRecordModal.tsx
new file mode 100644
index 0000000000..e573832aed
--- /dev/null
+++ b/apps/mes/app/components/JobOperation/components/BatchRecordModal.tsx
@@ -0,0 +1,404 @@
+import { useCarbon } from "@carbon/auth";
+import {
+ Button,
+ Checkbox,
+ cn,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDescription,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ Switch,
+ toast
+} from "@carbon/react";
+import { datetime, stripSpecialCharacters } from "@carbon/utils";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { nanoid } from "nanoid";
+import { useEffect, useState } from "react";
+import { LuCircleCheck, LuFile } from "react-icons/lu";
+import { useFetcher } from "react-router";
+import { useUser } from "~/hooks";
+import type { BatchStep } from "~/services/operations.service";
+import { usePeople } from "~/stores";
+import { path } from "~/utils/path";
+import FileDropzone from "../../FileDropzone";
+
+// How a step type is captured in the grid: a typed cell per job (values differ
+// part to part), or a tick per job with one shared payload (a task done, a
+// timestamp, one photo for every job).
+type Kind = "number" | "text" | "list" | "person" | "tick" | "file";
+
+const kindOf = (type: string): Kind =>
+ type === "Measurement"
+ ? "number"
+ : type === "Value"
+ ? "text"
+ : type === "List"
+ ? "list"
+ : type === "Person"
+ ? "person"
+ : type === "File" || type === "Inspection"
+ ? "file"
+ : "tick";
+
+type Member = BatchStep["perMember"][number];
+
+const initialValue = (kind: Kind, member: Member) => {
+ const record = member.record;
+ if (!record) return "";
+ if (kind === "number") return record.numericValue?.toString() ?? "";
+ if (kind === "person") return record.userValue ?? "";
+ return record.value ?? "";
+};
+
+// Same bare, full-cell input as the Complete Batch grid.
+const cellClass =
+ "block h-full min-h-12 w-full bg-transparent px-3 text-base outline-none transition-colors focus:ring-2 focus:ring-inset focus:ring-ring disabled:cursor-not-allowed disabled:opacity-40";
+
+// Records one work-instruction step for every job in the batch from a single
+// grid — the batch view's counterpart of the per-job RecordModal. Only rows
+// that are new or changed are sent (a re-record re-runs the step's backflush).
+export function BatchRecordModal({
+ batchId,
+ step,
+ members,
+ jobIdOf,
+ onClose
+}: {
+ batchId: string;
+ step: BatchStep;
+ // The step's per-member rows, already in job order.
+ members: Member[];
+ jobIdOf: (jobOperationId: string) => string;
+ onClose: () => void;
+}) {
+ const { t } = useLingui();
+ const { carbon } = useCarbon();
+ const { company } = useUser();
+ const [people] = usePeople();
+ const fetcher = useFetcher<{ success?: boolean }>();
+ const kind = kindOf(step.type);
+ const ticked = kind === "tick" || kind === "file";
+
+ const [values, setValues] = useState<Record<string, string>>(() =>
+ Object.fromEntries(members.map((m) => [m.stepId, initialValue(kind, m)]))
+ );
+ // Tick kinds: the jobs to record. Recorded ones stay recorded (untick them
+ // in the job's own view), so the default is "everything still open".
+ const [selected, setSelected] = useState<Set<string>>(
+ () => new Set(members.filter((m) => !m.recorded).map((m) => m.stepId))
+ );
+ const [file, setFile] = useState<File | null>(null);
+ const [passed, setPassed] = useState(true);
+ const [uploading, setUploading] = useState(false);
+
+ useEffect(() => {
+ if (fetcher.data?.success) onClose();
+ }, [fetcher.data?.success, onClose]);
+
+ const changed = members.filter((m) =>
+ ticked
+ ? selected.has(m.stepId)
+ : values[m.stepId]?.trim() &&
+ values[m.stepId] !== initialValue(kind, m) &&
+ (kind !== "number" || Number.isFinite(Number(values[m.stepId])))
+ );
+ const open = members.filter((m) => !m.recorded);
+ const busy = uploading || fetcher.state !== "idle";
+
+ const outOfRange = (value: string) => {
+ if (kind !== "number" || !value.trim()) return false;
+ const n = Number(value);
+ return (
+ (step.minValue !== null && n < step.minValue) ||
+ (step.maxValue !== null && n > step.maxValue)
+ );
+ };
+
+ const setAll = (value: string) =>
+ setValues(Object.fromEntries(members.map((m) => [m.stepId, value])));
+
+ const submit = async () => {
+ const formData = new FormData();
+ let paths: string[] = [];
+ if (kind === "file" && file && carbon) {
+ // One upload per job, under each job's own step folder — the path shape
+ // is the contract the customer-portal file route authorizes against.
+ setUploading(true);
+ const safeName = stripSpecialCharacters(file.name) || "file";
+ const uploads = await Promise.all(
+ changed.map((m) =>
+ carbon.storage
+ .from("private")
+ .upload(
+ `${company.id}/job/${m.jobOperationId}/${m.stepId}/${nanoid()}/${safeName}`,
+ file,
+ { cacheControl: `${12 * 60 * 60}`, upsert: true }
+ )
+ )
+ );
+ setUploading(false);
+ if (uploads.some((u) => u.error || !u.data?.path)) {
+ toast.error(t`Failed to upload ${file.name}`);
+ return;
+ }
+ paths = uploads.map((u) => u.data?.path ?? "");
+ }
+
+ const now = datetime.timestamp();
+ changed.forEach((m, i) => {
+ const prefix = `records[${i}]`;
+ formData.append(`${prefix}.jobOperationStepId`, m.stepId);
+ const value = values[m.stepId] ?? "";
+ if (kind === "number") formData.append(`${prefix}.numericValue`, value);
+ else if (kind === "text" || kind === "list")
+ formData.append(`${prefix}.value`, value);
+ else if (kind === "person") formData.append(`${prefix}.userValue`, value);
+ else if (kind === "file") {
+ formData.append(`${prefix}.value`, paths[i] ?? "");
+ if (step.type === "Inspection")
+ formData.append(`${prefix}.booleanValue`, String(passed));
+ } else if (step.type === "Timestamp")
+ formData.append(`${prefix}.value`, now);
+ else formData.append(`${prefix}.booleanValue`, "true");
+ });
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.batchRecord(batchId)
+ });
+ };
+
+ const cellFor = (m: Member | null) => {
+ // `null` is the "All jobs" row: it writes every job's cell.
+ const rowValues = members.map((row) => values[row.stepId] ?? "");
+ const value = m
+ ? (values[m.stepId] ?? "")
+ : rowValues.every((v) => v === rowValues[0])
+ ? (rowValues[0] ?? "")
+ : "";
+ const onChange = (v: string) =>
+ m ? setValues((prev) => ({ ...prev, [m.stepId]: v })) : setAll(v);
+
+ if (kind === "number" || kind === "text") {
+ return (
+ <input
+ type="text"
+ inputMode={kind === "number" ? "decimal" : "text"}
+ aria-label={m ? jobIdOf(m.jobOperationId) : t`All jobs`}
+ placeholder={m ? undefined : t`Same for every job`}
+ value={value}
+ onFocus={(e) => e.currentTarget.select()}
+ onChange={(e) =>
+ onChange(
+ kind === "number"
+ ? e.target.value.replace(/[^0-9.-]/g, "")
+ : e.target.value
+ )
+ }
+ className={cn(
+ cellClass,
+ kind === "number" && "text-right font-mono tabular-nums",
+ outOfRange(value) && "bg-red-500/10 text-red-600"
+ )}
+ />
+ );
+ }
+ if (kind === "list" || kind === "person") {
+ const options =
+ kind === "list"
+ ? (step.listValues ?? []).map((v) => ({ value: v, label: v }))
+ : people.map((p) => ({ value: p.id, label: p.name }));
+ return (
+ <select
+ aria-label={m ? jobIdOf(m.jobOperationId) : t`All jobs`}
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ className={cn(cellClass, !value && "text-muted-foreground")}
+ >
+ <option value="">{m ? "—" : t`Same for every job`}</option>
+ {options.map((o) => (
+ <option key={o.value} value={o.value}>
+ {o.label}
+ </option>
+ ))}
+ </select>
+ );
+ }
+ // Tick kinds
+ const recorded = m?.recorded ?? false;
+ const checked = m
+ ? recorded || selected.has(m.stepId)
+ : open.length > 0 && open.every((o) => selected.has(o.stepId));
+ return (
+ <div className="flex min-h-12 items-center justify-center">
+ <Checkbox
+ aria-label={m ? jobIdOf(m.jobOperationId) : t`All jobs`}
+ checked={checked}
+ disabled={recorded || (!m && open.length === 0)}
+ onCheckedChange={(next) =>
+ setSelected((prev) => {
+ const targets = m ? [m] : open;
+ const copy = new Set(prev);
+ for (const target of targets) {
+ if (next) copy.add(target.stepId);
+ else copy.delete(target.stepId);
+ }
+ return copy;
+ })
+ }
+ />
+ </div>
+ );
+ };
+
+ const spec =
+ step.minValue !== null && step.maxValue !== null
+ ? t`Between ${step.minValue} and ${step.maxValue} ${step.unitOfMeasureCode ?? ""}`
+ : null;
+
+ return (
+ <Modal
+ open
+ onOpenChange={(isOpen) => {
+ if (!isOpen) onClose();
+ }}
+ >
+ <ModalContent size="large">
+ <ModalHeader>
+ <ModalTitle>{step.name}</ModalTitle>
+ <ModalDescription>
+ {spec ??
+ (ticked ? (
+ <Trans>Tick the jobs this was done for.</Trans>
+ ) : (
+ <Trans>
+ Enter each job's value, or fill every job at once from the
+ first row. Empty rows are skipped.
+ </Trans>
+ ))}
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ {kind === "file" && (
+ <div className="mb-4 flex flex-col gap-3">
+ {file ? (
+ <div className="flex items-center justify-between gap-3 rounded-lg border bg-card px-4 py-3">
+ <div className="flex min-w-0 items-center gap-3">
+ <LuFile className="size-5 shrink-0 text-muted-foreground" />
+ <span className="truncate text-sm">{file.name}</span>
+ </div>
+ <Button variant="secondary" onClick={() => setFile(null)}>
+ <Trans>Remove</Trans>
+ </Button>
+ </div>
+ ) : (
+ <FileDropzone onDrop={(files) => setFile(files[0] ?? null)} />
+ )}
+ {step.type === "Inspection" && (
+ <div className="flex items-center justify-between rounded-lg border bg-card px-4 py-3">
+ <span className="text-sm font-medium">
+ <Trans>Passed inspection</Trans>
+ </span>
+ <Switch checked={passed} onCheckedChange={setPassed} />
+ </div>
+ )}
+ </div>
+ )}
+ <div className="overflow-hidden rounded-lg border bg-card">
+ <table className="w-full border-separate border-spacing-0 text-sm">
+ <thead>
+ <tr>
+ <th className="border-b border-r bg-muted/40 px-3 py-2 text-left font-medium text-muted-foreground">
+ <Trans>Job</Trans>
+ </th>
+ <th
+ className={cn(
+ "border-b bg-muted/40 px-3 py-2 font-medium text-muted-foreground",
+ ticked ? "w-24 text-center" : "text-left",
+ kind === "number" && "text-right"
+ )}
+ >
+ {ticked ? (
+ <Trans>Done</Trans>
+ ) : kind === "number" && step.unitOfMeasureCode ? (
+ step.unitOfMeasureCode
+ ) : (
+ <Trans>Value</Trans>
+ )}
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {members.length > 1 && (
+ <tr className="bg-muted/20">
+ <td className="border-b border-r px-3 py-2 align-middle font-medium text-muted-foreground">
+ <Trans>All jobs</Trans>
+ </td>
+ <td className="border-b p-0 align-middle">
+ {cellFor(null)}
+ </td>
+ </tr>
+ )}
+ {members.map((m, i) => {
+ const isLast = i === members.length - 1;
+ return (
+ <tr key={m.stepId}>
+ <td
+ className={cn(
+ "border-r px-3 py-2 align-middle",
+ !isLast && "border-b"
+ )}
+ >
+ <div className="flex items-center gap-2">
+ <span className="font-medium tabular-nums">
+ {jobIdOf(m.jobOperationId)}
+ </span>
+ {m.recorded && (
+ <LuCircleCheck
+ className="size-4 text-emerald-500"
+ aria-label={t`Recorded`}
+ />
+ )}
+ </div>
+ </td>
+ <td
+ className={cn(
+ "p-0 align-middle",
+ !isLast && "border-b"
+ )}
+ >
+ {cellFor(m)}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" size="lg" onClick={onClose}>
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button
+ size="lg"
+ rightIcon={<LuCircleCheck />}
+ isLoading={busy}
+ isDisabled={
+ busy || changed.length === 0 || (kind === "file" && !file)
+ }
+ onClick={submit}
+ >
+ {changed.length > 0 ? (
+ <Trans>Record {changed.length} jobs</Trans>
+ ) : (
+ <Trans>Record</Trans>
+ )}
+ </Button>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+}
diff --git a/apps/mes/app/components/JobOperation/components/Controls.tsx b/apps/mes/app/components/JobOperation/components/Controls.tsx
index ee710ab45b..7cb0ffd0f7 100644
--- a/apps/mes/app/components/JobOperation/components/Controls.tsx
+++ b/apps/mes/app/components/JobOperation/components/Controls.tsx
@@ -19,6 +19,8 @@ import {
LuEllipsisVertical,
LuHammer,
LuHardHat,
+ LuPanelRightClose,
+ LuPanelRightOpen,
LuTimer,
LuX
} from "react-icons/lu";
@@ -33,22 +35,48 @@ import type {
import { START_STOP_SHORTCUT } from "~/shortcuts";
import { path } from "~/utils/path";
+// The operation's action panel. One mounted instance, laid out by CSS: a
+// full-height dock column from lg (collapsible to an icon rail), a pinned
+// bottom action bar below it — never rendered twice, since it owns the
+// start/stop form and the modal triggers.
export function Controls({
children,
- className
+ className,
+ collapsed = false,
+ onCollapsedChange
}: {
children: ReactNode;
className?: string;
+ collapsed?: boolean;
+ onCollapsedChange?: (collapsed: boolean) => void;
}) {
+ const { t } = useLingui();
return (
- <div
+ <aside
+ data-collapsed={collapsed}
className={cn(
- "flex flex-col relative z-[40] lg:absolute p-2 lg:top-[calc(var(--header-height)*2-2px)] lg:right-0 w-full lg:w-[var(--controls-width)] lg:min-h-[180px] bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 lg:border-l border-y lg:rounded-bl-lg",
+ "group/dock flex min-h-0 min-w-0 items-center gap-2 border-t bg-background/95 px-3 py-2 pb-[max(0.5rem,env(safe-area-inset-bottom))] backdrop-blur supports-[backdrop-filter]:bg-background/60",
+ "lg:w-[var(--controls-width)] lg:flex-col lg:items-stretch lg:overflow-y-auto lg:overflow-x-hidden lg:border-t-0 lg:border-l lg:p-2 lg:transition-[width] lg:duration-200 lg:data-[collapsed=true]:w-[76px]",
className
)}
>
{children}
- </div>
+ {onCollapsedChange && (
+ <button
+ type="button"
+ onClick={() => onCollapsedChange(!collapsed)}
+ aria-label={collapsed ? t`Expand panel` : t`Collapse panel`}
+ aria-expanded={!collapsed}
+ className="mt-auto hidden h-10 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring lg:flex"
+ >
+ {collapsed ? (
+ <LuPanelRightOpen className="size-4" />
+ ) : (
+ <LuPanelRightClose className="size-4" />
+ )}
+ </button>
+ )}
+ </aside>
);
}
@@ -63,7 +91,7 @@ export function Times({
<TooltipProvider>
<div
className={cn(
- "flex flex-col lg:absolute p-2 bottom-2 lg:left-4 lg:right-[calc(var(--controls-gutter,0px)+1rem)] w-full lg:w-auto z-50 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 border-b lg:border lg:rounded-lg",
+ "min-w-0 border-t bg-background/95 px-4 py-2.5 backdrop-blur supports-[backdrop-filter]:bg-background/60 lg:px-6",
className
)}
>
@@ -79,7 +107,7 @@ export const ButtonWithTooltip = forwardRef<
>(({ tooltip, children, ...props }, ref) => {
return (
<Tooltip>
- <TooltipTrigger>
+ <TooltipTrigger asChild>
<button ref={ref} {...props}>
{children}
</button>
@@ -108,7 +136,7 @@ export function IconButtonWithTooltip({
tooltip={tooltip}
disabled={disabled}
className={cn(
- "size-16 text-xl lg:text-lg lg:size-[8dvh] flex flex-row items-center gap-2 justify-center bg-accent rounded-full shadow-lg hover:cursor-pointer hover:shadow-xl hover:accent hover:scale-105 transition-all disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-30 text-accent-foreground group-hover:text-accent-foreground/80",
+ "size-12 shrink-0 text-lg lg:size-[8dvh] lg:group-data-[collapsed=true]/dock:size-12 flex flex-row items-center gap-2 justify-center bg-accent rounded-full shadow-lg hover:cursor-pointer hover:shadow-xl hover:accent hover:scale-105 transition-all disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-30 text-accent-foreground group-hover:text-accent-foreground/80",
variant === "success" &&
"bg-emerald-500 !text-white hover:bg-emerald-600 hover:text-white",
variant === "destructive" &&
@@ -158,22 +186,22 @@ export function WorkTypeToggle({
onValueChange={onChange}
disabled={!!value && count <= 1}
className={cn(
- "grid w-full",
+ "grid w-full lg:group-data-[collapsed=true]/dock:grid-cols-1",
count <= 1 && "grid-cols-1",
- count === 2 && "grid-cols-2 py-2",
- count === 3 && "grid-cols-3 py-2",
+ count === 2 && "grid-cols-2 lg:py-2",
+ count === 3 && "grid-cols-3 lg:py-2",
className
)}
>
{operation.setupDuration > 0 && (
<ToggleGroupItem
- className="flex flex-col items-center relative justify-center text-center h-14 w-full"
+ className="flex flex-col items-center relative justify-center text-center h-12 lg:h-14 w-full"
value="Setup"
size="lg"
aria-label="Toggle setup"
>
<LuTimer className="size-6 pt-1" />
- <span className="text-xxs">
+ <span className="text-xxs lg:group-data-[collapsed=true]/dock:sr-only">
<Trans>Setup</Trans>
</span>
{active.setup && (
@@ -183,13 +211,13 @@ export function WorkTypeToggle({
)}
{operation.laborDuration > 0 && (
<ToggleGroupItem
- className="flex flex-col items-center relative justify-center text-center h-14 w-full"
+ className="flex flex-col items-center relative justify-center text-center h-12 lg:h-14 w-full"
value="Labor"
size="lg"
aria-label="Toggle labor"
>
<LuHardHat className="size-6 pt-1" />
- <span className="text-xxs">
+ <span className="text-xxs lg:group-data-[collapsed=true]/dock:sr-only">
<Trans>Labor</Trans>
</span>
{active.labor && (
@@ -199,13 +227,13 @@ export function WorkTypeToggle({
)}
{operation.machineDuration > 0 && (
<ToggleGroupItem
- className="flex flex-col items-center relative justify-center text-center h-14 w-full"
+ className="flex flex-col items-center relative justify-center text-center h-12 lg:h-14 w-full"
value="Machine"
size="lg"
aria-label="Toggle machine"
>
<LuHammer className="size-6 pt-1" />
- <span className="text-xxs">
+ <span className="text-xxs lg:group-data-[collapsed=true]/dock:sr-only">
<Trans>Machine</Trans>
</span>
{active.machine && (
@@ -358,7 +386,10 @@ export const PauseButton = forwardRef<
ref={ref}
{...props}
tooltip={t`Pause`}
- className="group size-24 tall:size-32 flex flex-row items-center gap-2 justify-center bg-red-500 rounded-full shadow-lg hover:cursor-pointer hover:drop-shadow-xl hover:bg-red-600 hover:scale-105 transition-all text-accent disabled:bg-muted disabled:text-muted-foreground/80 text-4xl border-b-4 border-red-700 active:border-b-0 active:translate-y-1 disabled:bg-gray-500 disabled:hover:bg-gray-600 disabled:border-gray-700 disabled:text-white"
+ className={cn(
+ "group size-14 text-2xl lg:size-24 lg:text-4xl lg:tall:size-32 lg:group-data-[collapsed=true]/dock:!size-14 lg:group-data-[collapsed=true]/dock:!text-2xl shrink-0 flex flex-row items-center gap-2 justify-center bg-red-500 rounded-full shadow-lg hover:cursor-pointer hover:drop-shadow-xl hover:bg-red-600 hover:scale-105 transition-all text-accent disabled:bg-muted disabled:text-muted-foreground/80 border-b-4 border-red-700 active:border-b-0 active:translate-y-1 disabled:bg-gray-500 disabled:hover:bg-gray-600 disabled:border-gray-700 disabled:text-white",
+ className
+ )}
>
<FaPause className="group-hover:scale-110" />
</ButtonWithTooltip>
@@ -376,7 +407,10 @@ export const PlayButton = forwardRef<
ref={ref}
{...props}
tooltip={t`Start`}
- className="group size-24 tall:size-32 flex flex-row items-center gap-2 justify-center bg-emerald-500 rounded-full shadow-lg hover:cursor-pointer hover:drop-shadow-xl hover:bg-emerald-600 hover:scale-105 transition-all text-accent disabled:bg-muted disabled:text-muted-foreground/80 text-4xl border-b-4 border-emerald-700 active:border-b-0 active:translate-y-1 disabled:bg-gray-500 disabled:hover:bg-gray-600 disabled:border-gray-700 disabled:text-white"
+ className={cn(
+ "group size-14 text-2xl lg:size-24 lg:text-4xl lg:tall:size-32 lg:group-data-[collapsed=true]/dock:!size-14 lg:group-data-[collapsed=true]/dock:!text-2xl shrink-0 flex flex-row items-center gap-2 justify-center bg-emerald-500 rounded-full shadow-lg hover:cursor-pointer hover:drop-shadow-xl hover:bg-emerald-600 hover:scale-105 transition-all text-accent disabled:bg-muted disabled:text-muted-foreground/80 border-b-4 border-emerald-700 active:border-b-0 active:translate-y-1 disabled:bg-gray-500 disabled:hover:bg-gray-600 disabled:border-gray-700 disabled:text-white",
+ className
+ )}
>
<FaPlay className="group-hover:scale-110" />
</ButtonWithTooltip>
diff --git a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
index 44b6ba2347..65f1605343 100644
--- a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
@@ -88,6 +88,8 @@ export function IssueMaterialModal({
locationId,
workCenterId,
material,
+ batchId,
+ batchRemainingQuantity,
parentId,
parentIdIsSerialized,
jobOperationStepId,
@@ -117,6 +119,15 @@ export function IssueMaterialModal({
locationId?: string;
workCenterId?: string;
material?: JobMaterial;
+ // Batch mode: the pick covers every member of this operation batch. The
+ // edge fn splits the picked lots pro-rata by remaining requirement and
+ // records per-member consumption, so no parent entity is sent.
+ batchId?: string;
+ // Batch mode: the WHOLE batch's outstanding requirement for this item. The
+ // default pick must be this, not the member's share — the pick is split
+ // pro-rata across every member, so defaulting to one member's quantity
+ // under-serves all of them (4,000 of a 6,500 batch became 2461/1538).
+ batchRemainingQuantity?: number;
parentId?: string;
parentIdIsSerialized?: boolean;
// Assembly view only: the step + 1-based unit the operator is on, stamped onto the
@@ -327,6 +338,12 @@ export function IssueMaterialModal({
// total for the operation.
const initialQuantity = useMemo(() => {
if (!material) return 1;
+ // Batch mode: one pick covers every member, so the default is the batch's
+ // outstanding requirement — the member's own share would be split again
+ // across all members and satisfy none of them.
+ if (batchId && batchRemainingQuantity !== undefined) {
+ return Math.max(1, batchRemainingQuantity);
+ }
const perUnit = material.quantity ?? material.estimatedQuantity ?? 1;
if (parentIdIsSerialized) {
return Math.max(1, perUnit - (material.quantityIssued ?? 0));
@@ -336,7 +353,13 @@ export function IssueMaterialModal({
}
const total = material.estimatedQuantity ?? material.quantity ?? 1;
return Math.max(1, total - (material.quantityIssued ?? 0));
- }, [material, parentIdIsSerialized, issuePerUnit]);
+ }, [
+ material,
+ parentIdIsSerialized,
+ issuePerUnit,
+ batchId,
+ batchRemainingQuantity
+ ]);
// Serial numbers selection state
const [selectedSerialNumbers, setSelectedSerialNumbers] = useState<
@@ -950,7 +973,7 @@ export function IssueMaterialModal({
]);
const handleSubmitBatch = useCallback(() => {
- if (!parentId) {
+ if (!batchId && !parentId) {
toast.error("Parent tracking ID is required for batch tracked items.");
return;
}
@@ -987,28 +1010,38 @@ export function IssueMaterialModal({
...(jobOperationStepId ? { jobOperationStepId } : {}),
...(unitNumber !== undefined ? { unitNumber } : {})
};
- const payload = material?.id
+ const payload = batchId
? {
- materialId: material.id,
- parentTrackedEntityId: parentId,
+ batchId,
+ itemId: material?.itemId ?? selectedItemId,
children: selectedBatchNumbers.map((bn) => ({
trackedEntityId: bn.id,
quantity: bn.quantity
})),
- ...contextFields,
...overrideFields
}
- : {
- jobOperationId: operationId,
- itemId: selectedItemId,
- parentTrackedEntityId: parentId,
- children: selectedBatchNumbers.map((bn) => ({
- trackedEntityId: bn.id,
- quantity: bn.quantity
- })),
- ...contextFields,
- ...overrideFields
- };
+ : material?.id
+ ? {
+ materialId: material.id,
+ parentTrackedEntityId: parentId,
+ children: selectedBatchNumbers.map((bn) => ({
+ trackedEntityId: bn.id,
+ quantity: bn.quantity
+ })),
+ ...contextFields,
+ ...overrideFields
+ }
+ : {
+ jobOperationId: operationId,
+ itemId: selectedItemId,
+ parentTrackedEntityId: parentId,
+ children: selectedBatchNumbers.map((bn) => ({
+ trackedEntityId: bn.id,
+ quantity: bn.quantity
+ })),
+ ...contextFields,
+ ...overrideFields
+ };
fetcher.submit(JSON.stringify(payload), {
method: "post",
@@ -1019,8 +1052,10 @@ export function IssueMaterialModal({
}, [
selectedBatchNumbers,
validateBatchNumber,
+ batchId,
parentId,
material?.id,
+ material?.itemId,
operationId,
selectedItemId,
fetcher,
diff --git a/apps/mes/app/components/JobOperation/components/Step.tsx b/apps/mes/app/components/JobOperation/components/Step.tsx
index ed65a98029..9174b98c5d 100644
--- a/apps/mes/app/components/JobOperation/components/Step.tsx
+++ b/apps/mes/app/components/JobOperation/components/Step.tsx
@@ -78,7 +78,7 @@ type SlideAnnotation = {
// JSON.stringify({}) === "{}" (and some legacy rows carry it as a tiptap doc
// whose only text is literally "{}"). Treat an empty object, empty doc, or
// "{}"-only text as "no description" so we render nothing instead of a bare "{}".
-function hasStepDescription(
+export function hasStepDescription(
description: JobOperationStep["description"]
): boolean {
if (!description) return false;
@@ -115,33 +115,10 @@ export function StepsListItem({
step;
const hasDescription = hasStepDescription(description);
- const mentionIds = hasDescription
- ? parseMentionsFromDocument(description as JSONContent)
- : [];
const disclosure = useDisclosure({
defaultIsOpen: hasDescription
});
- // Reference images ("slides") attached to this step in the Bill of Process. A slide
- // is image XOR model; only image slides (imagePath) render here — model slides need a
- // modelUpload join the standard-view loader doesn't fetch, so they're skipped.
- const imageSlides = (step.jobOperationStepSlide ?? [])
- .filter((slide) => !!slide.imagePath)
- .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))
- .map((slide) => ({
- id: slide.id,
- url: getPrivateUrl(slide.imagePath as string),
- caption: slide.caption,
- // Slides copied from the method (get-method) can persist annotations as a
- // non-array JSON value ({}), so normalize before the viewer calls .map().
- annotations: Array.isArray(slide.annotations)
- ? (slide.annotations as SlideAnnotation[])
- : []
- }));
- const [viewerIndex, setViewerIndex] = useState<number | null>(null);
- const activeSlide =
- viewerIndex !== null ? (imageSlides[viewerIndex] ?? null) : null;
-
if (!operationId) return null;
const record = step.jobOperationStepRecord.find(
(r) => r.index === activeStep
@@ -282,6 +259,58 @@ export function StepsListItem({
)}
</div>
</div>
+ <StepMedia
+ description={description}
+ slides={step.jobOperationStepSlide ?? []}
+ showDescription={disclosure.isOpen && hasDescription}
+ />
+ </div>
+ );
+}
+
+type StepSlide = {
+ id: string;
+ imagePath: string | null;
+ caption: string | null;
+ sortOrder: number | null;
+ annotations: unknown;
+};
+
+// A step's reference material: its image slides from the Bill of Process (a
+// slide is image XOR model; model slides need a modelUpload join these loaders
+// don't fetch, so only image slides render), the rich-text description, and
+// the parts it @-mentions. Shared by the job's step list and the batch view.
+export function StepMedia({
+ description,
+ slides,
+ showDescription
+}: {
+ description: JobOperationStep["description"];
+ slides: StepSlide[];
+ showDescription: boolean;
+}) {
+ const imageSlides = slides
+ .filter((slide) => !!slide.imagePath)
+ .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))
+ .map((slide) => ({
+ id: slide.id,
+ url: getPrivateUrl(slide.imagePath as string),
+ caption: slide.caption,
+ // Slides copied from the method (get-method) can persist annotations as a
+ // non-array JSON value ({}), so normalize before the viewer calls .map().
+ annotations: Array.isArray(slide.annotations)
+ ? (slide.annotations as SlideAnnotation[])
+ : []
+ }));
+ const [viewerIndex, setViewerIndex] = useState<number | null>(null);
+ const activeSlide =
+ viewerIndex !== null ? (imageSlides[viewerIndex] ?? null) : null;
+ const mentionIds = hasStepDescription(description)
+ ? parseMentionsFromDocument(description as JSONContent)
+ : [];
+
+ return (
+ <>
{imageSlides.length > 0 && (
<div className="mt-4 flex flex-wrap gap-2">
{imageSlides.map((slide, i) => (
@@ -306,7 +335,7 @@ export function StepsListItem({
))}
</div>
)}
- {disclosure.isOpen && hasDescription && (
+ {showDescription && (
<div
className="my-4 text-sm prose prose-sm dark:prose-invert"
dangerouslySetInnerHTML={{
@@ -322,7 +351,7 @@ export function StepsListItem({
annotations={activeSlide?.annotations ?? []}
onClose={() => setViewerIndex(null)}
/>
- </div>
+ </>
);
}
diff --git a/apps/mes/app/components/JobOperation/hooks/useFiles.tsx b/apps/mes/app/components/JobOperation/hooks/useFiles.tsx
index 4e656aa7cc..6d97292a88 100644
--- a/apps/mes/app/components/JobOperation/hooks/useFiles.tsx
+++ b/apps/mes/app/components/JobOperation/hooks/useFiles.tsx
@@ -13,6 +13,7 @@ export function useFiles(job: Job) {
const getFilePath = useCallback(
(file: StorageItem) => {
+ if (file.storagePath) return file.storagePath;
const companyId = user.company.id;
const { bucket } = file;
let id: string | null = "";
diff --git a/apps/mes/app/components/JobOperation/hooks/useOperation.tsx b/apps/mes/app/components/JobOperation/hooks/useOperation.tsx
index cc40bf8da9..55e6f8db59 100644
--- a/apps/mes/app/components/JobOperation/hooks/useOperation.tsx
+++ b/apps/mes/app/components/JobOperation/hooks/useOperation.tsx
@@ -13,8 +13,8 @@ import {
} from "@internationalized/date";
import type { RealtimeChannel } from "@supabase/supabase-js";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { useParams, useRevalidator } from "react-router";
-import { useUrlParams, useUser } from "~/hooks";
+import { useParams } from "react-router";
+import { useRealtimeRevalidator, useUrlParams, useUser } from "~/hooks";
import { isSerialEntityIncompleteForOperation } from "~/services/operations.service";
import { shouldAdvanceToNextSerialUnit } from "~/services/serial-advancement";
import type {
@@ -67,7 +67,7 @@ export function useOperation({
const { carbon, accessToken } = useCarbon();
const user = useUser();
- const revalidator = useRevalidator();
+ const revalidate = useRealtimeRevalidator();
// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
const channelRef = useRef<RealtimeChannel | null>(null);
@@ -132,7 +132,7 @@ export function useOperation({
},
(payload) => {
if (payload.eventType === "UPDATE") {
- revalidator.revalidate();
+ revalidate();
}
}
)
diff --git a/apps/mes/app/components/Suggestion.tsx b/apps/mes/app/components/Suggestion.tsx
index 9ab7e0854f..329464a602 100644
--- a/apps/mes/app/components/Suggestion.tsx
+++ b/apps/mes/app/components/Suggestion.tsx
@@ -23,11 +23,10 @@ import {
VStack
} from "@carbon/react";
import data from "@emoji-mart/data";
-import Picker from "@emoji-mart/react";
import { Trans, useLingui } from "@lingui/react/macro";
import { nanoid } from "nanoid";
import type { ChangeEvent } from "react";
-import { useEffect, useRef, useState } from "react";
+import { lazy, Suspense, useEffect, useRef, useState } from "react";
import { LuImage, LuMailbox } from "react-icons/lu";
import { useFetcher, useLocation } from "react-router";
import { useUser } from "~/hooks";
@@ -35,6 +34,11 @@ import type { action } from "~/routes/x+/suggestion";
import { suggestionValidator } from "~/services/models";
import { path } from "~/utils/path";
+// Lazy, not a static import: @emoji-mart/react is CommonJS, so under SSR its
+// default import is `{ default: Picker }` and dev React warns "type is
+// invalid" the moment the element is created, even in a closed popover.
+const Picker = lazy(() => import("@emoji-mart/react"));
+
const log = getLogger("mes");
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB in bytes
@@ -214,15 +218,17 @@ const Suggestion = () => {
align="end"
sideOffset={8}
>
- <Picker
- data={data}
- onEmojiSelect={onEmojiSelect}
- theme={pickerTheme}
- previewPosition="none"
- skinTonePosition="none"
- navPosition="bottom"
- perLine={8}
- />
+ <Suspense>
+ <Picker
+ data={data}
+ onEmojiSelect={onEmojiSelect}
+ theme={pickerTheme}
+ previewPosition="none"
+ skinTonePosition="none"
+ navPosition="bottom"
+ perLine={8}
+ />
+ </Suspense>
</PopoverContent>
</Popover>
</HStack>
diff --git a/apps/mes/app/hooks/index.ts b/apps/mes/app/hooks/index.ts
index dcaeeeaf0e..cb9386c39a 100644
--- a/apps/mes/app/hooks/index.ts
+++ b/apps/mes/app/hooks/index.ts
@@ -9,7 +9,7 @@ import { useCompanyTimeZone, useLocationTimeZone } from "./useCompanyTimeZone";
import { useDateFormatter } from "./useDateFormatter";
import { useIdle } from "./useIdle";
import { useImageUpload } from "./useImageUpload";
-import { useRealtime } from "./useRealtime";
+import { useRealtime, useRealtimeRevalidator } from "./useRealtime";
import { useUser } from "./useUser";
export {
@@ -22,6 +22,7 @@ export {
useOptimisticLocation,
usePrinting,
useRealtime,
+ useRealtimeRevalidator,
useRouteData,
useUrlParams,
useUser
diff --git a/apps/mes/app/hooks/useRealtime.tsx b/apps/mes/app/hooks/useRealtime.tsx
index 8b65740d92..d9d3aab190 100644
--- a/apps/mes/app/hooks/useRealtime.tsx
+++ b/apps/mes/app/hooks/useRealtime.tsx
@@ -1,10 +1,29 @@
import { useRealtimeChannel } from "@carbon/react";
-import { useRevalidator } from "react-router";
+import { useCallback, useRef } from "react";
+import { useFetchers, useRevalidator } from "react-router";
import { useUser } from "./useUser";
+// Revalidate for a realtime change — except while a fetcher on this page is
+// submitting. A submission's own writes echo back over realtime mid-action,
+// and React Router drops a fetcher's redirect when a newer navigation started
+// after the submit (the page then sits on stale data, or a loader gate
+// flashes an error for work that just succeeded). Nothing is lost by skipping:
+// the router revalidates after every action, the same reason `revalidate()`
+// already no-ops during a navigation submission.
+export function useRealtimeRevalidator() {
+ const revalidator = useRevalidator();
+ const fetchers = useFetchers();
+ const submitting = useRef(false);
+ submitting.current = fetchers.some((f) => f.state === "submitting");
+
+ return useCallback(() => {
+ if (!submitting.current) revalidator.revalidate();
+ }, [revalidator]);
+}
+
export function useRealtime(table: string, filter?: string) {
const { company } = useUser();
- const revalidator = useRevalidator();
+ const revalidate = useRealtimeRevalidator();
const channel = useRealtimeChannel({
topic: `postgres_changes:${table}`,
@@ -19,7 +38,7 @@ export function useRealtime(table: string, filter?: string) {
filter: filter ?? `companyId=eq.${company.id}`
},
() => {
- revalidator.revalidate();
+ revalidate();
}
);
}
diff --git a/apps/mes/app/middleware/user.ts b/apps/mes/app/middleware/user.ts
index 977c7f2a84..e221ee1741 100644
--- a/apps/mes/app/middleware/user.ts
+++ b/apps/mes/app/middleware/user.ts
@@ -35,7 +35,15 @@ export const userMiddleware: MiddlewareFunction = async ({
// Redirect back to the originally-requested URL (not the root) so deep
// links survive the one-time location-cookie bootstrap. The re-run finds
// the cookie set, so `updated` is false the second time through.
- return redirect(request.url, {
+ //
+ // RELATIVE, never `request.url`: behind a reverse proxy (portless locally,
+ // any load balancer in production) `request.url` is the server's internal
+ // origin (`http://127.0.0.1:<port>`). An absolute Location sent the
+ // browser there on the first visit, off the public domain its session
+ // cookie is scoped to — landing on a login page at 127.0.0.1. A relative
+ // Location resolves against whatever origin the browser is actually on.
+ const { pathname, search } = new URL(request.url);
+ return redirect(`${pathname}${search}`, {
headers: {
"Set-Cookie": setLocation(companyId, location)
}
diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsx
index ad86243b06..3a627a312e 100644
--- a/apps/mes/app/root.tsx
+++ b/apps/mes/app/root.tsx
@@ -46,6 +46,7 @@ import {
ScrollRestoration,
useLoaderData
} from "react-router";
+import SonnerStyle from "sonner/dist/styles.css?url";
import { preloadCatalog, useCatalog } from "~/services/lingui";
import { getMode, setMode } from "~/services/mode.server";
import Background from "~/styles/background.css?url";
@@ -65,6 +66,7 @@ export const clientMiddleware = [flashClientMiddleware];
export const links: Route.LinksFunction = () => [
{ rel: "stylesheet", href: Tailwind },
+ { rel: "stylesheet", href: SonnerStyle },
{ rel: "stylesheet", href: Background },
{ rel: "stylesheet", href: NProgress },
...faviconLinks
diff --git a/apps/mes/app/routes/_public+/login.tsx b/apps/mes/app/routes/_public+/login.tsx
index 110ee33fdf..60a752641d 100644
--- a/apps/mes/app/routes/_public+/login.tsx
+++ b/apps/mes/app/routes/_public+/login.tsx
@@ -4,6 +4,7 @@ import {
CONTROLLED_ENVIRONMENT,
carbonClient,
error,
+ getMESUrl,
isAuthProviderEnabled,
magicLinkValidator,
RATE_LIMIT
@@ -12,6 +13,7 @@ import {
getMagicLinkErrorMessage,
logAuthEvent,
sendMagicLink,
+ signInWithBypassEmail,
turnstileSiteKey,
verifyAuthSession,
verifyLoginCaptcha
@@ -20,7 +22,8 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import {
clearAuthCookies,
flash,
- getAuthSession
+ getAuthSession,
+ setAuthSession
} from "@carbon/auth/session.server";
import { getUserByEmail } from "@carbon/auth/users.server";
import { isSsoEnabled, isSsoRequiredForEmail } from "@carbon/ee/sso.server";
@@ -155,6 +158,26 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
+ const user = await getUserByEmail(email);
+
+ const devBypassEmail = process.env.DEV_BYPASS_EMAIL;
+ if (
+ devBypassEmail &&
+ email.toLowerCase() === devBypassEmail.toLowerCase() &&
+ user.data?.active
+ ) {
+ const authSession = await signInWithBypassEmail(email);
+ if (authSession) {
+ // Genuine completed login — clear any accumulated lockout state.
+ await lockout.reset(email);
+ logAuthEvent("login_success", { actor: email, ip, method: "bypass" });
+ const sessionCookie = await setAuthSession(request, { authSession });
+ return redirect(path.to.authenticatedRoot, {
+ headers: [["Set-Cookie", sessionCookie]]
+ });
+ }
+ }
+
const attempt = await lockout.recordFailure(email);
if (attempt.locked) {
logAuthEvent("login_locked", {
@@ -185,10 +208,8 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- const user = await getUserByEmail(email);
-
if (user.data && user.data.active) {
- const magicLink = await sendMagicLink(email, turnstileToken);
+ const magicLink = await sendMagicLink(email, turnstileToken, getMESUrl());
if (magicLink.error) {
logAuthEvent("login_failed", {
diff --git a/apps/mes/app/routes/x+/batch.$batchId.complete.tsx b/apps/mes/app/routes/x+/batch.$batchId.complete.tsx
index ada5dd9de4..0b695b3b6b 100644
--- a/apps/mes/app/routes/x+/batch.$batchId.complete.tsx
+++ b/apps/mes/app/routes/x+/batch.$batchId.complete.tsx
@@ -4,9 +4,41 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
-import { data, redirect } from "react-router";
+import { data } from "react-router";
import { completeJobOperationBatchValidator } from "~/services/models";
-import { path } from "~/utils/path";
+import {
+ getJobOperationBatch,
+ type JobOperationBatch
+} from "~/services/operations.service";
+
+// A batch planned with a combined output merges every member's produced lot
+// into the planned lot number once completion lands. Parent ids are derived
+// SERVER-SIDE from membership: this route invokes `issue` with the SERVICE
+// ROLE, so the edge fn's `inventory` check validates the service role rather
+// than the operator. A second call finds nothing (parents are Consumed), so a
+// resume never double-merges.
+async function getPlannedMergeLots(
+ serviceRole: Awaited<ReturnType<typeof getCarbonServiceRole>>,
+ batch: JobOperationBatch,
+ companyId: string
+): Promise<string[] | null> {
+ if (!batch.mergeOutput || batch.status !== "Completed") return [];
+ const entityIds = (batch.operations ?? [])
+ .map((operation) => operation.trackedEntityId)
+ .filter(Boolean) as string[];
+ if (entityIds.length < 2) return [];
+ const outputs = await serviceRole
+ .from("trackedEntity")
+ .select("id")
+ .in("id", entityIds)
+ .eq("companyId", companyId)
+ .eq("status", "Available")
+ .gt("quantity", 0);
+ // null = could not tell, which the caller reports instead of skipping.
+ if (outputs.error) return null;
+ const ids = (outputs.data ?? []).map((lot) => lot.id);
+ return ids.length >= 2 ? ids : [];
+}
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
@@ -16,14 +48,30 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { batchId } = params;
if (!batchId) throw new Error("Batch ID is required");
+ const formData = await request.formData();
+
const validation = await validator(
completeJobOperationBatchValidator
- ).validate(await request.formData());
+ ).validate(formData);
if (validation.error) {
return validationError(validation.error);
}
const serviceRole = await getCarbonServiceRole();
+ const planned = await getJobOperationBatch(serviceRole, batchId, companyId);
+ if (planned.error || !planned.data) {
+ return data(
+ {},
+ await flash(request, error(planned.error, "Batch not found"))
+ );
+ }
+ // Lot identity was planned at creation: a merged batch stamps its one lot
+ // number on every member's output; otherwise each member keeps its own
+ // planned number (null leaves the entity's readableId untouched, and the
+ // edge fn refuses an output with no number at all).
+ const plannedLotNumber = planned.data.mergeOutput
+ ? planned.data.outputLotNumber
+ : null;
// The edge function owns the whole completion: slice events + record quantities
// (phase 1, one txn), then issue each member's BOM + flip members Done + post GL
@@ -45,6 +93,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
jobOperationId: m.jobOperationId,
quantity: excluded ? 0 : (m.quantity ?? 0),
scrapQuantity: excluded ? 0 : (m.scrapQuantity ?? 0),
+ trackedEntityId: m.trackedEntityId || null,
+ batchNumber: plannedLotNumber,
excluded
};
}),
@@ -53,7 +103,22 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
});
- if (completeResult.error || completeResult.data?.error) {
+ // "Already completed" is not a failure: a duplicate submit (double click,
+ // a retry after a slow first attempt) means the work landed. Fall through to
+ // the merge step, which is itself idempotent — the parents are Consumed by
+ // then, so it finds no groups — and report success. Reporting this as
+ // an error told the operator the completion failed when it had just
+ // succeeded, with the lots and the merged lot already written.
+ const completionErrorMessage =
+ completeResult.data?.error ??
+ (completeResult.error ? String(completeResult.error.message ?? "") : "");
+ const alreadyCompleted = /already been completed|already completed/i.test(
+ completionErrorMessage
+ );
+ if (
+ (completeResult.error || completeResult.data?.error) &&
+ !alreadyCompleted
+ ) {
return data(
{},
await flash(
@@ -66,8 +131,64 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- return redirect(
- path.to.operations,
- await flash(request, success("Batch completed"))
+ const completed = await getJobOperationBatch(serviceRole, batchId, companyId);
+ const mergeLots =
+ completed.data && !completed.error
+ ? await getPlannedMergeLots(serviceRole, completed.data, companyId)
+ : null;
+ // A planned merge whose lots could not be read is reported, never skipped.
+ if (mergeLots === null && planned.data.mergeOutput) {
+ return data(
+ { completed: true },
+ await flash(
+ request,
+ error(
+ completed.error,
+ `Batch completed, but combining lots into ${plannedLotNumber} failed — use "Merge output lots" on the batch`
+ )
+ )
+ );
+ }
+ if (mergeLots && mergeLots.length >= 2) {
+ const mergeResult = await serviceRole.functions.invoke<{ error?: string }>(
+ "issue",
+ {
+ body: {
+ type: "mergeTrackedEntities",
+ trackedEntityIds: mergeLots,
+ readableId: plannedLotNumber,
+ companyId,
+ userId
+ }
+ }
+ );
+ if (mergeResult.error || mergeResult.data?.error) {
+ return data(
+ { completed: true },
+ await flash(
+ request,
+ error(
+ mergeResult.error ?? mergeResult.data?.error,
+ `Batch completed, but combining lots into ${plannedLotNumber} failed — use "Merge output lots" on the batch`
+ )
+ )
+ );
+ }
+ }
+
+ // Not a redirect: the completion's own writes fire the page's realtime
+ // revalidation mid-action, and React Router drops a fetcher's redirect when
+ // a newer navigation started after the submit. JobOperation navigates on
+ // `completed` instead.
+ return data(
+ { completed: true },
+ await flash(
+ request,
+ success(
+ mergeLots && mergeLots.length >= 2
+ ? `Batch completed — ${mergeLots.length} lots combined into ${plannedLotNumber}`
+ : "Batch completed"
+ )
+ )
);
}
diff --git a/apps/mes/app/routes/x+/batch.$batchId.record.tsx b/apps/mes/app/routes/x+/batch.$batchId.record.tsx
new file mode 100644
index 0000000000..1add32669e
--- /dev/null
+++ b/apps/mes/app/routes/x+/batch.$batchId.record.tsx
@@ -0,0 +1,72 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { batchStepRecordsValidator } from "~/services/models";
+import {
+ backflushUntrackedMaterialsOnStepRecord,
+ insertBatchStepRecords
+} from "~/services/operations.service";
+
+const log = getLogger("mes");
+
+// Records one work-instruction step for several batch members at once — the
+// batch view's counterpart of x+/record, with the same per-step backflush.
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId, userId } = await requirePermissions(request, {});
+ const { batchId } = params;
+ if (!batchId) throw new Error("Batch ID is required");
+
+ const validation = await validator(batchStepRecordsValidator).validate(
+ await request.formData()
+ );
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const serviceRole = await getCarbonServiceRole();
+ const inserted = await insertBatchStepRecords(serviceRole, {
+ batchId,
+ companyId,
+ createdBy: userId,
+ records: validation.data.records
+ });
+ if (inserted.error) {
+ return data(
+ {},
+ await flash(request, error(inserted.error, "Failed to record step"))
+ );
+ }
+
+ // One backflush per recorded step, as if each job had recorded its own.
+ const backflushes = await Promise.all(
+ validation.data.records.map((record) =>
+ backflushUntrackedMaterialsOnStepRecord(serviceRole, {
+ jobOperationStepId: record.jobOperationStepId,
+ companyId,
+ userId
+ })
+ )
+ );
+ for (const [i, backflush] of backflushes.entries()) {
+ if (backflush.error) {
+ log.error("Backflush on batch step record failed", {
+ error: backflush.error,
+ jobOperationStepId: validation.data.records[i]?.jobOperationStepId
+ });
+ }
+ }
+
+ return data(
+ { success: true },
+ await flash(
+ request,
+ success(`Recorded for ${validation.data.records.length} jobs`)
+ )
+ );
+}
diff --git a/apps/mes/app/routes/x+/issue-tracked-entity.tsx b/apps/mes/app/routes/x+/issue-tracked-entity.tsx
index b62d0a081e..dc73434ae1 100644
--- a/apps/mes/app/routes/x+/issue-tracked-entity.tsx
+++ b/apps/mes/app/routes/x+/issue-tracked-entity.tsx
@@ -26,6 +26,7 @@ export async function action({ request }: ActionFunctionArgs) {
materialId,
jobOperationId,
itemId,
+ batchId,
parentTrackedEntityId,
children,
jobOperationStepId,
@@ -34,22 +35,43 @@ export async function action({ request }: ActionFunctionArgs) {
overrideReason
} = validation.data;
+ if (batchId ? !itemId : !parentTrackedEntityId) {
+ return data(
+ { success: false, message: "Failed to validate payload" },
+ { status: 400 }
+ );
+ }
+
const serviceRole = await getCarbonServiceRole();
+ // Batch mode: one pick for the whole operation batch. The edge fn splits the
+ // picked lots pro-rata by each member's remaining requirement and records
+ // per-member consumption, so costing and genealogy stay per job.
const issue = await serviceRole.functions.invoke("issue", {
- body: {
- type: "trackedEntitiesToOperation",
- materialId,
- jobOperationId,
- itemId,
- parentTrackedEntityId,
- children,
- jobOperationStepId,
- unitNumber,
- overrideExpired,
- overrideReason,
- companyId,
- userId
- }
+ body: batchId
+ ? {
+ type: "trackedEntitiesToBatch",
+ batchId,
+ itemId,
+ children,
+ overrideExpired,
+ overrideReason,
+ companyId,
+ userId
+ }
+ : {
+ type: "trackedEntitiesToOperation",
+ materialId,
+ jobOperationId,
+ itemId,
+ parentTrackedEntityId,
+ children,
+ jobOperationStepId,
+ unitNumber,
+ overrideExpired,
+ overrideReason,
+ companyId,
+ userId
+ }
});
if (issue.error) {
diff --git a/apps/mes/app/routes/x+/operation.$operationId.tsx b/apps/mes/app/routes/x+/operation.$operationId.tsx
index 7507ae61fe..163c5f5248 100644
--- a/apps/mes/app/routes/x+/operation.$operationId.tsx
+++ b/apps/mes/app/routes/x+/operation.$operationId.tsx
@@ -8,6 +8,8 @@ import { redirect, useLoaderData, useParams } from "react-router";
import { JobOperation } from "~/components/JobOperation";
import { getCompanySettings } from "~/services/inventory.service";
import {
+ getBatchMaterialTotals,
+ getBatchWorkInstructions,
getJobByOperationId,
getJobFiles,
getJobMakeMethod,
@@ -239,6 +241,21 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
jobMakeMethod: jobMakeMethod.data,
kanban: kanban.data,
files: getJobFiles(serviceRole, companyId, job.data, operation.data),
+ // Batch mode: the combined per-item requirement across every member, so
+ // the materials panel can show the one shared pick.
+ batchMaterialTotals: batch
+ ? await getBatchMaterialTotals(serviceRole, {
+ batchId: batch.id as string,
+ companyId
+ })
+ : null,
+ // Batch mode: steps, parameters and files across every member (deferred).
+ batchWorkInstructions: batch
+ ? getBatchWorkInstructions(serviceRole, {
+ batchId: batch.id as string,
+ companyId
+ })
+ : null,
materials: getJobMaterialsByOperationId(serviceRole, {
operation: operation.data?.[0],
trackedEntityId:
@@ -281,6 +298,8 @@ export default function OperationRoute() {
const {
batch,
+ batchMaterialTotals,
+ batchWorkInstructions,
events,
expiredEntityPolicy,
autoSelectMaterialWithoutPickingList,
@@ -302,6 +321,8 @@ export default function OperationRoute() {
<JobOperation
key={`job-operation-${operationId}`}
batch={batch}
+ batchMaterialTotals={batchMaterialTotals}
+ batchWorkInstructions={batchWorkInstructions}
events={events}
expiredEntityPolicy={expiredEntityPolicy}
autoSelectMaterialWithoutPickingList={
diff --git a/apps/mes/app/services/models.ts b/apps/mes/app/services/models.ts
index e1f41df4da..23dc8c7799 100644
--- a/apps/mes/app/services/models.ts
+++ b/apps/mes/app/services/models.ts
@@ -112,6 +112,25 @@ export const stepRecordValidator = z.object({
userValue: zfd.text(z.string().optional())
});
+// One step recorded for several batch members at once (the batch view's
+// Record). Rows are the members the operator filled in; unchanged ones are
+// never sent, so a re-open can't re-trigger a step's backflush.
+export const batchStepRecordsValidator = z.object({
+ records: z
+ .array(
+ z.object({
+ jobOperationStepId: z.string().min(1),
+ value: zfd.text(z.string().optional()),
+ numericValue: zfd.numeric(z.number().optional()),
+ booleanValue: zfd
+ .text(z.enum(["true", "false"]).transform((val) => val === "true"))
+ .optional(),
+ userValue: zfd.text(z.string().optional())
+ })
+ )
+ .min(1, { message: "Record at least one job" })
+});
+
export const issueValidator = z.object({
itemId: z.string().min(1, { message: "Item is required" }),
jobOperationId: z.string().min(1, { message: "Job Operation is required" }),
@@ -177,7 +196,11 @@ export const issueTrackedEntityValidator = z.object({
materialId: z.string().optional(),
jobOperationId: z.string().optional(),
itemId: z.string().optional(),
- parentTrackedEntityId: z.string(),
+ // Batch mode: the pick covers every member of this operation batch — the
+ // edge fn splits it pro-rata and resolves each member's own parent entity,
+ // so parentTrackedEntityId is not sent.
+ batchId: z.string().optional(),
+ parentTrackedEntityId: z.string().optional(),
children: z.array(
z.object({
trackedEntityId: z.string(),
@@ -235,6 +258,10 @@ export const completeJobOperationBatchValidator = z.object({
// included quantity to 0, so `undefined` never reaches the edge fn.
quantity: zfd.numeric(z.number().int().min(0).optional()),
scrapQuantity: zfd.numeric(z.number().int().min(0).optional()),
+ // Batch-tracked output: the member's WIP entity finalized as the
+ // produced lot. Its lot number was planned at batch creation and is
+ // resolved server-side — never an operator input.
+ trackedEntityId: zfd.text(z.string().optional()),
// "Not in this run": the operation was not physically part of the
// batch run — it detaches back to the schedule instead of being
// marked Done. String flag (same idiom as productionEventValidator's
diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.ts
index d05b546bfe..02638d3ea0 100644
--- a/apps/mes/app/services/operations.service.ts
+++ b/apps/mes/app/services/operations.service.ts
@@ -1,4 +1,4 @@
-import type { Database } from "@carbon/database";
+import type { Database, Json } from "@carbon/database";
import { activeJobStatuses, getCompanyTimeZone } from "@carbon/database";
import type { WorkSource } from "@carbon/lib/telemetry";
import { trackWorkEvent } from "@carbon/lib/telemetry";
@@ -18,6 +18,7 @@ import type { z } from "zod";
import { sanitize } from "~/utils/supabase";
import { getPickedQuantitiesByJobMaterial } from "./inventory.service";
import type {
+ batchStepRecordsValidator,
documentTypes,
nonScrapQuantityValidator,
productionEventValidator,
@@ -90,21 +91,75 @@ export async function getJobOperationBatch(
.single();
if (batch.error) return batch;
// Only what the operation view's batch mode consumes: member planned times
- // (summed into the work-type toggle), completion pre-fill quantities, and the
- // member's job id for the chip / completion table.
+ // (summed into the work-type toggle), completion pre-fill quantities, the
+ // member's job id for the chip / completion table, and the due dates and
+ // customers the batch's header summarizes.
const operations = await client
.from("jobOperation")
.select(
- "id, description, operationQuantity, quantityComplete, setupTime, setupUnit, laborTime, laborUnit, machineTime, machineUnit, job(jobId)"
+ "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))"
)
.eq("jobOperationBatchId", batchId)
- .eq("companyId", companyId);
+ .eq("companyId", companyId)
+ .order("jobId", { referencedTable: "job", ascending: true });
+
+ // Batch-tracked outputs: each member's WIP entity (finalized as the produced
+ // lot at completion) and its current batch number, for the completion form's
+ // per-member batch-number field.
+ const makeMethodIds = [
+ ...new Set(
+ (operations.data ?? [])
+ .map((o) => o.jobMakeMethodId)
+ .filter(Boolean) as string[]
+ )
+ ];
+ const entities = makeMethodIds.length
+ ? await client
+ .from("trackedEntity")
+ .select("id, readableId, attributes, createdAt")
+ .in("attributes->>Job Make Method", makeMethodIds)
+ .eq("companyId", companyId)
+ .order("createdAt", { ascending: true })
+ : { data: [], error: null };
+ const entityByMakeMethod = new Map<
+ string,
+ { id: string; readableId: string | null }
+ >();
+ for (const e of entities.data ?? []) {
+ const makeMethodId =
+ e.attributes !== null &&
+ typeof e.attributes === "object" &&
+ "Job Make Method" in e.attributes
+ ? (e.attributes["Job Make Method"] as string)
+ : null;
+ if (makeMethodId && !entityByMakeMethod.has(makeMethodId)) {
+ entityByMakeMethod.set(makeMethodId, {
+ id: e.id,
+ readableId: e.readableId
+ });
+ }
+ }
+
return {
data: {
...batch.data,
- operations: operations.data ?? []
+ operations: (operations.data ?? []).map((o) => {
+ const entity = o.jobMakeMethodId
+ ? entityByMakeMethod.get(o.jobMakeMethodId)
+ : undefined;
+ return {
+ ...o,
+ requiresBatchTracking:
+ o.jobMakeMethod?.requiresBatchTracking ?? false,
+ itemId: o.jobMakeMethod?.itemId ?? null,
+ trackedEntityId: entity?.id ?? null,
+ batchNumber: entity?.readableId ?? null
+ };
+ })
},
- error: operations.error
+ // The entities carry the planned lot numbers — completion must not run
+ // on a batch whose lots could not be read.
+ error: operations.error ?? entities.error
};
}
@@ -688,6 +743,303 @@ export async function getJobMakeMethod(
return client.from("jobMakeMethod").select("*").eq("id", id).single();
}
+// Batch-wide material requirement per item: summed estimated vs issued across
+// every member operation's BOM lines. Feeds the batch-mode materials panel so
+// the operator sees the combined pick (e.g. 6,500 seeds); recording still
+// happens per member via the issue fn's trackedEntitiesToBatch case.
+export type BatchMaterialTotal = {
+ required: number;
+ issued: number;
+ itemReadableId: string | null;
+ name: string | null;
+ thumbnailPath: string | null;
+ itemType: string | null;
+ // Where the members' rows say to pick it from (the first one set).
+ storageUnitName: string | null;
+ unitOfMeasureCode: string | null;
+ requiresBatchTracking: boolean;
+ requiresSerialTracking: boolean;
+ // each member's share, in member order, for the per-job split line
+ perMember: { jobOperationId: string; required: number }[];
+};
+
+// The batch's materials, summed per item across every member. Reads the same
+// op-linked rows the shared pick (issue `trackedEntitiesToBatch`) issues
+// against, so what the batch view shows is exactly what one pick can cover.
+export async function getBatchMaterialTotals(
+ client: SupabaseClient<Database>,
+ args: { batchId: string; companyId: string }
+): Promise<Record<string, BatchMaterialTotal>> {
+ const members = await client
+ .from("jobOperation")
+ .select("id, jobMakeMethodId")
+ .eq("jobOperationBatchId", args.batchId)
+ .eq("companyId", args.companyId);
+ if (members.error || !members.data?.length) return {};
+ // A member's materials are what its operation view lists — its make method's
+ // BOM — with a row linked straight to a member operation kept on it. The
+ // batch pick (`issue` trackedEntitiesToBatch) attributes rows the same way.
+ const memberIds = new Set(members.data.map((m) => m.id));
+ const memberByMakeMethod = new Map(
+ members.data
+ .filter((m) => m.jobMakeMethodId)
+ .map((m) => [m.jobMakeMethodId as string, m.id])
+ );
+ const rows = await client
+ .from("jobMaterial")
+ .select(
+ "itemId, jobOperationId, jobMakeMethodId, estimatedQuantity, quantityIssued, description, unitOfMeasureCode, requiresBatchTracking, requiresSerialTracking, item(readableIdWithRevision, thumbnailPath, type), storageUnit(name)"
+ )
+ .or(
+ [
+ `jobOperationId.in.(${[...memberIds].join(",")})`,
+ memberByMakeMethod.size
+ ? `jobMakeMethodId.in.(${[...memberByMakeMethod.keys()].join(",")})`
+ : null
+ ]
+ .filter(Boolean)
+ .join(",")
+ )
+ .eq("companyId", args.companyId);
+ const totals: Record<string, BatchMaterialTotal> = {};
+ for (const r of rows.data ?? []) {
+ const jobOperationId =
+ r.jobOperationId && memberIds.has(r.jobOperationId)
+ ? r.jobOperationId
+ : memberByMakeMethod.get(r.jobMakeMethodId);
+ if (!r.itemId || !jobOperationId) continue;
+ const t = (totals[r.itemId] ??= {
+ required: 0,
+ issued: 0,
+ itemReadableId: r.item?.readableIdWithRevision ?? null,
+ thumbnailPath: r.item?.thumbnailPath ?? null,
+ itemType: r.item?.type ?? null,
+ storageUnitName: null,
+ name: r.description ?? null,
+ unitOfMeasureCode: r.unitOfMeasureCode ?? null,
+ requiresBatchTracking: Boolean(r.requiresBatchTracking),
+ requiresSerialTracking: Boolean(r.requiresSerialTracking),
+ perMember: []
+ });
+ t.storageUnitName ??= r.storageUnit?.name ?? null;
+ const required = Number(r.estimatedQuantity ?? 0);
+ t.required += required;
+ t.issued += Number(r.quantityIssued ?? 0);
+ const share = t.perMember.find((m) => m.jobOperationId === jobOperationId);
+ if (share) share.required += required;
+ else t.perMember.push({ jobOperationId, required });
+ }
+ return totals;
+}
+
+export type BatchStep = {
+ key: string;
+ name: string;
+ type: string;
+ sortOrder: number;
+ required: boolean;
+ unitOfMeasureCode: string | null;
+ minValue: number | null;
+ maxValue: number | null;
+ listValues: string[] | null;
+ // The reference material, taken from the first member carrying the step
+ // (the same procedure step on every job).
+ description: Json | null;
+ slides: {
+ id: string;
+ imagePath: string | null;
+ caption: string | null;
+ sortOrder: number | null;
+ annotations: Json | null;
+ }[];
+ // One entry per member operation carrying this step.
+ perMember: {
+ jobOperationId: string;
+ stepId: string;
+ recorded: boolean;
+ record: BatchStepRecord | null;
+ }[];
+};
+
+export type BatchStepRecord = {
+ value: string | null;
+ numericValue: number | null;
+ booleanValue: boolean | null;
+ userValue: string | null;
+};
+
+export type BatchParameter = {
+ key: string;
+ // Distinct values and the member operations holding each; one entry when
+ // every job runs the same setting.
+ values: { value: string; jobOperationIds: string[] }[];
+};
+
+export type BatchWorkInstructions = Awaited<
+ ReturnType<typeof getBatchWorkInstructions>
+>;
+
+export type BatchFile = StorageItem & {
+ storagePath: string;
+ // The member job a job file belongs to; null for item files every job shares.
+ jobReadableId: string | null;
+};
+
+// The batch view's work instructions, aggregated across members: each step
+// once (members share the routing) with who has recorded it, each parameter
+// once with any per-job differences, and every file — the item's shared
+// drawings once, plus each job's own attachments labelled by job.
+export async function getBatchWorkInstructions(
+ client: SupabaseClient<Database>,
+ args: { batchId: string; companyId: string }
+): Promise<{
+ steps: BatchStep[];
+ parameters: BatchParameter[];
+ files: BatchFile[];
+}> {
+ const members = await client
+ .from("jobOperation")
+ .select("id, jobId, job(jobId, itemId)")
+ .eq("jobOperationBatchId", args.batchId)
+ .eq("companyId", args.companyId);
+ if (members.error || !members.data?.length) {
+ return { steps: [], parameters: [], files: [] };
+ }
+ const memberIds = members.data.map((m) => m.id);
+
+ const [steps, parameters] = await Promise.all([
+ client
+ .from("jobOperationStep")
+ .select(
+ "id, operationId, name, type, sortOrder, required, unitOfMeasureCode, minValue, maxValue, listValues, description, jobOperationStepSlide(id, imagePath, caption, sortOrder, annotations), jobOperationStepRecord(index, value, numericValue, booleanValue, userValue)"
+ )
+ .in("operationId", memberIds)
+ .eq("companyId", args.companyId),
+ client
+ .from("jobOperationParameter")
+ .select("operationId, key, value")
+ .in("operationId", memberIds)
+ .eq("companyId", args.companyId)
+ ]);
+
+ const stepsByKey = new Map<string, BatchStep>();
+ for (const step of steps.data ?? []) {
+ const key = `${step.sortOrder ?? 0}|${step.type}|${step.name}`;
+ const entry =
+ stepsByKey.get(key) ??
+ ({
+ key,
+ name: step.name,
+ type: step.type,
+ sortOrder: Number(step.sortOrder ?? 0),
+ required: Boolean(step.required),
+ unitOfMeasureCode: step.unitOfMeasureCode ?? null,
+ minValue: step.minValue ?? null,
+ maxValue: step.maxValue ?? null,
+ listValues: step.listValues ?? null,
+ description: step.description ?? null,
+ slides: step.jobOperationStepSlide ?? [],
+ perMember: []
+ } satisfies BatchStep);
+ const records = step.jobOperationStepRecord ?? [];
+ const record = records.find((r) => r.index === 0) ?? records[0] ?? null;
+ entry.perMember.push({
+ jobOperationId: step.operationId,
+ stepId: step.id,
+ recorded: records.length > 0,
+ record: record
+ ? {
+ value: record.value ?? null,
+ numericValue: record.numericValue ?? null,
+ booleanValue: record.booleanValue ?? null,
+ userValue: record.userValue ?? null
+ }
+ : null
+ });
+ stepsByKey.set(key, entry);
+ }
+
+ const parametersByKey = new Map<string, BatchParameter>();
+ for (const parameter of parameters.data ?? []) {
+ const entry = parametersByKey.get(parameter.key) ?? {
+ key: parameter.key,
+ values: []
+ };
+ const same = entry.values.find((v) => v.value === parameter.value);
+ if (same) same.jobOperationIds.push(parameter.operationId);
+ else
+ entry.values.push({
+ value: parameter.value,
+ jobOperationIds: [parameter.operationId]
+ });
+ parametersByKey.set(parameter.key, entry);
+ }
+
+ // Storage has no multi-folder list: one listing per member job and per
+ // distinct item, bounded by the batch's size (the same shape getJobFiles uses).
+ const jobs = members.data
+ .map((m) => ({
+ id: m.jobId,
+ readableId: (m.job as { jobId?: string } | null)?.jobId ?? m.jobId,
+ itemId: (m.job as { itemId?: string } | null)?.itemId ?? null
+ }))
+ .filter((job, i, all) => all.findIndex((j) => j.id === job.id) === i);
+ const itemIds = [
+ ...new Set(jobs.map((job) => job.itemId).filter((id): id is string => !!id))
+ ];
+ const [jobFiles, itemFiles] = await Promise.all([
+ Promise.all(
+ jobs.map(async (job) => {
+ const folder = `${args.companyId}/job/${job.id}`;
+ const listed = await client.storage.from("private").list(folder);
+ return (listed.data ?? []).map(
+ (file): BatchFile => ({
+ ...file,
+ bucket: "job",
+ storagePath: `${folder}/${file.name}`,
+ jobReadableId: job.readableId
+ })
+ );
+ })
+ ),
+ Promise.all(
+ itemIds.map(async (itemId) => {
+ const folder = `${args.companyId}/parts/${itemId}`;
+ const listed = await client.storage.from("private").list(folder);
+ return (listed.data ?? []).map(
+ (file): BatchFile => ({
+ ...file,
+ bucket: "parts",
+ itemId,
+ storagePath: `${folder}/${file.name}`,
+ jobReadableId: null
+ })
+ );
+ })
+ )
+ ]);
+
+ return {
+ steps: [...stepsByKey.values()].sort((a, b) => a.sortOrder - b.sortOrder),
+ parameters: [...parametersByKey.values()],
+ files: [
+ ...itemFiles.flat(),
+ ...jobFiles.flat().sort((a, b) =>
+ (a.jobReadableId ?? "").localeCompare(
+ b.jobReadableId ?? "",
+ undefined,
+ {
+ numeric: true
+ }
+ )
+ )
+ ].filter(
+ // Supabase lists a folder placeholder with no id; it is not a file.
+ (file) => file.id && !file.name.startsWith(".")
+ )
+ };
+}
+
export async function getJobMaterialsByOperationId(
client: SupabaseClient<Database>,
args: {
@@ -1792,6 +2144,53 @@ export async function insertAttributeRecord(
});
}
+// The batch view's Record: one step written for several members in one upsert,
+// at record set 0 (batch members are never serial-tracked, so each job has one
+// set). The steps are re-read under the batch and company — this runs with the
+// service role and the ids come from the form.
+export async function insertBatchStepRecords(
+ client: SupabaseClient<Database>,
+ args: {
+ batchId: string;
+ companyId: string;
+ createdBy: string;
+ records: z.infer<typeof batchStepRecordsValidator>["records"];
+ }
+): Promise<{ error: { message: string } | null }> {
+ const members = await client
+ .from("jobOperation")
+ .select("id")
+ .eq("jobOperationBatchId", args.batchId)
+ .eq("companyId", args.companyId);
+ if (members.error) return { error: members.error };
+
+ const stepIds = [...new Set(args.records.map((r) => r.jobOperationStepId))];
+ const steps = await client
+ .from("jobOperationStep")
+ .select("id")
+ .in("id", stepIds)
+ .in(
+ "operationId",
+ (members.data ?? []).map((m) => m.id)
+ )
+ .eq("companyId", args.companyId);
+ if (steps.error) return { error: steps.error };
+ if ((steps.data ?? []).length !== stepIds.length) {
+ return { error: { message: "A step is not part of this batch" } };
+ }
+
+ const upsert = await client.from("jobOperationStepRecord").upsert(
+ args.records.map((record) => ({
+ ...record,
+ index: 0,
+ companyId: args.companyId,
+ createdBy: args.createdBy
+ })),
+ { onConflict: "jobOperationStepId, index", ignoreDuplicates: false }
+ );
+ return { error: upsert.error };
+}
+
// Manager override: record every step of an operation that has no record yet for this unit
// index, in one write. Records carry no captured value (booleanValue/numericValue/etc. left
// null) — the override marks steps done without their data capture, which is the point of an
diff --git a/apps/mes/app/services/types.ts b/apps/mes/app/services/types.ts
index e929fb267b..1b71dbdfaf 100644
--- a/apps/mes/app/services/types.ts
+++ b/apps/mes/app/services/types.ts
@@ -90,6 +90,9 @@ export type ProductionQuantity = NonNullable<
export type StorageItem = FileObject & {
bucket: string;
itemId?: string;
+ // The file's full storage path when it does not live under the current job
+ // (the batch view lists every member job's files).
+ storagePath?: string;
};
export type TrackedEntity = NonNullable<
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index 6b4b00f32d..9f1e8cb780 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -48,6 +48,7 @@ export const path = {
authenticatedRoot: x,
batch: (id: string) => generatePath(`${x}/batch/${id}`),
batchComplete: (id: string) => generatePath(`${x}/batch/${id}/complete`),
+ batchRecord: (id: string) => generatePath(`${x}/batch/${id}/record`),
callback: "/callback",
companySwitch: (companyId: string) =>
generatePath(`${x}/company/switch/${companyId}`),
diff --git a/apps/mes/package.json b/apps/mes/package.json
index c7d0c15f74..2be5db2117 100644
--- a/apps/mes/package.json
+++ b/apps/mes/package.json
@@ -81,6 +81,7 @@
"react-resizable-panels": "catalog:",
"react-router": "catalog:",
"remix-flat-routes": "catalog:",
+ "sonner": "2.0.7",
"sst": "catalog:",
"supabase": "catalog:",
"tailwind-merge": "catalog:",
diff --git a/apps/mes/vite.config.ts b/apps/mes/vite.config.ts
index 8b6a23e15c..7cc7e9192f 100644
--- a/apps/mes/vite.config.ts
+++ b/apps/mes/vite.config.ts
@@ -25,6 +25,14 @@ export default defineConfig(({ mode, isSsrBuild }) => {
*/
const ssrNoExternal = [
"react-dropzone",
+ /**
+ * sonner's stylesheet is imported as `dist/styles.css?url` from root.tsx.
+ * Externalized, the dev SSR module runner hands the resolved path with
+ * its query straight to Node, which cannot load it ("Cannot find module
+ * ...styles.css?url"). Inlined, the ?url import goes through Vite's
+ * asset pipeline. The production build is unaffected either way.
+ */
+ "sonner",
"react-icons",
"react-phone-number-input",
"tailwind-merge",
diff --git a/docs/content/docs/reference/batching.mdx b/docs/content/docs/reference/batching.mdx
index 356b603b63..6423ceda89 100644
--- a/docs/content/docs/reference/batching.mdx
+++ b/docs/content/docs/reference/batching.mdx
@@ -15,7 +15,7 @@ An operation batch (`BAT000001`) is a production-run concept. It is unrelated to
Batching is switched on per **process**, not per item or method. On the process form (**Resources → Processes**), turn on **"Batchable"** and pick a **"Batch type"**: **"Sequential"** (parts run one after another, like a saw or laser table) or **"Simultaneous"** (parts run together in one load, like a furnace, oven, or plating bath). The type drives the run-time estimate: sequential sums the members' times, simultaneous takes the longest.
-The same card holds the **"Compatibility rules"**: how strictly each material property must match for operations to share a batch. Six dimensions (material, substance, grade, dimension, form, finish), each set to **"Require Match"**, **"Suggest Match"**, or **"Ignore"**. By default substance, grade, and dimension suggest a match and the rest are ignored.
+The same card holds the **"Compatibility rules"**: how strictly each dimension must match for operations to share a batch. Six describe the material consumed (material, substance, grade, dimension, form, finish) and a seventh, **"Produced item"**, describes what each job makes. Each is set to **"Require Match"**, **"Suggest Match"**, or **"Ignore"**. By default substance, grade, and dimension suggest a match and the rest are ignored. Requiring a match on "Produced item" keeps a run to a single output item, which is what makes its [output lots](#completing-the-batch) mergeable afterwards.
Only "Require Match" ever blocks anything; a suggested mismatch just warns. A work center can additionally carry an advisory **"Batch Capacity"** and **"Minimum Batch Quantity"**; the builder shows a fill bar against them but never refuses a batch over them.
@@ -27,7 +27,11 @@ Operations whose "Require Match" dimensions clash with your selection stay visib
<Screenshot label="The batch builder at Production → Batches → New Batch: scope pickers, the eligible-operations list grouped by material with suggestion banner, and the Review & create panel with setup-saving chip" caption="Suggestions group by material signature and due window; the review panel shows one shared setup instead of one per operation." />
-The builder also proposes ready-made groupings: operations sharing a material signature and due within the same seven-day window, ranked by setup saved, urgency, and capacity fit. Finish with **"Create batch"** (the batch waits as **"Planned"**) or **"Create & Release"** (it goes straight to the floor). A work center is optional at this point: leave it blank and the scheduler auto-assigns the earliest-finishing candidate on release, writing it to the batch and every member.
+The builder also proposes ready-made groupings: operations sharing a material signature and due within the same seven-day window, ranked by setup saved, urgency, and capacity fit.
+
+When the selected operations produce a lot-tracked item, the review panel adds an **"Output"** section: this is where the run's lot numbers are decided, not on the shop floor. Each job gets its own lot number, pre-filled from the job's current one. When every selected operation makes the same lot-tracked item, **"Combine output into one lot"** replaces them with a single lot number for the whole run. Creating is disabled until every lot number is filled in and no two jobs share one.
+
+Finish with **"Create batch"** (the batch waits as **"Planned"**) or **"Create & Release"** (it goes straight to the floor). A work center is optional at this point: leave it blank and the scheduler auto-assigns the earliest-finishing candidate on release, writing it to the batch and every member.
## Lifecycle
@@ -44,10 +48,12 @@ There is no cancelled state: **"Dissolve Batch"** returns the members to the sch
The moment a single timer event is recorded against the batch, membership is permanent: adding, removing, changing the work center, unreleasing, and dissolving are all refused, and the only exit is completing it. Decide the composition before work starts.
</Callout>
-<Callout type="note" title="Release pulls member jobs onto the floor">
-A batched operation is visible to operators when its **batch** is released, even if its own job is still "Draft" or "Planned"; the batch's schedule outranks the job's. Releasing recalculates requirements for those unreleased member jobs first, so materials are known, but it does not run MRP. The same job's other, unbatched operations stay hidden until the job itself is released.
+<Callout type="note" title="Releasing a batch releases its jobs">
+Member jobs still in "Draft" or "Planned" are released with the batch, exactly as **"Release Job"** would release them: requirements are recalculated, MRP runs, the job becomes "Ready", and its outside operations go on purchase orders. The **"Release"** dialog checks every one of those jobs first — each assembly needs an operation and manufacturing must not be blocked — and a single job that fails keeps the whole batch unreleased until it is fixed. For each supplier you choose a new purchase order or an existing draft, once for the whole batch, so outside operations from every member job land on one order.
</Callout>
+Bulk **"Release N batches"** on the Batches list has no dialog: a batch whose jobs need fixing, or whose suppliers already have a draft purchase order to choose from, is skipped and named in the summary. Release those from the batch itself.
+
## On the schedule
A released batch is one scheduling unit: it books a single work-center reservation sized by the batch type, placed before the per-job passes so member jobs plan around it.
@@ -56,16 +62,42 @@ On the [schedule board](/docs/reference/scheduling), the batch renders as one ca
## On the shop floor
-There is no separate batch screen in the shop floor app: any member's operation view *is* the batch UI. A batch chip shows the `BAT…` number, the member jobs, and a **"Print batch list"** action; the timer is shared, so starting it runs one clock for the whole batch, and planned time shows the batch total.
+There is no separate batch page in the shop floor app: any member's operation view *is* the batch UI. A batch chip shows the `BAT…` number, the member jobs, and a **"Print batch list"** action; the timer is shared, so starting it runs one clock for the whole batch, and planned time shows the batch total.
+
+Beside the chip, a **Batch | job** switch picks what the page shows. **"Batch"** (the default) is the whole run: completed quantity across every job, materials issued, scrap, the output lot, one materials table with batch totals, and the list of member jobs. The job switch shows the member's own steps, parameters, materials, and files, as for any operation.
+
+<Screenshot label="A batched operation in the shop floor app with the Batch view selected: Completed, Materials issued, Scrapped, and Output lot cards, the batch materials table, and the Jobs in this batch table" caption="The batch view aggregates the run; the job view is one member's own details." />
+
+## Picking materials
+
+The run is shared, so the materials list is too. The batch view lists each material once with the batch's total requirement and the split per job beneath it (for example `2 · 4 · 6`), and a **"Pick"** button for what is still outstanding. In the job view each material row carries a second **"Batch"** figure beside the member's own.
+
+Picking a <Term id="tracked-entity">lot-tracked</Term> material issues it to every member at once. The quantity defaults to the batch's outstanding requirement, and Carbon divides what you pick across the members in proportion to what each still needs. Costing and lot [traceability](/docs/reference/traceability) stay per job; only the operator's trip to the shelf is pooled.
+
+<Callout type="warn" title="Pick the batch quantity, not one job's">
+The split is proportional, so a smaller pick is divided across every member rather than filling one of them. On a batch needing 4,000 and 2,500, picking 4,000 leaves both members short instead of completing the first. Take the default, which is the batch total.
+</Callout>
+
+Materials that are not lot-tracked show a batch total for reference only. They are still consumed per job automatically at completion.
+
+## Completing the batch
-<Screenshot label="The Complete Batch modal in the shop floor app: one row per member job with Quantity and Scrap inputs, and the footnote about leaving a row at zero" caption="Time and cost split across jobs proportionally to quantity; scrap is entered per job and never split." />
+<Screenshot label="The Complete Batch modal in the shop floor app: one row per member job with Quantity and Scrap inputs, the planned output lot stated above them, and the footnote about leaving a row at zero" caption="Time and cost split across jobs proportionally to quantity; the output lot was set when the batch was planned." />
-Completion happens once, for the whole batch, in the **"Complete Batch"** modal: one row per member with **Quantity** and **Scrap**, pre-filled with each operation's remaining quantity. Leave a row at zero to skip that operation — it detaches and returns to the schedule un-run, with no time or quantity recorded.
+Completion happens once, for the whole batch, in the **"Complete Batch"** modal: one row per member with **Quantity** and **Scrap**, pre-filled with each operation's remaining quantity. Leave a row at zero to skip that operation, which detaches it and returns it to the schedule un-run, with no time or quantity recorded.
-On submit, any running timer stops, the shared time is sliced into per-member events in proportion to each member's planned quantity, scrap is recorded per member exactly as typed, materials issue, costs post, and every remaining member is marked **"Done"**.
+The operator never enters a lot number. A combined run states its lot above the rows (*"All output goes to lot …"*); otherwise a read-only **"Lot"** column shows each job's planned lot. A batch created before lot planning existed, with a lot-tracked member that has no lot number, cannot complete: the modal names those jobs, and the fix is the lot number in the job's properties sidebar.
+
+On submit, any running timer stops, the shared time is sliced into per-member events in proportion to each member's planned quantity, scrap is recorded per member exactly as typed, each member's output lot is created, materials issue, costs post, and every remaining member is marked **"Done"**.
<Callout type="warn" title="A partial quantity still completes the operation">
-Entering less than the pre-filled quantity records less output, but the member operation is marked "Done" regardless. The only way to keep a member open is to zero it out entirely so it leaves the batch. If a downstream step fails mid-completion, the batch parks at "Completing" and the modal's button becomes **"Retry Completion"** — the retry must resubmit the recorded quantities, and corrections happen after completion.
+Entering less than the pre-filled quantity records less output, but the member operation is marked "Done" regardless. The only way to keep a member open is to zero it out entirely so it leaves the batch. If a downstream step fails mid-completion, the batch parks at "Completing" and the modal's button becomes **"Retry Completion"**. The retry must resubmit the recorded quantities, and corrections happen after completion.
+</Callout>
+
+Each member first gets its own lot, because each job has its own cost and history. When the batch was planned to combine its output, those lots merge into the planned lot right after completion. Otherwise they stay separate. Completing the batch also completes each member job whose batched operation was its last, so the merged lot's full quantity is on hand immediately; a member with operations still remaining completes later and adds its share then. A completed batch's drawer still offers **"Merge output lots"** for lots kept separate.
+
+<Callout type="success" title="Merging adds history rather than losing it">
+The merged lot holds the summed quantity and the earliest expiry date of the lots that went into it, and its genealogy still reaches back through every member job to the materials each one consumed. A quality event on it resolves to the exact jobs involved, which a single directly-produced lot could never tell you.
</Callout>
## Related
@@ -75,6 +107,7 @@ Entering less than the pre-filled quantity records less output, but the member o
<Card title="Jobs" href="/docs/reference/jobs">The work orders whose operations a batch groups.</Card>
<Card title="Work centers" href="/docs/reference/work-centers">Where a batch runs, and the advisory capacity numbers the builder reads.</Card>
<Card title="MES" href="/docs/reference/mes">The shop floor app where the shared timer runs and completion happens.</Card>
+ <Card title="Traceability" href="/docs/reference/traceability">The lots a batch consumes and produces, and how a merged lot still traces to every member job.</Card>
</Cards>
<AgentContext>
@@ -90,7 +123,17 @@ Eligibility (`assertEligible`): same company, same process, process batchable, `
Two-phase completion (`completeBatch`): phase 1 in one transaction — detach excluded members, auto-close a running timer at NOW(), slice events per member ∝ `operationQuantity` (largest-remainder whole seconds; `productionEvent.duration` is GENERATED so cost follows), insert per-member `productionQuantity` rows (Production when qty>0, Scrap when scrap>0), flip Active→Completing. Phase 2 idempotent — issue materials per member with qty>0, flip members Done (fires `sync_finish_job_operation` each), post GL per sliced event skipping already-posted, finalize Completing→Completed. MES batch timers skip `post-production-event` at End (`apps/mes/app/routes/x+/event.tsx:129-132`); cost posts once at completion. Scheduler: `batch-scheduler.ts` pre-pass places Active/Completing batches as one unit (Planned excluded), auto-assigns earliest-finish work center when blank (guarded `WHERE workCenterId IS NULL`), writes one reservation anchored on the min open member op; the reservation is spared by per-job regen and retired only by the status trigger (`20260907155426_cleanup-reservations-on-batch-exit.sql`) on entry to Planned/Completed; dissolve self-heals via FK SET NULL. Employee finiteness is deliberately absent in v1 — the batch reserves the work center only.
-Key refusal strings (edge fn): "The process is not batchable"; "Operation {id} is already in a batch"; "Operation {id} has already started"; "Operations with recorded production events cannot be batched"; "These operations can't share a batch — the {dims} must match on this process"; "Cannot add operations to a batch with status {status}"; "The batch has already started — complete it instead"; "Cannot remove operations: production has been recorded. Complete the batch instead."; "Cannot change the work center: production has been recorded."; "Only a planned batch can be released"; "Cannot release an empty batch"; "Only an active batch can be unreleased"; "Cannot dissolve: production has been recorded. Complete the batch instead — member jobs then proceed independently."; "Every operation is excluded — dissolve the batch instead of completing it"; "Operation {id} was included when completion started — retry with the recorded values; corrections happen after completion."; "Quantities were already recorded for this batch ({detail}). Retry with the recorded values; corrections happen after completion."; "One or more operations were already claimed by another batch — refresh and try again". MES gates: "This operation is part of a batch that has not been released to the floor"; "This operation's job has not been released to the floor". Builder add-mode: "Only a planned or active batch can take more operations". Scheduling conflict: "{Batch} has no estimated time — add setup, labor, or machine time to its operations to schedule it".
+Materials and output lots (spec `.ai/specs/2026-09-16-batch-materials-and-output-lots.md`). Shared pick: `issue` case `trackedEntitiesToBatch` (permission `update: "production"`) resolves the accounting period BEFORE opening its transaction (`getCurrentAccountingPeriod` reads over HTTP but writes in-transaction, so N members in one transaction would each try to create a missing month), locks the members' `jobMaterial` rows `FOR UPDATE`, and splits each picked lot with `splitPickAcrossMembers` (`shared/batch-pick-split.ts`, re-exported by `@carbon/utils`) weighted by each member's REMAINING requirement, via `distributeRoundingResidual`. Per-member writes reuse `consumeTrackedEntitiesIntoOperation`, the sequence extracted from `trackedEntitiesToOperation`, so genealogy and ledger rows are identical to N manual picks. Each picked lot is split separately, so every member ends up linked to every lot it actually drew from (complete recall coverage). MES panel totals come from `getBatchMaterialTotals`; the pick modal's `batchRemainingQuantity` prop is what makes the default the batch total rather than the member's share. Untracked materials are display-only and still backflush in completion phase 2.
+
+Output lots: completion phase 2 calls `issue` case `jobOperationBatchOutput` per member whose `jobMakeMethod.requiresBatchTracking` is true, between the material issue and the Done flip. It is the `Produce` activity plus the entity flip to Available, extracted from `jobOperationBatchComplete` WITHOUT that case's `productionQuantity` insert (phase 1 wrote it) or backflush (the issue step ran). Idempotent: an already-Available entity returns `{ created: false }`. A member that requires batch tracking but carries no `trackedEntityId` is refused rather than silently skipped.
+
+Lot merge: `issue` case `mergeTrackedEntities` (permission `update: "inventory"`) → `buildBatchMergeRecords` (`shared/batch-merge.ts`). Parents keep their quantity and flip `Consumed`; the merged entity is a fresh id with the summed quantity, the EARLIEST parent `expirationDate`, attributes kept only where all parents agree, `"Merged From Entity IDs"` provenance, and the FIRST parent's `readableId` when the caller passes none (the edge fn orders parents by the caller's list, so "first" is deterministic). Genealogy is one `trackedActivity` `type: "Merge"`, inputs = each parent at its quantity, output = the merged entity; ledger gets `Batch Merge` rows sized by each parent's RECEIVED (on-ledger) balance — the merge is identity-only, so lots merged straight off a completed batch (nothing received yet) write no ledger rows at all, and each member job's later receipt posts against the merged lot (`complete_job_to_inventory` walks Merge activities to the terminal output; migration `20260916131445_merge-aware-job-receipt.sql`; enum added by `20260915201233_batch-merge-ledger-enum.sql`). **Both callers derive the parent ids server-side from batch membership** — MES `getPlannedMergeLots` in `batch.$batchId.complete.tsx` (only when the batch has `mergeOutput`; the members' Available output lots, merged right after completion succeeds under `outputLotNumber`), ERP `getBatchOutputLots` in the `mergeOutputs` intent — because these routes invoke `issue` with the service role, so the edge fn's `inventory` check validates the service role rather than the operator. No entity ids travel through a form.
+
+Lot planning (migration `20260918094217_batch-output-lot-at-creation.sql`): `jobOperationBatch.mergeOutput` + `outputLotNumber` (CHECK: a merged batch has a non-blank lot). The `batch-operations` create payload carries either `mergeOutput` + `outputLotNumber` or `lotNumbers: [{ jobOperationId, lotNumber }]`; split mode writes each member's WIP `trackedEntity.readableId` in the create transaction. `get_batchable_operations` returns `itemId`, `requiresBatchTracking`, `trackedEntityId`, `lotNumber` so the builder can pre-fill. `add` on a merged batch re-runs `assertMergeable`. The MES completion form no longer posts batch numbers: the route passes `outputLotNumber` (merged) or null (split, the entity keeps its planned readableId). The completion route returns `data({ completed: true })` rather than a redirect because realtime revalidation during the action makes React Router drop a fetcher redirect; `JobOperation` navigates on it.
+
+Compatibility: `producedItem` is the seventh entry in `BATCH_RULE_DIMENSIONS`, default `ignore`, resolved from the job's item readable id on both the client fold and the edge fn's `assertMaterialCompatible`. Batch completion completes member JOBS too: `sync_finish_job_operation`'s status gate admits Draft/Planned jobs when the Done operation carries a `jobOperationBatchId` (migration `20260916155634_batch-completion-completes-draft-jobs.sql`) — a Draft job's op can only reach Done through a released batch, so the run genuinely happened; the job's receipt posts before the route's merge, which is why a merged lot's on-hand equals its full quantity. Serial-tracked members are unchanged by all of the above — batch mode still disables tracked activity for them.
+
+Key refusal strings (edge fn): "The process is not batchable"; "Operation {id} is already in a batch"; "Operation {id} has already started"; "Operations with recorded production events cannot be batched"; "These operations can't share a batch — the {dims} must match on this process"; "Cannot add operations to a batch with status {status}"; "The batch has already started — complete it instead"; "Cannot remove operations: production has been recorded. Complete the batch instead."; "Cannot change the work center: production has been recorded."; "Only a planned batch can be released"; "Cannot release an empty batch"; "Only an active batch can be unreleased"; "Cannot dissolve: production has been recorded. Complete the batch instead — member jobs then proceed independently."; "Every operation is excluded — dissolve the batch instead of completing it"; "Operation {id} was included when completion started — retry with the recorded values; corrections happen after completion."; "Quantities were already recorded for this batch ({detail}). Retry with the recorded values; corrections happen after completion."; "One or more operations were already claimed by another batch — refresh and try again"; "Pick of {n} exceeds the batch's remaining requirement of {m}"; "No member operation still requires this item"; "Batch is already completed"; "Operation {id} produces a batch-tracked item — its output lot is required"; "Operation {id} produces a batch-tracked item — its batch number is required"; "Only lots of the same item can be merged"; "At least two lots are required to merge"; "Lot {readableId} is not available to merge"; "Lot {readableId} has no quantity to merge"; "No mergeable output lots" (ERP mergeOutputs, when server-side derivation finds nothing); "A combined output needs its lot number"; "Lot number {n} is used twice — give each job its own, or combine them into one lot"; "Only operations that produce a batch-tracked item can combine into one lot"; "Lots of different items can't combine into one lot" (create/add lot planning). Batch release (ERP `releaseBatchMemberJobs`): "Fix these jobs before releasing: {jobId}: no operations on {assemblies}; {jobId}: manufacturing is blocked; {jobId}: choose a supplier for {operation} on the job; {jobId}: {operation} has no supplier" (an outside operation's supplier is its own supplier process, else its process's only supplier — a process with several needs the choice made on the job's own Release); "Outside operations need a purchase order choice — open the batch to release it" (bulk release only, when a supplier has Draft POs to choose from); "Failed to create purchase orders for job {id}". Job release route: "Assign an operation to each assembly before releasing: {assemblies}". MES gates: "This operation is part of a batch that has not been released to the floor"; "This operation's job has not been released to the floor". Builder add-mode: "Only a planned or active batch can take more operations". Scheduling conflict: "{Batch} has no estimated time — add setup, labor, or machine time to its operations to schedule it".
### The batch card is missing from the operations board / MES
Planned batches are invisible outside the Batches list and the builder: the board and the floor only surface Active ("Released") and Completing batches. Release it.
@@ -107,6 +150,15 @@ By design: a resume must match what phase 1 recorded (mismatches are quoted back
### The builder hides some operations on the process
The hidden-ops note explains: "{n} already started", "{n} already in a batch". Started or event-carrying operations can never be batched.
+### The pick modal says a batch number is not available
+The lot picker lists stock at the member job's location that is Available with a positive on-hand and a storage unit on its ledger. A lot in another location, with no bin, or already allocated to a picking list will not appear. The Scan field matches the tracked entity id a label encodes, not the human-readable lot number.
+
+### A shared pick left every member short
+Expected when less than the batch's outstanding requirement was picked: `splitPickAcrossMembers` divides whatever was picked pro-rata across every member with remaining need (largest-remainder at internal scale, so shares sum exactly). Pick the batch total, which is the modal default in batch mode.
+
+### Completed the batch but the lots did not merge
+Merging happens only when the batch was created with "Combine output into one lot". Otherwise separate lots are by design; serial-tracked members never merge. Lots kept separate can still be merged from the completed batch's drawer ("Merge output lots") until they are consumed.
+
### Suggested batches look wrong / too small
Suggestions group by material signature split into 7-day due windows, scored by setup saved (0.4), urgency (0.35), capacity fit (0.15), specificity (0.1); top 6 shown. Undated members ride the earliest dated cluster. They're suggestions — manual selection is never constrained by them.
</AgentContext>
diff --git a/docs/content/docs/reference/traceability.mdx b/docs/content/docs/reference/traceability.mdx
index e6558dc62e..8212ffd401 100644
--- a/docs/content/docs/reference/traceability.mdx
+++ b/docs/content/docs/reference/traceability.mdx
@@ -26,6 +26,10 @@ Receiving a tracked item creates entities **On Hold**; posting the receipt relea
Every material event (consume, produce, split, ship) is recorded as an **activity** with **inputs** (what was consumed) and **outputs** (what was produced). Parent and child link through the activity, so the <Term>genealogy</Term> graph is built as work happens and walked later to trace a unit's ancestry or descendants. Consuming part of a batch records a **split**, linking the original lot to the consumed portion and the remainder.
+The inverse is a **merge**, which combines lots of one item into a single lot carrying their summed quantity and the earliest expiry date among them. Both lots stay in the graph as inputs to that merge, so the new lot traces back through each of them. [Operation batching](/docs/reference/batching) merges the members a run completed under one batch number; lots kept separate can still be merged from the batch's drawer.
+
+<Screenshot label="The genealogy graph at Inventory → Traceability → Graph: circular entity nodes colored by status (Available, Consumed, Reserved, On Hold, Rejected), diamond activity nodes between them, a stacked node for a serial group, and the legend popover open" caption="The graph is walked from any unit outward — upstream to its ancestry, downstream to everything it ended up in." />
+
<Callout type="note">
There are no separate serial-number or batch-number tables — one tracked-entity model represents both, and the number itself is an attribute. Genealogy isn't a stored parent pointer; it's reconstructed by walking the activity graph from a unit outward.
</Callout>
diff --git a/packages/auth/src/services/auth.server.ts b/packages/auth/src/services/auth.server.ts
index 9838272d96..b6088309dc 100644
--- a/packages/auth/src/services/auth.server.ts
+++ b/packages/auth/src/services/auth.server.ts
@@ -18,6 +18,7 @@ import {
CLOUDFLARE_TURNSTILE_SECRET_KEY,
CLOUDFLARE_TURNSTILE_SITE_KEY,
CONTROLLED_ENVIRONMENT,
+ IS_LOCAL_DEV,
REFRESH_ACCESS_TOKEN_THRESHOLD,
SESSION_IDLE_LOCK_MS,
STRIPE_BYPASS_COMPANY_IDS,
@@ -473,11 +474,19 @@ export const requiresTurnstile =
// enforcement without a widget is not.
export const turnstileSiteKey = CLOUDFLARE_TURNSTILE_SITE_KEY ?? null;
-export async function sendMagicLink(email: string, turnstileToken?: string) {
+export async function sendMagicLink(
+ email: string,
+ turnstileToken?: string,
+ // The app's own origin. VERCEL_URL is only correct for the app it was set
+ // for — in local dev crbn writes the ERP url (or a localhost fallback) into
+ // .env.local, so an MES started outside `crbn up` would send its first-login
+ // magic link back to the wrong origin. MES passes getMESUrl().
+ origin?: string
+) {
return getCarbonServiceRole().auth.signInWithOtp({
email,
options: {
- emailRedirectTo: `${VERCEL_URL}/callback`,
+ emailRedirectTo: `${origin ?? VERCEL_URL}/callback`,
// GoTrue verifies the token itself when Supabase Auth captcha is on
...(SUPABASE_AUTH_CAPTCHA_ENABLED && turnstileToken
? { captchaToken: turnstileToken }
@@ -547,9 +556,19 @@ async function verifyTurnstileToken(
}
}
+// DEV_BYPASS_EMAIL signs a developer in with no magic link, so it is a local
+// stack's convenience and nothing else: refuse it anywhere the env says this
+// is a real deployment (production, preview, or self-hosted), whatever the
+// variable happens to be set to there.
export async function signInWithBypassEmail(
email: string
): Promise<AuthSession | null> {
+ if (!IS_LOCAL_DEV) {
+ log.error("DEV_BYPASS_EMAIL sign-in refused outside local development", {
+ actor: email
+ });
+ return null;
+ }
const client = getCarbonServiceRole();
const { data: linkData, error: linkError } =
diff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.json
index c099f8a919..e310288225 100644
--- a/packages/checks/src/conformance/baseline.json
+++ b/packages/checks/src/conformance/baseline.json
@@ -462,6 +462,7 @@
"no-raw-rounding::apps/mes/app/components/Inspection/InspectionView.tsx::const m = Math.floor((s % 3600) / 60)",
"no-raw-rounding::apps/mes/app/components/Inspection/InspectionView.tsx::return Math.max(0, Math.floor((Date.now() - start) / 1000));",
"no-raw-rounding::apps/mes/app/components/JobOperation/JobOperation.tsx::Math.floor(",
+ "no-raw-rounding::apps/mes/app/components/JobOperation/components/BatchOverview.tsx::Math.floor(",
"no-raw-rounding::apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx::Array(Math.max(1, Math.ceil(initialQuantity)))",
"no-raw-rounding::apps/mes/app/components/TimeCardButton.tsx::const hours = Math.floor(ms / 3600000);",
"no-raw-rounding::apps/mes/app/components/TimeCardButton.tsx::const minutes = Math.floor((ms % 3600000) / 60000);",
diff --git a/packages/config/tailwind/theme.css b/packages/config/tailwind/theme.css
index fe1e41b935..555d2e6eb1 100644
--- a/packages/config/tailwind/theme.css
+++ b/packages/config/tailwind/theme.css
@@ -17,6 +17,126 @@
);
}
+/*
+ * scroll-fade / scroll-fade-x — vendored from shadcn's tailwind.css
+ * (https://ui.shadcn.com/docs/utils/scroll-fade). Put it on the element that
+ * scrolls: the edge with more content fades, tracking scroll position via
+ * scroll-driven animation (static fade on both edges without support).
+ */
+@property --scroll-fade-t {
+ syntax: "<length-percentage>";
+ inherits: false;
+ initial-value: 0px;
+}
+@property --scroll-fade-b {
+ syntax: "<length-percentage>";
+ inherits: false;
+ initial-value: 0px;
+}
+@property --scroll-fade-s {
+ syntax: "<length-percentage>";
+ inherits: false;
+ initial-value: 0px;
+}
+@property --scroll-fade-e {
+ syntax: "<length-percentage>";
+ inherits: false;
+ initial-value: 0px;
+}
+
+@theme inline {
+ @keyframes scroll-fade-reveal-t {
+ from {
+ --scroll-fade-t: 0px;
+ }
+ to {
+ --scroll-fade-t: var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)));
+ }
+ }
+ @keyframes scroll-fade-reveal-b {
+ from {
+ --scroll-fade-b: var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)));
+ }
+ to {
+ --scroll-fade-b: 0px;
+ }
+ }
+ @keyframes scroll-fade-reveal-s {
+ from {
+ --scroll-fade-s: 0px;
+ }
+ to {
+ --scroll-fade-s: var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)));
+ }
+ }
+ @keyframes scroll-fade-reveal-e {
+ from {
+ --scroll-fade-e: var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)));
+ }
+ to {
+ --scroll-fade-e: 0px;
+ }
+ }
+}
+
+@utility scroll-fade {
+ mask-image: linear-gradient(
+ to bottom,
+ transparent 0,
+ #000 var(--scroll-fade-t, 0px),
+ #000 calc(100% - var(--scroll-fade-b, 0px)),
+ transparent 100%
+ );
+ mask-repeat: no-repeat;
+
+ @supports (animation-timeline: scroll()) {
+ animation:
+ scroll-fade-reveal-t 1ms ease-in-out,
+ scroll-fade-reveal-b 1ms ease-in-out;
+ animation-timeline: scroll(self y), scroll(self y);
+ animation-range:
+ 0 calc(var(--spacing) * 24),
+ calc(100% - calc(var(--spacing) * 24)) 100%;
+ animation-fill-mode: both;
+ }
+
+ @supports not (animation-timeline: scroll()) {
+ --scroll-fade-t: var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)));
+ --scroll-fade-b: var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)));
+ }
+}
+
+@utility scroll-fade-x {
+ mask-image: linear-gradient(
+ to right,
+ transparent 0,
+ #000 var(--scroll-fade-s, 0px),
+ #000 calc(100% - var(--scroll-fade-e, 0px)),
+ transparent 100%
+ );
+ mask-repeat: no-repeat;
+
+ @supports (animation-timeline: scroll()) {
+ animation:
+ scroll-fade-reveal-s 1ms ease-in-out,
+ scroll-fade-reveal-e 1ms ease-in-out;
+ animation-timeline: scroll(self inline), scroll(self inline);
+ animation-range:
+ 0 calc(var(--spacing) * 24),
+ calc(100% - calc(var(--spacing) * 24)) 100%;
+ animation-fill-mode: both;
+ }
+
+ @supports not (animation-timeline: scroll()) {
+ --scroll-fade-s: var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)));
+ --scroll-fade-e: var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)));
+ }
+}
+
+@utility scroll-fade-* {
+ --scroll-fade-size: calc(var(--spacing) * --value(integer));
+}
+
/*
* Restore v3 base defaults that changed in v4.
* - border color: v4 uses currentColor, v3 used gray-200
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 65a2119f58..0ea2c75d13 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -17637,6 +17637,12 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperationBatch.updatedAt"
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperationBatch.mergeOutput"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationBatch.outputLotNumber"
+ },
{
$ref: "#/parameters/select"
},
@@ -17735,6 +17741,12 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperationBatch.updatedAt"
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperationBatch.mergeOutput"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationBatch.outputLotNumber"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -17787,6 +17799,12 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperationBatch.updatedAt"
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperationBatch.mergeOutput"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationBatch.outputLotNumber"
+ },
{
$ref: "#/parameters/body.jobOperationBatch"
},
@@ -113716,7 +113734,8 @@ export default {
"locationId",
"status",
"createdBy",
- "createdAt"
+ "createdAt",
+ "mergeOutput"
],
properties: {
id: {
@@ -113780,6 +113799,15 @@ export default {
updatedAt: {
format: "timestamp with time zone",
type: "string"
+ },
+ mergeOutput: {
+ default: false,
+ format: "boolean",
+ type: "boolean"
+ },
+ outputLotNumber: {
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -115809,7 +115837,8 @@ export default {
"Inbound Inspection",
"Inventory Count",
"Scrap",
- "Sales Return Shipment"
+ "Sales Return Shipment",
+ "Batch Merge"
],
format: 'public."itemLedgerDocumentType"',
type: "string"
@@ -120959,7 +120988,8 @@ export default {
"Inbound Inspection",
"Inventory Count",
"Scrap",
- "Sales Return Shipment"
+ "Sales Return Shipment",
+ "Batch Merge"
],
format: 'public."itemLedgerDocumentType"',
type: "string"
@@ -121537,6 +121567,7 @@ export default {
"Non-Conformance",
"Inbound Inspection",
"Scrap",
+ "Batch Merge",
"Card Transaction"
],
format: 'public."journalLineDocumentType"',
@@ -134878,7 +134909,8 @@ export default {
"Inbound Inspection",
"Inventory Count",
"Scrap",
- "Sales Return Shipment"
+ "Sales Return Shipment",
+ "Batch Merge"
],
format: 'public."itemLedgerDocumentType"',
type: "string"
@@ -135088,6 +135120,7 @@ export default {
"Non-Conformance",
"Inbound Inspection",
"Scrap",
+ "Batch Merge",
"Card Transaction"
],
format: 'public."journalLineDocumentType"',
@@ -135274,6 +135307,7 @@ export default {
"Non-Conformance",
"Inbound Inspection",
"Scrap",
+ "Batch Merge",
"Card Transaction"
],
format: 'public."journalLineDocumentType"',
@@ -159201,6 +159235,18 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.jobOperationBatch.mergeOutput": {
+ name: "mergeOutput",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.jobOperationBatch.outputLotNumber": {
+ name: "outputLotNumber",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.itemInspectionDocumentAssignment": {
name: "itemInspectionDocumentAssignment",
description: "itemInspectionDocumentAssignment",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 27c4ae3bb5..54c60d241c 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -25361,7 +25361,9 @@ export type Database = {
customFields: Json | null
id: string
locationId: string
+ mergeOutput: boolean
notes: string | null
+ outputLotNumber: string | null
processId: string
readableId: string
status: Database["public"]["Enums"]["jobOperationBatchStatus"]
@@ -25376,7 +25378,9 @@ export type Database = {
customFields?: Json | null
id?: string
locationId: string
+ mergeOutput?: boolean
notes?: string | null
+ outputLotNumber?: string | null
processId: string
readableId: string
status?: Database["public"]["Enums"]["jobOperationBatchStatus"]
@@ -25391,7 +25395,9 @@ export type Database = {
customFields?: Json | null
id?: string
locationId?: string
+ mergeOutput?: boolean
notes?: string | null
+ outputLotNumber?: string | null
processId?: string
readableId?: string
status?: Database["public"]["Enums"]["jobOperationBatchStatus"]
@@ -82460,15 +82466,19 @@ export type Database = {
description: string
id: string
itemDescription: string
+ itemId: string
itemReadableId: string
jobDueDate: string
jobId: string
jobOperationBatchId: string
jobReadableId: string
jobStatus: Database["public"]["Enums"]["jobStatus"]
+ lotNumber: string
materials: Json
operationQuantity: number
+ requiresBatchTracking: boolean
status: Database["public"]["Enums"]["jobOperationStatus"]
+ trackedEntityId: string
workCenterId: string
}[]
}
@@ -85041,6 +85051,7 @@ export type Database = {
| "Inventory Count"
| "Scrap"
| "Sales Return Shipment"
+ | "Batch Merge"
itemLedgerType:
| "Purchase"
| "Sale"
@@ -85142,6 +85153,7 @@ export type Database = {
| "Non-Conformance"
| "Inbound Inspection"
| "Scrap"
+ | "Batch Merge"
| "Card Transaction"
kanbanOutput: "label" | "qrcode" | "url"
kanbanReplenishmentSystem: "Buy" | "Make" | "Transfer"
@@ -86467,6 +86479,7 @@ export const Constants = {
"Inventory Count",
"Scrap",
"Sales Return Shipment",
+ "Batch Merge",
],
itemLedgerType: [
"Purchase",
@@ -86576,6 +86589,7 @@ export const Constants = {
"Non-Conformance",
"Inbound Inspection",
"Scrap",
+ "Batch Merge",
"Card Transaction",
],
kanbanOutput: ["label", "qrcode", "url"],
diff --git a/packages/database/supabase/functions/batch-operations/index.ts b/packages/database/supabase/functions/batch-operations/index.ts
index 54f16ac71a..757a7740e0 100644
--- a/packages/database/supabase/functions/batch-operations/index.ts
+++ b/packages/database/supabase/functions/batch-operations/index.ts
@@ -1,5 +1,5 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
-import { Transaction } from "kysely";
+import { sql, Transaction } from "kysely";
import z from "npm:zod@^3.24.1";
import { type DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { corsHeaders } from "../lib/headers.ts";
@@ -35,6 +35,19 @@ const payloadValidator = z.discriminatedUnion("type", [
notes: z.string().optional().nullable(),
// Create straight onto the floor (Active) instead of staging as Planned.
release: z.boolean().optional(),
+ // Output lot identity is planned, never typed on the floor: either every
+ // member completes into one lot (mergeOutput + outputLotNumber), or each
+ // batch-tracked member gets its own number (lotNumbers).
+ mergeOutput: z.boolean().optional(),
+ outputLotNumber: z.string().trim().min(1).optional().nullable(),
+ lotNumbers: z
+ .array(
+ z.object({
+ jobOperationId: z.string(),
+ lotNumber: z.string().trim().min(1)
+ })
+ )
+ .optional(),
companyId: z.string(),
userId: z.string()
}),
@@ -86,6 +99,10 @@ const payloadValidator = z.discriminatedUnion("type", [
jobOperationId: z.string(),
quantity: z.number().int().min(0),
scrapQuantity: z.number().int().min(0).optional(),
+ // Batch-tracked output: the member's WIP entity to finalize as the
+ // produced lot, and the batch number to stamp on it.
+ trackedEntityId: z.string().optional().nullable(),
+ batchNumber: z.string().optional().nullable(),
// "Not in this run": detach the member back to the schedule instead
// of completing it. Its quantities must be 0.
excluded: z.boolean().optional()
@@ -97,6 +114,68 @@ const payloadValidator = z.discriminatedUnion("type", [
})
]);
+// The produced item + tracking of each member, and its live WIP entity (the
+// entity a member's output lot is finalized from; its readableId is the lot
+// number).
+async function loadMemberOutputs(
+ trx: Transaction<DB>,
+ companyId: string,
+ jobMakeMethodIds: string[]
+) {
+ if (jobMakeMethodIds.length === 0) return new Map();
+ const makeMethods = await trx
+ .selectFrom("jobMakeMethod")
+ .select(["id", "itemId", "requiresBatchTracking"])
+ .where("id", "in", jobMakeMethodIds)
+ .where("companyId", "=", companyId)
+ .execute();
+ const entities = await trx
+ .selectFrom("trackedEntity")
+ .select(["id", "createdAt", sql<string>`"attributes"->>'Job Make Method'`.as("jobMakeMethodId")])
+ .where(sql`"attributes"->>'Job Make Method'`, "in", jobMakeMethodIds)
+ .where("companyId", "=", companyId)
+ .where("status", "not in", ["Consumed", "Scrapped", "Rejected"])
+ .orderBy("createdAt", "asc")
+ .execute();
+ const entityByMakeMethod = new Map<string, string>();
+ for (const e of entities) {
+ if (!entityByMakeMethod.has(e.jobMakeMethodId)) {
+ entityByMakeMethod.set(e.jobMakeMethodId, e.id);
+ }
+ }
+ return new Map(
+ makeMethods.map((m) => [
+ m.id,
+ {
+ itemId: m.itemId as string | null,
+ requiresBatchTracking: Boolean(m.requiresBatchTracking),
+ trackedEntityId: entityByMakeMethod.get(m.id) ?? null
+ }
+ ])
+ );
+}
+
+// A merged batch's members must all produce ONE batch-tracked item: lots of
+// different items can never merge, and an untracked item has no lot at all.
+function assertMergeable(
+ operations: Array<{ jobMakeMethodId: string | null }>,
+ outputs: Map<string, { itemId: string | null; requiresBatchTracking: boolean }>
+) {
+ const items = new Set<string>();
+ for (const op of operations) {
+ const out = op.jobMakeMethodId ? outputs.get(op.jobMakeMethodId) : undefined;
+ if (!out?.requiresBatchTracking || !out.itemId) {
+ throw new Error(
+ "Only operations that produce a batch-tracked item can combine into one lot"
+ );
+ }
+ items.add(out.itemId);
+ }
+ if (items.size > 1) {
+ throw new Error("Lots of different items can't combine into one lot");
+ }
+}
+
async function assertEligible(
trx: Transaction<DB>,
companyId: string,
@@ -195,13 +274,33 @@ async function assertMaterialCompatible(
// (jobOperationId IS NULL). The gate must judge the same materials the
// builder shows, or a visible "must" match could still be refused (and vice
// versa).
+ // Produced item mirrors the builder's candidate `itemReadableId` (the JOB's
+ // item — get_batchable_operations joins item on job.itemId), so the gate and
+ // the builder judge the producedItem dimension by the same value.
const memberOps = await trx
.selectFrom("jobOperation")
- .select(["id", "jobId"])
- .where("id", "in", jobOperationIds)
- .where("companyId", "=", companyId)
+ .innerJoin("job", (join: any) =>
+ join
+ .onRef("job.id", "=", "jobOperation.jobId")
+ .onRef("job.companyId", "=", "jobOperation.companyId")
+ )
+ .leftJoin("item as pi", (join: any) =>
+ join
+ .onRef("pi.id", "=", "job.itemId")
+ .onRef("pi.companyId", "=", "job.companyId")
+ )
+ .select([
+ "jobOperation.id as id",
+ "jobOperation.jobId as jobId",
+ "pi.readableId as producedItemReadableId"
+ ])
+ .where("jobOperation.id", "in", jobOperationIds)
+ .where("jobOperation.companyId", "=", companyId)
.execute();
const jobIdByOp = new Map(memberOps.map((o) => [o.id, o.jobId]));
+ const producedByOp = new Map(
+ memberOps.map((o) => [o.id, o.producedItemReadableId])
+ );
const memberJobIds = [...new Set(memberOps.map((o) => o.jobId))];
const rows = await trx
@@ -250,13 +349,15 @@ async function assertMaterialCompatible(
const byOp = new Map<string, MemberValueSets>();
for (const id of jobOperationIds) {
+ const produced = producedByOp.get(id);
byOp.set(id, {
item: [],
substance: [],
grade: [],
dimension: [],
form: [],
- finish: []
+ finish: [],
+ producedItem: produced ? [produced] : []
});
}
const opsWithLinkedRows = new Set(
@@ -319,6 +420,8 @@ async function completeBatch(
jobOperationId: string;
quantity: number;
scrapQuantity?: number;
+ trackedEntityId?: string | null;
+ batchNumber?: string | null;
excluded?: boolean;
}[];
}
@@ -614,6 +717,80 @@ async function completeBatch(
}
}
+ // Finalize batch-tracked outputs: for each member producing a batch-tracked
+ // item, flip its WIP entity to an Available lot via the lean
+ // jobOperationBatchOutput case (Produce activity + entity flip only — the
+ // productionQuantity rows were written in Phase 1 and the member's materials
+ // were issued above). Idempotent: an already-Available entity is a no-op, so
+ // a resume fast-forwards. Runs BEFORE the Done flip so a failure here leaves
+ // the batch resumable with no member stranded Done without its output lot.
+ const memberOpRows = await client
+ .from("jobOperation")
+ .select("id, jobMakeMethodId")
+ .in("id", memberIds)
+ .eq("companyId", companyId);
+ if (memberOpRows.error) {
+ throw new Error(`Failed to load member operations: ${memberOpRows.error.message}`);
+ }
+ const makeMethodIds = [
+ ...new Set(
+ (memberOpRows.data ?? [])
+ // deno-lint-ignore no-explicit-any
+ .map((o: any) => o.jobMakeMethodId)
+ .filter(Boolean) as string[]
+ )
+ ];
+ const makeMethods = makeMethodIds.length
+ ? await client
+ .from("jobMakeMethod")
+ .select("id, requiresBatchTracking")
+ .in("id", makeMethodIds)
+ .eq("companyId", companyId)
+ : { data: [], error: null };
+ if (makeMethods.error) {
+ throw new Error(`Failed to load make methods: ${makeMethods.error.message}`);
+ }
+ const requiresBatchByMakeMethod = new Map(
+ // deno-lint-ignore no-explicit-any
+ (makeMethods.data ?? []).map((m: any) => [m.id, m.requiresBatchTracking])
+ );
+ const makeMethodByOp = new Map(
+ // deno-lint-ignore no-explicit-any
+ (memberOpRows.data ?? []).map((o: any) => [o.id, o.jobMakeMethodId])
+ );
+
+ const outputTrackedEntityIds: string[] = [];
+ for (const m of members) {
+ const makeMethodId = makeMethodByOp.get(m.jobOperationId);
+ const requiresBatch = makeMethodId
+ ? (requiresBatchByMakeMethod.get(makeMethodId) ?? false)
+ : false;
+ if (!requiresBatch) continue;
+ if (m.quantity <= 0) continue;
+ if (!m.trackedEntityId) {
+ throw new Error(
+ `Operation ${m.jobOperationId} produces a batch-tracked item — its output lot is required`
+ );
+ }
+ const output = await client.functions.invoke("issue", {
+ body: {
+ type: "jobOperationBatchOutput",
+ jobOperationId: m.jobOperationId,
+ trackedEntityId: m.trackedEntityId,
+ quantity: m.quantity,
+ readableId: m.batchNumber ?? null,
+ companyId,
+ userId
+ }
+ });
+ if (output.error) {
+ throw new Error(
+ `Failed to create the output lot for operation ${m.jobOperationId}: ${output.error.message}`
+ );
+ }
+ outputTrackedEntityIds.push(m.trackedEntityId);
+ }
+
// Flip members Done — sync_finish_job_operation readies each member job's next
// operation and completes the job independently. Skip already-Done so a resume
// does not re-fire the trigger.
@@ -658,7 +835,8 @@ async function completeBatch(
completed: members.length,
excluded: excludedIds.length,
memberIds,
- eventIds: glEvents.map((e) => e.id)
+ eventIds: glEvents.map((e) => e.id),
+ outputTrackedEntityIds
};
}
@@ -725,6 +903,52 @@ serve(async (req: Request) => {
// center: the scheduler's batch pre-pass auto-selects the
// earliest-finish candidate (load balancing, like single ops) for
// any Released batch still lacking one, and persists it.
+ const outputs = await loadMemberOutputs(
+ trx,
+ companyId,
+ // deno-lint-ignore no-explicit-any
+ operations.map((o: any) => o.jobMakeMethodId).filter(Boolean)
+ );
+ const mergeOutput = payload.mergeOutput === true;
+ if (mergeOutput) {
+ if (!payload.outputLotNumber) {
+ throw new Error("A combined output needs its lot number");
+ }
+ assertMergeable(operations, outputs);
+ }
+ // Split mode: one number per batch-tracked member, never repeated —
+ // two separate lots sharing a number is exactly the ambiguity the
+ // merge option exists to remove.
+ const lotNumbers = mergeOutput ? [] : (payload.lotNumbers ?? []);
+ const seen = new Set<string>();
+ const lotWrites: Array<{ trackedEntityId: string; lotNumber: string }> =
+ [];
+ for (const entry of lotNumbers) {
+ const op = operations.find(
+ // deno-lint-ignore no-explicit-any
+ (o: any) => o.id === entry.jobOperationId
+ );
+ const out = op?.jobMakeMethodId
+ ? outputs.get(op.jobMakeMethodId)
+ : undefined;
+ if (!out?.requiresBatchTracking || !out.trackedEntityId) {
+ throw new Error(
+ `Operation ${entry.jobOperationId} does not produce a batch-tracked lot`
+ );
+ }
+ const key = entry.lotNumber.toLowerCase();
+ if (seen.has(key)) {
+ throw new Error(
+ `Lot number ${entry.lotNumber} is used twice — give each job its own, or combine them into one lot`
+ );
+ }
+ seen.add(key);
+ lotWrites.push({
+ trackedEntityId: out.trackedEntityId,
+ lotNumber: entry.lotNumber
+ });
+ }
+
const readableId = await getNextSequence(
trx,
"jobOperationBatch",
@@ -740,11 +964,22 @@ serve(async (req: Request) => {
locationId: payload.locationId,
status: payload.release ? "Active" : "Planned",
notes: payload.notes ?? null,
+ mergeOutput,
+ outputLotNumber: mergeOutput ? payload.outputLotNumber : null,
createdBy: userId
})
.returning(["id", "readableId"])
.executeTakeFirstOrThrow();
+ for (const write of lotWrites) {
+ await trx
+ .updateTable("trackedEntity")
+ .set({ readableId: write.lotNumber, updatedBy: userId })
+ .where("id", "=", write.trackedEntityId)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+
const memberUpdate: Record<string, unknown> = {
jobOperationBatchId: batch.id,
updatedBy: userId
@@ -799,7 +1034,7 @@ serve(async (req: Request) => {
throw new Error("The batch has already started — complete it instead");
}
- await assertEligible(
+ const { operations: incoming } = await assertEligible(
trx,
companyId,
payload.jobOperationIds,
@@ -810,10 +1045,23 @@ serve(async (req: Request) => {
// plus the incoming ops together, not the newcomers in isolation.
const existingMembers = await trx
.selectFrom("jobOperation")
- .select("id")
+ .select(["id", "jobMakeMethodId"])
.where("jobOperationBatchId", "=", payload.batchId)
.where("companyId", "=", companyId)
.execute();
+
+ // A combined-output batch stays one item: a newcomer producing
+ // something else could never merge into the planned lot.
+ if (batch.mergeOutput) {
+ const all = [...existingMembers, ...incoming];
+ const outputs = await loadMemberOutputs(
+ trx,
+ companyId,
+ // deno-lint-ignore no-explicit-any
+ all.map((o: any) => o.jobMakeMethodId).filter(Boolean)
+ );
+ assertMergeable(all, outputs);
+ }
await assertMaterialCompatible(trx, companyId, batch.processId, [
// deno-lint-ignore no-explicit-any
...existingMembers.map((m: any) => m.id as string),
@@ -1090,6 +1338,8 @@ serve(async (req: Request) => {
jobOperationId: string;
quantity: number;
scrapQuantity?: number;
+ trackedEntityId?: string | null;
+ batchNumber?: string | null;
}[]
});
break;
diff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.ts
index 6dfc165e40..0a9127f3c1 100644
--- a/packages/database/supabase/functions/create/index.ts
+++ b/packages/database/supabase/functions/create/index.ts
@@ -440,6 +440,9 @@ serve(async (req: Request) => {
case "purchaseOrderFromJob": {
const { jobId, purchaseOrdersBySupplierId } = payload;
+ // The PO each supplier's lines landed on (created or chosen), so a caller
+ // releasing several jobs can put them on one PO per supplier.
+ const purchaseOrderIdsBySupplierId: Record<string, string> = {};
logger.info({ type, jobId, companyId, userId });
try {
@@ -488,7 +491,7 @@ serve(async (req: Request) => {
.from("purchaseOrderLine")
.select("*")
.eq("jobId", jobId)
- .eq(
+ .in(
"jobOperationId",
outsideOperations.map((d) => d.id)
),
@@ -736,6 +739,8 @@ serve(async (req: Request) => {
]);
}
+ purchaseOrderIdsBySupplierId[supplier] = purchaseOrderId;
+
const purchaseOrderLineInserts: Database["public"]["Tables"]["purchaseOrderLine"]["Insert"][] =
[];
@@ -796,7 +801,7 @@ serve(async (req: Request) => {
return errorResponse(err, 500);
}
- return jsonResponse({ success: true });
+ return jsonResponse({ success: true, purchaseOrderIdsBySupplierId });
}
case "receiptDefault": {
const { locationId } = payload;
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.ts
index c5cdeda16e..70feca3bd9 100644
--- a/packages/database/supabase/functions/issue/index.ts
+++ b/packages/database/supabase/functions/issue/index.ts
@@ -1,6 +1,6 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { type CalendarDate, parseDate } from "@internationalized/date";
-import { Transaction } from "kysely";
+import { sql, Transaction } from "kysely";
import { z } from "npm:zod@^4.5.4";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
@@ -19,6 +19,8 @@ import type { Json } from "../lib/types.ts";
import { TrackedEntityAttributes, credit, debit, journalReference } from "../lib/utils.ts";
import { buildBatchSplitRecords } from "../shared/batch-split.ts";
+import { buildBatchMergeRecords } from "../shared/batch-merge.ts";
+import { splitPickAcrossMembers } from "../shared/batch-pick-split.ts";
import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
import { bookAdjustment } from "../shared/post-adjustment.ts";
import { getNextSequence } from "../shared/get-next-sequence.ts";
@@ -903,6 +905,15 @@ const payloadValidator = z.discriminatedUnion("type", [
inspectionId: z.string().optional(),
inspectionSampleId: z.string().optional(),
}),
+ z.object({
+ type: z.literal("jobOperationBatchOutput"),
+ jobOperationId: z.string(),
+ trackedEntityId: z.string(),
+ quantity: z.number(),
+ readableId: z.string().optional().nullable(),
+ companyId: z.string(),
+ userId: z.string(),
+ }),
z.object({
type: z.literal("jobOperationSerialComplete"),
trackedEntityId: z.string(),
@@ -957,6 +968,28 @@ const payloadValidator = z.discriminatedUnion("type", [
companyId: z.string(),
userId: z.string(),
}),
+ z.object({
+ type: z.literal("mergeTrackedEntities"),
+ trackedEntityIds: z.array(z.string()).min(2),
+ readableId: z.string().optional().nullable(),
+ companyId: z.string(),
+ userId: z.string(),
+ }),
+ z.object({
+ type: z.literal("trackedEntitiesToBatch"),
+ batchId: z.string(),
+ itemId: z.string(),
+ children: z.array(
+ z.object({
+ trackedEntityId: z.string(),
+ quantity: z.number(),
+ })
+ ),
+ overrideExpired: z.boolean().optional(),
+ overrideReason: z.string().optional(),
+ companyId: z.string(),
+ userId: z.string(),
+ }),
z.object({
type: z.literal("trackedEntitiesToOperation"),
materialId: z.string().optional(),
@@ -1037,1277 +1070,1595 @@ const payloadValidator = z.discriminatedUnion("type", [
}),
]);
-serve(async (req: Request) => {
- const preflight = corsPreflight(req);
- if (preflight) return preflight;
- const payload = await req.json();
- logger.info({ payload });
- try {
- const validatedPayload = payloadValidator.parse(payload);
+// Shared accounting context for the tracked-consumption paths (the per-op and
+// per-batch cases): whether accounting is enabled, the posting-group defaults,
+// and the active dimension map.
+async function loadConsumeAccountingContext(
+ // deno-lint-ignore no-explicit-any
+ client: any,
+ companyId: string
+) {
+ const [accountingSettings, companyRecord] = await Promise.all([
+ client
+ .from("companySettings")
+ .select("accountingEnabled")
+ .eq("id", companyId)
+ .single(),
+ client.from("company").select("companyGroupId").eq("id", companyId).single(),
+ ]);
+ if (companyRecord.error) throw new Error("Failed to fetch company");
+ const accountingEnabled = accountingSettings.data?.accountingEnabled ?? false;
+
+ const accountDefaults = accountingEnabled
+ ? await getDefaultPostingGroup(client, companyId)
+ : null;
+ if (accountingEnabled && (accountDefaults?.error || !accountDefaults?.data)) {
+ throw new Error("Error getting account defaults");
+ }
- logger.info(validatedPayload);
+ const dimensions = accountingEnabled
+ ? await client
+ .from("dimension")
+ .select("id, entityType")
+ .eq("companyGroupId", companyRecord.data.companyGroupId)
+ .eq("active", true)
+ .in("entityType", ["ItemPostingGroup", "Item", "Location"])
+ : null;
+
+ const dimensionMap = new Map<string, string>();
+ if (dimensions?.data) {
+ for (const dim of dimensions.data) {
+ if (dim.entityType) dimensionMap.set(dim.entityType, dim.id);
+ }
+ }
- const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =
- [];
+ return { accountingEnabled, accountDefaults, dimensionMap };
+}
- switch (validatedPayload.type) {
- case "jobOperation": {
- const { id, companyId, quantity, userId } = validatedPayload;
+// The per-operation tracked-consumption write sequence, extracted verbatim from
+// the trackedEntitiesToOperation case so trackedEntitiesToBatch can run it once
+// per member inside ONE transaction. Reads run against `trx`, so sequential
+// member calls drawing from the same lot see each other's decrements.
+async function consumeTrackedEntitiesIntoOperation(
+ trx: Transaction<DB>,
+ {
+ materialId,
+ jobOperationId,
+ itemId,
+ parentTrackedEntityId,
+ children,
+ jobOperationStepId,
+ unitNumber,
+ overrideExpired,
+ overrideReason,
+ companyId,
+ userId,
+ companyToday,
+ client,
+ accountingEnabled: accountingEnabledTracked,
+ accountDefaults: accountDefaultsTracked,
+ dimensionMap: dimensionMapTracked,
+ }: {
+ materialId?: string;
+ jobOperationId?: string;
+ itemId?: string;
+ parentTrackedEntityId: string;
+ children: { trackedEntityId: string; quantity: number }[];
+ jobOperationStepId?: string;
+ unitNumber?: number;
+ overrideExpired?: boolean;
+ overrideReason?: string | null;
+ companyId: string;
+ userId: string;
+ companyToday: CalendarDate;
+ // deno-lint-ignore no-explicit-any
+ client: any;
+ accountingEnabled: boolean;
+ // deno-lint-ignore no-explicit-any
+ accountDefaults: any;
+ dimensionMap: Map<string, string>;
+ }
+): Promise<{
+ splitEntities: Array<{
+ originalId: string;
+ newId: string;
+ readableId: string;
+ quantity: number;
+ remainingQuantity: number;
+ }>;
+ warning: string | undefined;
+}> {
+ let expiredWarning: string | undefined;
- const client = await requirePermissions(req, companyId, userId, { update: "production" });
+ const trackedEntities = await trx
+ .selectFrom("trackedEntity")
+ .where(
+ "id",
+ "in",
+ children.map((child) => child.trackedEntityId)
+ )
+ .selectAll()
+ .execute();
- const [accountingSettings, companyRecord] = await Promise.all([
- client
- .from("companySettings")
- .select("accountingEnabled")
- .eq("id", companyId)
- .single(),
- client.from("company").select("companyGroupId").eq("id", companyId).single(),
- ]);
- if (companyRecord.error) throw new Error("Failed to fetch company");
- const accountingEnabled = accountingSettings.data?.accountingEnabled ?? false;
+ const itemLedgers = await trx
+ .selectFrom("itemLedger")
+ .where("trackedEntityId", "in", [
+ ...children.map((child) => child.trackedEntityId),
+ ])
+ .orderBy("createdBy", "desc")
+ .selectAll()
+ .execute();
- const accountDefaults = accountingEnabled
- ? await getDefaultPostingGroup(client, companyId)
- : null;
- if (accountingEnabled && (accountDefaults?.error || !accountDefaults?.data)) {
- throw new Error("Error getting account defaults");
- }
+ if (trackedEntities.length !== children.length) {
+ throw new Error("Tracked entities not found");
+ }
- const dimensions = accountingEnabled
- ? await client
- .from("dimension")
- .select("id, entityType")
- .eq("companyGroupId", companyRecord.data.companyGroupId)
- .eq("active", true)
- .in("entityType", ["ItemPostingGroup", "Item", "Location"])
- : null;
+ if (trackedEntities.some((entity) => entity.status !== "Available")) {
+ throw new Error("Tracked entities are not available");
+ }
- const dimensionMap = new Map<string, string>();
- if (dimensions?.data) {
- for (const dim of dimensions.data) {
- if (dim.entityType) dimensionMap.set(dim.entityType, dim.id);
+ // Expiry policy gate. Reads companySettings.inventoryShelfLife.
+ const expiredPolicy = await getExpiredEntityPolicy(trx, companyId);
+ const expiredCheck = checkExpiredEntities(
+ trackedEntities.map((e) => ({
+ id: e.id,
+ expirationDate: e.expirationDate,
+ })),
+ expiredPolicy,
+ { allowed: !!overrideExpired, reason: overrideReason ?? null },
+ companyToday
+ );
+ if (!expiredCheck.ok) {
+ throw new Error(expiredCheck.reason);
+ }
+ if (expiredCheck.warning) {
+ expiredWarning = expiredCheck.warning;
}
- }
- await db.transaction().execute(async (trx) => {
- await issueJobOperationMaterials(trx, {
- jobOperationId: id,
- quantity,
- companyId,
- userId,
- accountingEnabled,
- accountDefaults: accountDefaults?.data ? accountDefaults : null,
- dimensionMap,
- client,
- db,
- });
- });
+ let jobMaterial: Awaited<
+ ReturnType<
+ ReturnType<typeof trx.selectFrom<"jobMaterial">>["selectAll"]
+ >
+ >[0] | undefined;
+ let actualMaterialId: string | undefined = materialId;
+ const firstTrackedEntity = trackedEntities[0];
- break;
- }
- case "jobOperationBatchComplete": {
- const { trackedEntityId, companyId, userId, ...row } = validatedPayload;
- const client = await requirePermissions(req, companyId, userId, { update: "production" });
+ if (materialId) {
+ // Existing behavior: fetch the jobMaterial
+ jobMaterial = await trx
+ .selectFrom("jobMaterial")
+ .where("id", "=", materialId)
+ .selectAll()
+ .executeTakeFirst();
- const [jobOperation, productionQuantities] = await Promise.all([
- client
- .from("jobOperation")
- .select("*")
- .eq("id", row.jobOperationId)
- .single(),
- client
- .from("productionQuantity")
- .select("*")
- .eq("jobOperationId", row.jobOperationId)
- .eq("type", "Production"),
- ]);
+ // Check if any tracked entity has a different sourceDocumentId than the material's itemId
+ if (
+ firstTrackedEntity &&
+ jobMaterial &&
+ firstTrackedEntity.sourceDocumentId !== jobMaterial.itemId
+ ) {
+ // Create a new jobMaterial for the tracked entity's item
+ const totalChildQuantity = children.reduce((sum, child) => {
+ return sum + Number(child.quantity);
+ }, 0);
- if (!jobOperation.data || !jobOperation.data.jobMakeMethodId) {
- throw new Error("Job operation not found");
- }
+ const itemCost = await trx
+ .selectFrom("itemCost")
+ .where("itemId", "=", firstTrackedEntity.sourceDocumentId!)
+ .select("unitCost")
+ .executeTakeFirst();
- const [accountingSettingsBatch, companyRecordBatch] = await Promise.all([
- client
- .from("companySettings")
- .select("accountingEnabled")
- .eq("id", companyId)
- .single(),
- client.from("company").select("companyGroupId").eq("id", companyId).single(),
- ]);
- if (companyRecordBatch.error) throw new Error("Failed to fetch company");
- const accountingEnabledBatch = accountingSettingsBatch.data?.accountingEnabled ?? false;
+ const newJobMaterial = await trx
+ .insertInto("jobMaterial")
+ .values({
+ companyId,
+ createdBy: userId,
+ description: firstTrackedEntity.sourceDocumentReadableId ?? "",
+ estimatedQuantity: 0,
+ itemId: firstTrackedEntity.sourceDocumentId!,
+ jobId: jobMaterial.jobId!,
+ jobMakeMethodId: jobMaterial.jobMakeMethodId,
+ jobOperationId: jobMaterial.jobOperationId,
+ itemType: jobMaterial.itemType,
+ methodType: jobMaterial.methodType,
+ quantity: 0,
+ quantityIssued: totalChildQuantity,
+ requiresBatchTracking: jobMaterial.requiresBatchTracking,
+ requiresSerialTracking: jobMaterial.requiresSerialTracking,
+ unitCost: itemCost?.unitCost ?? 0,
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
- const accountDefaultsBatch = accountingEnabledBatch
- ? await getDefaultPostingGroup(client, companyId)
- : null;
- if (accountingEnabledBatch && (accountDefaultsBatch?.error || !accountDefaultsBatch?.data)) {
- throw new Error("Error getting account defaults");
- }
+ actualMaterialId = newJobMaterial.id!;
- const dimensionsBatch = accountingEnabledBatch
- ? await client
- .from("dimension")
- .select("id, entityType")
- .eq("companyGroupId", companyRecordBatch.data.companyGroupId)
- .eq("active", true)
- .in("entityType", ["ItemPostingGroup", "Item", "Location"])
- : null;
+ // Fetch the newly created jobMaterial
+ jobMaterial = await trx
+ .selectFrom("jobMaterial")
+ .where("id", "=", actualMaterialId)
+ .selectAll()
+ .executeTakeFirstOrThrow();
+ }
+ } else if (jobOperationId && itemId) {
+ // New behavior: create a jobMaterial on the fly
+ const jobOperation = await trx
+ .selectFrom("jobOperation")
+ .where("id", "=", jobOperationId)
+ .select(["jobId", "jobMakeMethodId"])
+ .executeTakeFirst();
- const dimensionMapBatch = new Map<string, string>();
- if (dimensionsBatch?.data) {
- for (const dim of dimensionsBatch.data) {
- if (dim.entityType) dimensionMapBatch.set(dim.entityType, dim.id);
- }
- }
+ if (!jobOperation) {
+ throw new Error("Job operation not found");
+ }
- await db.transaction().execute(async (trx) => {
- await trx
- .insertInto("productionQuantity")
- .values({
- ...row,
- type: "Production",
- companyId,
- createdBy: userId,
- })
- .executeTakeFirst();
+ const item = await trx
+ .selectFrom("item")
+ .where("id", "=", itemId)
+ .select(["name", "type", "itemTrackingType", "defaultMethodType"])
+ .executeTakeFirst();
- const trackedEntity = await trx
- .selectFrom("trackedEntity")
- .where("id", "=", trackedEntityId)
- .selectAll()
- .executeTakeFirst();
+ if (!item) {
+ throw new Error("Item not found");
+ }
- if (!trackedEntity) {
- throw new Error("Tracked entity not found");
- }
+ const totalChildQuantity = children.reduce((sum, child) => {
+ return sum + Number(child.quantity);
+ }, 0);
- if (trackedEntity.status !== "Consumed") {
- const activityId = nanoid();
- await trx
- .insertInto("trackedActivity")
- .values({
- id: activityId,
- type: "Produce",
- sourceDocument: "Job Operation",
- sourceDocumentId: row.jobOperationId,
- attributes: {
- "Job Operation": row.jobOperationId,
- Employee: userId,
- Quantity: row.quantity,
- },
- companyId,
- createdBy: userId,
- })
- .execute();
+ const itemCost = await trx
+ .selectFrom("itemCost")
+ .where("itemId", "=", itemId)
+ .select("unitCost")
+ .executeTakeFirst();
- await trx
- .insertInto("trackedActivityOutput")
+ const newJobMaterial = await trx
+ .insertInto("jobMaterial")
.values({
- trackedActivityId: activityId,
- trackedEntityId: trackedEntityId,
- quantity: row.quantity,
companyId,
createdBy: userId,
+ description: item.name ?? "",
+ estimatedQuantity: 0,
+ itemId: itemId,
+ jobId: jobOperation.jobId!,
+ jobMakeMethodId: jobOperation.jobMakeMethodId,
+ jobOperationId: jobOperationId,
+ itemType: item.type ?? "Part",
+ methodType: item.defaultMethodType ?? "Pull from Inventory",
+ quantity: 0,
+ quantityIssued: totalChildQuantity,
+ requiresBatchTracking: item.itemTrackingType === "Batch",
+ requiresSerialTracking: item.itemTrackingType === "Serial",
+ unitCost: itemCost?.unitCost ?? 0,
})
- .execute();
-
- const previousProductionQuantities =
- productionQuantities?.data?.reduce((acc, curr) => {
- const quantity = Number(curr.quantity);
- return acc + quantity;
- }, 0) ?? 0;
-
- // Update the current trackedEntity to Complete
- await trx
- .updateTable("trackedEntity")
- .set({
- status: "Available",
- quantity: previousProductionQuantities + row.quantity,
- })
- .where("id", "=", trackedEntityId)
- .execute();
- }
-
- await issueJobOperationMaterials(trx, {
- jobOperationId: row.jobOperationId,
- quantity: row.quantity,
- companyId,
- userId,
- accountingEnabled: accountingEnabledBatch,
- accountDefaults: accountDefaultsBatch?.data ? accountDefaultsBatch : null,
- dimensionMap: dimensionMapBatch,
- client,
- db,
- });
- });
-
- return jsonResponse({
- success: true,
- });
- }
- case "jobOperationSerialComplete": {
- const { trackedEntityId, companyId, userId, ...row } = validatedPayload;
- const client = await requirePermissions(req, companyId, userId, { update: "production" });
+ .returning("id")
+ .executeTakeFirstOrThrow();
- const jobOperation = await client
- .from("jobOperation")
- .select("*")
- .eq("id", row.jobOperationId)
- .single();
- if (!jobOperation.data || !jobOperation.data.jobMakeMethodId) {
- throw new Error("Job operation not found");
- }
+ actualMaterialId = newJobMaterial.id!;
- const trackedEntities = await client
- .from("trackedEntity")
- .select("*")
- .eq("attributes->>Job Make Method", jobOperation.data.jobMakeMethodId)
- .order("createdAt", { ascending: true });
+ // Scope this unplanned tracked part to the step it was issued on
+ // (assembly view), so it shows on that step rather than as General.
+ if (jobOperationStepId) {
+ await trx
+ .insertInto("jobMaterialStep")
+ .values({
+ jobMaterialId: actualMaterialId,
+ jobOperationStepId,
+ })
+ .onConflict((oc) => oc.doNothing())
+ .execute();
+ }
- if (!trackedEntities.data || trackedEntities.data.length === 0) {
- throw new Error("Tracked entities not found");
- }
+ // Fetch the newly created jobMaterial
+ jobMaterial = await trx
+ .selectFrom("jobMaterial")
+ .where("id", "=", actualMaterialId)
+ .selectAll()
+ .executeTakeFirstOrThrow();
+ }
- const relatedTrackedEntities = trackedEntities.data.filter(
- (trackedEntity) =>
- `Operation ${row.jobOperationId}` in
- (trackedEntity.attributes as TrackedEntityAttributes)
- );
+ if (!jobMaterial) {
+ throw new Error("Job material not found");
+ }
- const [accountingSettingsSerial, companyRecordSerial] = await Promise.all([
- client
- .from("companySettings")
- .select("accountingEnabled")
- .eq("id", companyId)
- .single(),
- client.from("company").select("companyGroupId").eq("id", companyId).single(),
- ]);
- if (companyRecordSerial.error) throw new Error("Failed to fetch company");
- const accountingEnabledSerial = accountingSettingsSerial.data?.accountingEnabled ?? false;
+ // Get item details
+ const item = await trx
+ .selectFrom("item")
+ .where("id", "=", jobMaterial?.itemId!)
+ .select(["readableIdWithRevision"])
+ .executeTakeFirst();
- const accountDefaultsSerial = accountingEnabledSerial
- ? await getDefaultPostingGroup(client, companyId)
- : null;
- if (accountingEnabledSerial && (accountDefaultsSerial?.error || !accountDefaultsSerial?.data)) {
- throw new Error("Error getting account defaults");
- }
+ // Get job location
+ const job = await trx
+ .selectFrom("job")
+ .select(["id", "locationId"])
+ .where("id", "=", jobMaterial?.jobId!)
+ .executeTakeFirst();
- const dimensionsSerial = accountingEnabledSerial
- ? await client
- .from("dimension")
- .select("id, entityType")
- .eq("companyGroupId", companyRecordSerial.data.companyGroupId)
- .eq("active", true)
- .in("entityType", ["ItemPostingGroup", "Item", "Location"])
- : null;
+ // Get parent tracked entity details
+ const parentTrackedEntity = await trx
+ .selectFrom("trackedEntity")
+ .where("id", "=", parentTrackedEntityId)
+ .select([
+ "id",
+ "sourceDocumentId",
+ "quantity",
+ "attributes",
+ "status",
+ ])
+ .executeTakeFirst();
- const dimensionMapSerial = new Map<string, string>();
- if (dimensionsSerial?.data) {
- for (const dim of dimensionsSerial.data) {
- if (dim.entityType) dimensionMapSerial.set(dim.entityType, dim.id);
+ if (!parentTrackedEntity) {
+ throw new Error("Parent tracked entity not found");
}
- }
- let newEntityId: string | undefined;
- await db.transaction().execute(async (trx) => {
+ // Create tracked activity
+ const activityId = nanoid();
await trx
- .insertInto("productionQuantity")
+ .insertInto("trackedActivity")
.values({
- ...row,
- type: "Production",
+ id: activityId,
+ type: "Consume",
+ sourceDocument: "Job Material",
+ sourceDocumentId: actualMaterialId,
+ sourceDocumentReadableId: item?.readableIdWithRevision ?? "",
+ attributes: {
+ Job: job?.id!,
+ "Job Make Method": jobMaterial?.jobMakeMethodId!,
+ "Job Material": jobMaterial?.id!,
+ Employee: userId,
+ // Assembly view: which step + 1-based unit this consume was for, so
+ // the MES can attribute issued quantities per-unit even for a batch
+ // parent (where all units share one lot entity).
+ ...(jobOperationStepId
+ ? { "Job Operation Step": jobOperationStepId }
+ : {}),
+ ...(unitNumber !== undefined ? { Unit: unitNumber } : {}),
+ },
companyId,
createdBy: userId,
})
- .executeTakeFirst();
+ .execute();
- const trackedEntity = await trx
- .selectFrom("trackedEntity")
- .where("id", "=", trackedEntityId)
- .selectAll()
- .executeTakeFirst();
+ await trx
+ .insertInto("trackedActivityOutput")
+ .values({
+ trackedActivityId: activityId,
+ trackedEntityId: parentTrackedEntityId,
+ quantity: parentTrackedEntity.quantity,
+ companyId,
+ createdBy: userId,
+ })
+ .execute();
- if (!trackedEntity) {
- throw new Error("Tracked entity not found");
- }
+ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =
+ [];
+ const trackedActivityInputs: Database["public"]["Tables"]["trackedActivityInput"]["Insert"][] =
+ [];
- if (trackedEntity.status !== "Consumed") {
- const activityId = nanoid();
- await trx
- .insertInto("trackedActivity")
- .values({
- id: activityId,
- type: "Complete",
- sourceDocument: "Job Operation",
- sourceDocumentId: row.jobOperationId,
- attributes: {
- "Job Operation": row.jobOperationId,
- Employee: userId,
- },
- companyId,
- createdBy: userId,
- })
- .execute();
+ const splitEntities: Array<{
+ originalId: string;
+ newId: string;
+ readableId: string;
+ quantity: number;
+ remainingQuantity: number;
+ }> = [];
- await trx
- .insertInto("trackedActivityOutput")
- .values({
- trackedActivityId: activityId,
- trackedEntityId: trackedEntityId,
- quantity: 1,
+ // Process each child tracked entity
+ for (const child of children) {
+ const trackedEntity = trackedEntities.find(
+ (entity) => entity.id === child.trackedEntityId
+ );
+ if (!trackedEntity) {
+ throw new Error("Tracked entity not found");
+ }
+ const { trackedEntityId, quantity } = child;
+
+ // Partial consume → split: the lineside entity keeps its id and
+ // is decremented; a NEW child entity carries the consumed
+ // quantity. EVERYTHING below (Consumed status, Consume input,
+ // Consumption ledger) books against the child — flipping the
+ // entity half without the ledger half would double-count on-hand.
+ let consumedEntityId = trackedEntityId;
+ if (Number(trackedEntity.quantity) !== quantity) {
+ const consumedChildId = nanoid();
+ consumedEntityId = consumedChildId;
+
+ const split = buildBatchSplitRecords({
+ parent: {
+ id: trackedEntity.id!,
+ readableId: trackedEntity.readableId,
+ quantity: Number(trackedEntity.quantity),
+ sourceDocument: trackedEntity.sourceDocument,
+ sourceDocumentId: trackedEntity.sourceDocumentId,
+ sourceDocumentReadableId:
+ trackedEntity.sourceDocumentReadableId,
+ itemId:
+ trackedEntity.itemId ?? trackedEntity.sourceDocumentId,
+ expirationDate: trackedEntity.expirationDate ?? null,
+ attributes: trackedEntity.attributes as Record<
+ string,
+ unknown
+ > | null
+ },
+ drawQuantity: quantity,
+ childId: consumedChildId,
+ splitActivityId: nanoid(),
+ activitySourceDocument: "Job Material",
+ activitySourceDocumentId: actualMaterialId,
+ bin: {
+ storageUnitId: resolveTrackedEntityBin(
+ itemLedgers,
+ trackedEntityId
+ ),
+ locationId: job?.locationId ?? null
+ },
+ itemLedgerItemId: trackedEntity.sourceDocumentId,
companyId,
- createdBy: userId,
- })
- .execute();
+ userId,
+ postingDate: companyToday.toString(),
+ // Created Available; the shared status update below flips the
+ // child to Consumed in the same transaction.
+ childStatus: "Available",
+ extraChildAttributes: {
+ ...(jobOperationStepId
+ ? { "Job Operation Step": jobOperationStepId }
+ : {}),
+ ...(unitNumber !== undefined ? { Unit: unitNumber } : {})
+ }
+ });
+
+ // Track split entity for the MES confirmation: quantity = what
+ // was consumed (the child), remainingQuantity = what the
+ // surviving lineside entity still holds.
+ splitEntities.push({
+ originalId: trackedEntityId,
+ newId: consumedChildId,
+ readableId: trackedEntity.sourceDocumentReadableId ?? "",
+ quantity,
+ remainingQuantity: split.parentUpdate.quantity,
+ });
+
+ await trx
+ .insertInto("trackedActivity")
+ .values(split.activityInsert)
+ .execute();
+
+ await trx
+ .insertInto("trackedEntity")
+ .values(split.childEntityInsert)
+ .execute();
+
+ await trx
+ .insertInto("trackedActivityInput")
+ .values(split.activityInputInsert)
+ .execute();
+
+ await trx
+ .insertInto("trackedActivityOutput")
+ .values(split.activityOutputInsert)
+ .execute();
+
+ await trx
+ .updateTable("trackedEntity")
+ .set(split.parentUpdate)
+ .where("id", "=", trackedEntityId)
+ .execute();
+
+ // MTO skips ONLY the ledger inserts; entity/activity writes
+ // above still happen.
+ if (jobMaterial?.methodType !== "Make to Order") {
+ itemLedgerInserts.push(...split.ledgerInserts);
+ }
+ }
+
+ // Consume the drawn entity — the split child, or the whole
+ // entity on a full draw.
await trx
.updateTable("trackedEntity")
.set({
- status: "Available",
- quantity: 1,
- attributes: {
- ...(trackedEntity.attributes as TrackedEntityAttributes),
- [`Operation ${row.jobOperationId}`]:
- relatedTrackedEntities.length + 1,
- },
+ status: "Consumed",
})
- .where("id", "=", trackedEntityId)
+ .where("id", "=", consumedEntityId)
.execute();
- }
- if (
- trackedEntities.data.length <
- (jobOperation.data.operationQuantity ?? 0)
- ) {
- // Number this lazily-spawned unit from the item's serial sequence, if
- // one is configured. This unit wasn't part of the initial pre-split at
- // job creation (e.g. the job quantity was increased afterwards, or the
- // sequence was configured later), so it would otherwise be created with
- // a null readableId. Resolve the job's location for the %{location}
- // token; the reservation runs in this transaction, atomic with the spawn.
- let spawnReadableId: string | null = null;
- if (trackedEntity.itemId) {
- let locationCode: string | null = null;
- let locationName: string | null = null;
- const jobIdForLocation = (
- trackedEntity.attributes as Record<string, unknown>
- ).Job;
- if (typeof jobIdForLocation === "string") {
- const jobRow = await client
- .from("job")
- .select("locationId")
- .eq("id", jobIdForLocation)
- .eq("companyId", companyId)
- .single();
- if (jobRow.data?.locationId) {
- const loc = await client
- .from("location")
- .select("code, name")
- .eq("id", jobRow.data.locationId)
- .eq("companyId", companyId)
- .single();
- locationCode = loc.data?.code ?? null;
- locationName = loc.data?.name ?? null;
- }
- }
- const spawnSerials = await getNextSerialNumbers(trx, {
- itemId: trackedEntity.itemId,
- companyId,
- count: 1,
- locationCode,
- locationName,
- });
- spawnReadableId = spawnSerials[0] ?? null;
- }
+ trackedActivityInputs.push({
+ trackedActivityId: activityId,
+ trackedEntityId: consumedEntityId,
+ quantity,
+ companyId,
+ createdBy: userId,
+ });
- // Create a new trackedEntity with the same attributes but status = Reserved
- const newTrackedEntityResult = await trx
- .insertInto("trackedEntity")
- .values({
- sourceDocument: trackedEntity.sourceDocument,
- sourceDocumentId: trackedEntity.sourceDocumentId,
- sourceDocumentReadableId:
- trackedEntity.sourceDocumentReadableId,
- quantity: 1,
- status: "Reserved",
- attributes: trackedEntity.attributes,
- itemId: trackedEntity.itemId ?? null,
- expirationDate: trackedEntity.expirationDate ?? null,
- readableId: spawnReadableId,
+ if (jobMaterial?.methodType !== "Make to Order") {
+ itemLedgerInserts.push({
+ entryType: "Consumption",
+ documentType: "Job Consumption",
+ documentId: job?.id!,
companyId,
+ itemId: trackedEntity.sourceDocumentId,
+ quantity: -quantity,
+ locationId: job?.locationId,
+ // The split child has no rows in the pre-transaction ledger
+ // snapshot — it sits at the parent's resolved bin.
+ storageUnitId: resolveTrackedEntityBin(itemLedgers, trackedEntityId),
+ trackedEntityId: consumedEntityId,
createdBy: userId,
- })
- .returning(["id"])
- .executeTakeFirst();
+ });
+ }
+ }
- newEntityId = newTrackedEntityResult?.id;
+ if (trackedActivityInputs.length > 0) {
+ await trx
+ .insertInto("trackedActivityInput")
+ .values(trackedActivityInputs)
+ .execute();
}
- await issueJobOperationMaterials(trx, {
- jobOperationId: row.jobOperationId,
- quantity: row.quantity,
- companyId,
- userId,
- accountingEnabled: accountingEnabledSerial,
- accountDefaults: accountDefaultsSerial?.data ? accountDefaultsSerial : null,
- dimensionMap: dimensionMapSerial,
- client,
- db,
- });
- });
+ if (itemLedgerInserts.length > 0) {
+ await trx
+ .insertInto("itemLedger")
+ .values(itemLedgerInserts)
+ .execute();
- return jsonResponse({
- success: true,
- newTrackedEntityId: newEntityId,
- });
- }
- case "jobOperationScrap": {
- const {
- jobOperationId,
- quantity,
- scrapReasonId,
- trackedEntityId: scrapEntityId,
- notes,
- laborProductionEventId,
- machineProductionEventId,
- setupProductionEventId,
- companyId,
- userId,
- } = validatedPayload;
- const client = await requirePermissions(req, companyId, userId, {
- update: "production",
- });
+ // Update pickMethod defaultStorageUnitId if needed for each inserted ledger
+ for (const ledger of itemLedgerInserts) {
+ await updatePickMethodDefaultStorageUnitIfNeeded(
+ trx,
+ ledger.itemId,
+ ledger.locationId,
+ ledger.storageUnitId,
+ companyId,
+ userId
+ );
+ }
+ }
- const operationRes = await client
- .from("jobOperation")
- .select("*")
- .eq("id", jobOperationId)
- .eq("companyId", companyId)
- .single();
- const operation = operationRes.data;
- if (!operation || !operation.jobMakeMethodId) {
- throw new Error("Job operation not found");
- }
+ if (accountingEnabledTracked && accountDefaultsTracked?.data && itemLedgerInserts.length > 0) {
+ const consumptionEntries = itemLedgerInserts
+ .filter((l) => l.entryType === "Consumption")
+ .map((l) => ({ itemId: l.itemId as string, quantity: Number(l.quantity) }));
- const [
- makeMethodRes,
- jobRes,
- trackedEntitiesRes,
- accountingSettingsScrapOp,
- companyRecordScrapOp,
- ] = await Promise.all([
- client
- .from("jobMakeMethod")
- .select(
- "id, itemId, requiresSerialTracking, requiresBatchTracking, parentMaterialId"
- )
- .eq("id", operation.jobMakeMethodId)
- .eq("companyId", companyId)
- .single(),
- client
- .from("job")
- .select("id, jobId, locationId")
- .eq("id", operation.jobId)
- .eq("companyId", companyId)
- .single(),
- client
- .from("trackedEntity")
- .select("id")
- .eq("attributes->>Job Make Method", operation.jobMakeMethodId)
- .eq("companyId", companyId),
+ if (consumptionEntries.length > 0) {
+ await createMaterialWipEntries(trx, {
+ consumptionLedgers: consumptionEntries,
+ jobId: job?.id!,
+ operationId: jobMaterial?.jobOperationId ?? actualMaterialId!,
+ description: "Tracked Entity Material Issue",
+ wipAccount: accountDefaultsTracked.data.workInProgressAccount,
+ rawMaterialsAccount: accountDefaultsTracked.data.rawMaterialsAccount,
+ finishedGoodsAccount: accountDefaultsTracked.data.finishedGoodsAccount,
+ dimensionMap: dimensionMapTracked,
+
+ jobLocationId: job?.locationId ?? null,
+ client,
+ db,
+ companyId,
+ userId,
+ });
+ }
+ }
+
+ const totalChildQuantity = children.reduce((sum, child) => {
+ return sum + Number(child.quantity);
+ }, 0);
+
+ // Only update if we didn't create a new jobMaterial (in which case it's already set)
+ if (actualMaterialId === materialId) {
+ const currentQuantityIssued =
+ Number(jobMaterial?.quantityIssued) || 0;
+ const newQuantityIssued =
+ currentQuantityIssued + totalChildQuantity;
+
+ await trx
+ .updateTable("jobMaterial")
+ .set({
+ quantityIssued: newQuantityIssued,
+ })
+ .where("id", "=", actualMaterialId)
+ .execute();
+
+ logger.info("Job material quantity updated", {
+ materialId: actualMaterialId,
+ newQuantityIssued,
+ });
+ }
+
+
+ return { splitEntities, warning: expiredWarning };
+}
+
+
+// The Produce half of a batch-tracked operation completion — the activity +
+// entity flip EXTRACTED from jobOperationBatchComplete, so the batch-operations
+// Phase 2 (jobOperationBatchOutput) can finalize a member's output WITHOUT that
+// case's productionQuantity insert (batch Phase 1 already recorded it) and
+// WITHOUT its backflush (the batch's own issue step already ran).
+async function produceBatchOutput(
+ trx: Transaction<DB>,
+ {
+ jobOperationId,
+ trackedEntityId,
+ producedQuantity,
+ totalQuantity,
+ companyId,
+ userId,
+ }: {
+ jobOperationId: string;
+ trackedEntityId: string;
+ producedQuantity: number;
+ totalQuantity: number;
+ companyId: string;
+ userId: string;
+ }
+) {
+ const trackedEntity = await trx
+ .selectFrom("trackedEntity")
+ .where("id", "=", trackedEntityId)
+ .where("companyId", "=", companyId)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (!trackedEntity) {
+ throw new Error("Tracked entity not found");
+ }
+
+ if (trackedEntity.status !== "Consumed") {
+ const activityId = nanoid();
+ await trx
+ .insertInto("trackedActivity")
+ .values({
+ id: activityId,
+ type: "Produce",
+ sourceDocument: "Job Operation",
+ sourceDocumentId: jobOperationId,
+ attributes: {
+ "Job Operation": jobOperationId,
+ Employee: userId,
+ Quantity: producedQuantity,
+ },
+ companyId,
+ createdBy: userId,
+ })
+ .execute();
+
+ await trx
+ .insertInto("trackedActivityOutput")
+ .values({
+ trackedActivityId: activityId,
+ trackedEntityId: trackedEntityId,
+ quantity: producedQuantity,
+ companyId,
+ createdBy: userId,
+ })
+ .execute();
+
+ // Update the current trackedEntity to Complete
+ await trx
+ .updateTable("trackedEntity")
+ .set({
+ status: "Available",
+ quantity: totalQuantity,
+ })
+ .where("id", "=", trackedEntityId)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+}
+
+serve(async (req: Request) => {
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
+ const payload = await req.json();
+ logger.info({ payload });
+
+ try {
+ const validatedPayload = payloadValidator.parse(payload);
+
+ logger.info(validatedPayload);
+
+ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =
+ [];
+
+ switch (validatedPayload.type) {
+ case "jobOperation": {
+ const { id, companyId, quantity, userId } = validatedPayload;
+
+ const client = await requirePermissions(req, companyId, userId, { update: "production" });
+
+ const [accountingSettings, companyRecord] = await Promise.all([
client
.from("companySettings")
.select("accountingEnabled")
.eq("id", companyId)
.single(),
- client
- .from("company")
- .select("companyGroupId")
- .eq("id", companyId)
- .single(),
+ client.from("company").select("companyGroupId").eq("id", companyId).single(),
]);
- if (makeMethodRes.error || !makeMethodRes.data) {
- throw new Error("Job make method not found");
- }
- if (jobRes.error || !jobRes.data) throw new Error("Job not found");
- if (companyRecordScrapOp.error) {
- throw new Error("Failed to fetch company");
- }
- const makeMethod = makeMethodRes.data;
- const job = jobRes.data;
- const existingEntityCount = trackedEntitiesRes.data?.length ?? 0;
+ if (companyRecord.error) throw new Error("Failed to fetch company");
+ const accountingEnabled = accountingSettings.data?.accountingEnabled ?? false;
- const accountingEnabledScrapOp =
- accountingSettingsScrapOp.data?.accountingEnabled ?? false;
- const accountDefaultsScrapOp = accountingEnabledScrapOp
+ const accountDefaults = accountingEnabled
? await getDefaultPostingGroup(client, companyId)
: null;
- if (
- accountingEnabledScrapOp &&
- (accountDefaultsScrapOp?.error || !accountDefaultsScrapOp?.data)
- ) {
+ if (accountingEnabled && (accountDefaults?.error || !accountDefaults?.data)) {
throw new Error("Error getting account defaults");
}
- const dimensionsScrapOp = accountingEnabledScrapOp
+ const dimensions = accountingEnabled
? await client
.from("dimension")
.select("id, entityType")
- .eq("companyGroupId", companyRecordScrapOp.data.companyGroupId)
+ .eq("companyGroupId", companyRecord.data.companyGroupId)
.eq("active", true)
- .in("entityType", [
- "ItemPostingGroup",
- "Item",
- "Location",
- "ScrapReason",
- "WorkCenter",
- "Employee",
- ])
+ .in("entityType", ["ItemPostingGroup", "Item", "Location"])
: null;
- const dimensionMapScrapOp = new Map<string, string>();
- if (dimensionsScrapOp?.data) {
- for (const dim of dimensionsScrapOp.data) {
- if (dim.entityType) dimensionMapScrapOp.set(dim.entityType, dim.id);
- }
- }
- const isSerial = makeMethod.requiresSerialTracking === true;
- if (isSerial && !scrapEntityId) {
- throw new Error("trackedEntityId is required to scrap a serial unit");
- }
- if (isSerial && quantity !== 1) {
- throw new Error("Serial units are scrapped one at a time");
+ const dimensionMap = new Map<string, string>();
+ if (dimensions?.data) {
+ for (const dim of dimensions.data) {
+ if (dim.entityType) dimensionMap.set(dim.entityType, dim.id);
+ }
}
- const todayScrapOp = datetime
- .today(await getCompanyTimeZone(client, companyId))
- .toString();
-
- let newEntityId: string | undefined;
await db.transaction().execute(async (trx) => {
- // 1. Scrap quantity record. The quantity-sync interceptor aggregates
- // quantityScrapped; scrap no longer counts toward the auto-Done
- // target (20260807090629), so the operation stays open until the
- // good quantity is actually made.
- await trx
- .insertInto("productionQuantity")
- .values({
- jobOperationId,
- quantity,
- type: "Scrap",
- scrapReasonId,
- notes,
- laborProductionEventId,
- machineProductionEventId,
- setupProductionEventId,
- companyId,
- createdBy: userId,
- })
- .executeTakeFirst();
-
- // 2. Backflush the scrapped units\' BOM for this operation — material
- // cost enters WIP exactly as a completion would (NetSuite "Issue
- // for Scrap"); the WIP→scrap journal below relieves it.
- const backflush = await issueJobOperationMaterials(trx, {
- jobOperationId,
+ await issueJobOperationMaterials(trx, {
+ jobOperationId: id,
quantity,
companyId,
userId,
- accountingEnabled: accountingEnabledScrapOp,
- accountDefaults: accountDefaultsScrapOp?.data
- ? accountDefaultsScrapOp
+ accountingEnabled,
+ accountDefaults: accountDefaults?.data ? accountDefaults : null,
+ dimensionMap,
+ client,
+ db,
+ });
+ });
+
+ break;
+ }
+ case "jobOperationBatchComplete": {
+ const { trackedEntityId, companyId, userId, ...row } = validatedPayload;
+ const client = await requirePermissions(req, companyId, userId, { update: "production" });
+
+ const [jobOperation, productionQuantities] = await Promise.all([
+ client
+ .from("jobOperation")
+ .select("*")
+ .eq("id", row.jobOperationId)
+ .single(),
+ client
+ .from("productionQuantity")
+ .select("*")
+ .eq("jobOperationId", row.jobOperationId)
+ .eq("type", "Production"),
+ ]);
+
+ if (!jobOperation.data || !jobOperation.data.jobMakeMethodId) {
+ throw new Error("Job operation not found");
+ }
+
+ const accountingBatch = await loadConsumeAccountingContext(
+ client,
+ companyId
+ );
+
+ await db.transaction().execute(async (trx) => {
+ await trx
+ .insertInto("productionQuantity")
+ .values({
+ ...row,
+ type: "Production",
+ companyId,
+ createdBy: userId,
+ })
+ .executeTakeFirst();
+
+ const previousProductionQuantities =
+ productionQuantities?.data?.reduce((acc, curr) => {
+ const quantity = Number(curr.quantity);
+ return acc + quantity;
+ }, 0) ?? 0;
+
+ await produceBatchOutput(trx, {
+ jobOperationId: row.jobOperationId,
+ trackedEntityId,
+ producedQuantity: row.quantity,
+ totalQuantity: previousProductionQuantities + row.quantity,
+ companyId,
+ userId,
+ });
+
+ await issueJobOperationMaterials(trx, {
+ jobOperationId: row.jobOperationId,
+ quantity: row.quantity,
+ companyId,
+ userId,
+ accountingEnabled: accountingBatch.accountingEnabled,
+ accountDefaults: accountingBatch.accountDefaults?.data
+ ? accountingBatch.accountDefaults
: null,
- dimensionMap: dimensionMapScrapOp,
+ dimensionMap: accountingBatch.dimensionMap,
client,
db,
});
+ });
- // 3. Serial: terminal status + Scrap genealogy on the selected unit.
- // The entity keeps its consumed-material input tree.
- let scrappedEntityAttributes: TrackedEntityAttributes | null = null;
- if (isSerial && scrapEntityId) {
- const entity = await trx
- .selectFrom("trackedEntity")
- .selectAll()
- .where("id", "=", scrapEntityId)
+ return jsonResponse({
+ success: true,
+ });
+ }
+ case "jobOperationBatchOutput": {
+ const { jobOperationId, trackedEntityId, quantity, readableId, companyId, userId } =
+ validatedPayload;
+ const client = await requirePermissions(req, companyId, userId, { update: "production" });
+
+ const [entity, productionQuantities] = await Promise.all([
+ client
+ .from("trackedEntity")
+ .select("id, status, readableId")
+ .eq("id", trackedEntityId)
+ .eq("companyId", companyId)
+ .single(),
+ client
+ .from("productionQuantity")
+ .select("quantity")
+ .eq("jobOperationId", jobOperationId)
+ .eq("type", "Production"),
+ ]);
+ if (entity.error || !entity.data) {
+ throw new Error("Tracked entity not found");
+ }
+
+ // Resume no-op: a prior attempt already produced this member's output.
+ if (entity.data.status === "Available") {
+ return jsonResponse({ success: true, created: false });
+ }
+
+ // An Available lot must carry a number. Batch creation plans it (the
+ // entity's readableId, or the merged lot passed as readableId); this is
+ // the backstop for direct calls and for batches planned before that.
+ if (!readableId && !entity.data.readableId) {
+ throw new Error(
+ `Operation ${jobOperationId} produces a batch-tracked item — its batch number is required`
+ );
+ }
+
+ const totalQuantity =
+ productionQuantities.data?.reduce(
+ (acc: number, curr: { quantity: number | string | null }) =>
+ acc + Number(curr.quantity),
+ 0
+ ) ?? 0;
+ if (totalQuantity <= 0) {
+ throw new Error(
+ "No recorded production quantity for this operation — complete the batch first"
+ );
+ }
+
+ await db.transaction().execute(async (trx) => {
+ if (readableId) {
+ await trx
+ .updateTable("trackedEntity")
+ .set({ readableId })
+ .where("id", "=", trackedEntityId)
.where("companyId", "=", companyId)
- .executeTakeFirst();
- if (!entity) throw new Error("Tracked entity not found");
- if (entity.status === "Consumed" || entity.status === "Scrapped") {
- throw new Error("Tracked entity is not in progress");
- }
- scrappedEntityAttributes =
- entity.attributes as TrackedEntityAttributes;
+ .execute();
+ }
+ await produceBatchOutput(trx, {
+ jobOperationId,
+ trackedEntityId,
+ producedQuantity: quantity,
+ totalQuantity,
+ companyId,
+ userId,
+ });
+ });
- const scrapActivityId = nanoid();
+ return jsonResponse({ success: true, created: true });
+ }
+ case "jobOperationSerialComplete": {
+ const { trackedEntityId, companyId, userId, ...row } = validatedPayload;
+ const client = await requirePermissions(req, companyId, userId, { update: "production" });
+
+ const jobOperation = await client
+ .from("jobOperation")
+ .select("*")
+ .eq("id", row.jobOperationId)
+ .single();
+ if (!jobOperation.data || !jobOperation.data.jobMakeMethodId) {
+ throw new Error("Job operation not found");
+ }
+
+ const trackedEntities = await client
+ .from("trackedEntity")
+ .select("*")
+ .eq("attributes->>Job Make Method", jobOperation.data.jobMakeMethodId)
+ .order("createdAt", { ascending: true });
+
+ if (!trackedEntities.data || trackedEntities.data.length === 0) {
+ throw new Error("Tracked entities not found");
+ }
+
+ const relatedTrackedEntities = trackedEntities.data.filter(
+ (trackedEntity) =>
+ `Operation ${row.jobOperationId}` in
+ (trackedEntity.attributes as TrackedEntityAttributes)
+ );
+
+ const [accountingSettingsSerial, companyRecordSerial] = await Promise.all([
+ client
+ .from("companySettings")
+ .select("accountingEnabled")
+ .eq("id", companyId)
+ .single(),
+ client.from("company").select("companyGroupId").eq("id", companyId).single(),
+ ]);
+ if (companyRecordSerial.error) throw new Error("Failed to fetch company");
+ const accountingEnabledSerial = accountingSettingsSerial.data?.accountingEnabled ?? false;
+
+ const accountDefaultsSerial = accountingEnabledSerial
+ ? await getDefaultPostingGroup(client, companyId)
+ : null;
+ if (accountingEnabledSerial && (accountDefaultsSerial?.error || !accountDefaultsSerial?.data)) {
+ throw new Error("Error getting account defaults");
+ }
+
+ const dimensionsSerial = accountingEnabledSerial
+ ? await client
+ .from("dimension")
+ .select("id, entityType")
+ .eq("companyGroupId", companyRecordSerial.data.companyGroupId)
+ .eq("active", true)
+ .in("entityType", ["ItemPostingGroup", "Item", "Location"])
+ : null;
+
+ const dimensionMapSerial = new Map<string, string>();
+ if (dimensionsSerial?.data) {
+ for (const dim of dimensionsSerial.data) {
+ if (dim.entityType) dimensionMapSerial.set(dim.entityType, dim.id);
+ }
+ }
+
+ let newEntityId: string | undefined;
+ await db.transaction().execute(async (trx) => {
+ await trx
+ .insertInto("productionQuantity")
+ .values({
+ ...row,
+ type: "Production",
+ companyId,
+ createdBy: userId,
+ })
+ .executeTakeFirst();
+
+ const trackedEntity = await trx
+ .selectFrom("trackedEntity")
+ .where("id", "=", trackedEntityId)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (!trackedEntity) {
+ throw new Error("Tracked entity not found");
+ }
+
+ if (trackedEntity.status !== "Consumed") {
+ const activityId = nanoid();
await trx
.insertInto("trackedActivity")
.values({
- id: scrapActivityId,
- type: "Scrap",
+ id: activityId,
+ type: "Complete",
sourceDocument: "Job Operation",
- sourceDocumentId: jobOperationId,
+ sourceDocumentId: row.jobOperationId,
attributes: {
- "Job Operation": jobOperationId,
- "Scrap Reason": scrapReasonId,
+ "Job Operation": row.jobOperationId,
Employee: userId,
- ...(notes?.trim() ? { Notes: notes.trim() } : {}),
},
companyId,
createdBy: userId,
})
.execute();
+
await trx
- .insertInto("trackedActivityInput")
+ .insertInto("trackedActivityOutput")
.values({
- trackedActivityId: scrapActivityId,
- trackedEntityId: scrapEntityId,
+ trackedActivityId: activityId,
+ trackedEntityId: trackedEntityId,
quantity: 1,
companyId,
createdBy: userId,
})
.execute();
- // No `Operation ...` completion stamp — the unit did NOT complete
- // this operation; status is the terminal marker.
await trx
.updateTable("trackedEntity")
.set({
- status: "Scrapped",
+ status: "Available",
+ quantity: 1,
attributes: {
- ...(entity.attributes as TrackedEntityAttributes),
- "Scrap Reason": scrapReasonId,
+ ...(trackedEntity.attributes as TrackedEntityAttributes),
+ [`Operation ${row.jobOperationId}`]:
+ relatedTrackedEntities.length + 1,
},
})
- .where("id", "=", scrapEntityId)
+ .where("id", "=", trackedEntityId)
.execute();
}
- // 4. Reopen Done ops + capacity top-up beyond the planned allowance
- // so replacement units can run the FULL routing.
- await applyScrapReplacement(trx, {
- jobMakeMethodId: operation.jobMakeMethodId!,
- jobId: job.id,
- companyId,
- userId,
- });
-
- // 5. Serial: spawn the replacement Reserved unit. Same convention as
- // jobOperationSerialComplete — spawn while total entities <
- // operationQuantity; the top-up above grew operationQuantity by
- // the beyond-allowance scrap, and pre-created allowance units
- // (job.scrapQuantity at release) already cover in-allowance scrap.
- if (isSerial && scrapEntityId && scrappedEntityAttributes) {
- const updatedOperation = await trx
- .selectFrom("jobOperation")
- .select(["operationQuantity"])
- .where("id", "=", jobOperationId)
- .executeTakeFirst();
- const capacity = Number(updatedOperation?.operationQuantity ?? 0);
- if (existingEntityCount < capacity) {
- let spawnReadableId: string | null = null;
- if (makeMethod.itemId) {
- let locationCode: string | null = null;
- let locationName: string | null = null;
- if (job.locationId) {
+ if (
+ trackedEntities.data.length <
+ (jobOperation.data.operationQuantity ?? 0)
+ ) {
+ // Number this lazily-spawned unit from the item's serial sequence, if
+ // one is configured. This unit wasn't part of the initial pre-split at
+ // job creation (e.g. the job quantity was increased afterwards, or the
+ // sequence was configured later), so it would otherwise be created with
+ // a null readableId. Resolve the job's location for the %{location}
+ // token; the reservation runs in this transaction, atomic with the spawn.
+ let spawnReadableId: string | null = null;
+ if (trackedEntity.itemId) {
+ let locationCode: string | null = null;
+ let locationName: string | null = null;
+ const jobIdForLocation = (
+ trackedEntity.attributes as Record<string, unknown>
+ ).Job;
+ if (typeof jobIdForLocation === "string") {
+ const jobRow = await client
+ .from("job")
+ .select("locationId")
+ .eq("id", jobIdForLocation)
+ .eq("companyId", companyId)
+ .single();
+ if (jobRow.data?.locationId) {
const loc = await client
.from("location")
.select("code, name")
- .eq("id", job.locationId)
+ .eq("id", jobRow.data.locationId)
.eq("companyId", companyId)
.single();
locationCode = loc.data?.code ?? null;
locationName = loc.data?.name ?? null;
}
- const spawnSerials = await getNextSerialNumbers(trx, {
- itemId: makeMethod.itemId,
- companyId,
- count: 1,
- locationCode,
- locationName,
- });
- spawnReadableId = spawnSerials[0] ?? null;
- }
-
- const scrappedEntity = await trx
- .selectFrom("trackedEntity")
- .selectAll()
- .where("id", "=", scrapEntityId)
- .executeTakeFirst();
- const newTrackedEntityResult = await trx
- .insertInto("trackedEntity")
- .values({
- sourceDocument: scrappedEntity?.sourceDocument ?? "Item",
- sourceDocumentId:
- scrappedEntity?.sourceDocumentId ?? makeMethod.itemId ?? "",
- sourceDocumentReadableId:
- scrappedEntity?.sourceDocumentReadableId,
- quantity: 1,
- status: "Reserved",
- attributes: scrappedEntityAttributes as unknown as Json,
- itemId: makeMethod.itemId ?? null,
- expirationDate: scrappedEntity?.expirationDate ?? null,
- readableId: spawnReadableId,
- companyId,
- createdBy: userId,
- })
- .returning(["id"])
- .executeTakeFirst();
- newEntityId = newTrackedEntityResult?.id;
- }
- }
-
- // 6. GL: relieve the scrapped units\' accumulated material cost from
- // WIP into the scrap account. Valuation = this operation\'s actual
- // backflush cost + prior operations\' estimated material cost
- // (jobMaterial per-unit quantity × itemCost.unitCost). Labor and
- // overhead already absorbed stay in WIP and settle via close-job
- // variance (spec decision 6).
- if (accountingEnabledScrapOp && accountDefaultsScrapOp?.data) {
- let priorUnitMaterialCost = 0;
- const priorOperations = await trx
- .selectFrom("jobOperation")
- .select(["id"])
- .where("jobMakeMethodId", "=", operation.jobMakeMethodId!)
- .where("order", "<", operation.order)
- .execute();
- if (priorOperations.length > 0) {
- const priorMaterials = await trx
- .selectFrom("jobMaterial")
- .select(["itemId", "quantity"])
- .where(
- "jobOperationId",
- "in",
- priorOperations.map((op) => op.id)
- )
- .where("methodType", "!=", "Make to Order")
- .execute();
- if (priorMaterials.length > 0) {
- const priorCosts = await trx
- .selectFrom("itemCost")
- .select(["itemId", "unitCost"])
- .where(
- "itemId",
- "in",
- priorMaterials.map((m) => m.itemId)
- )
- .where("companyId", "=", companyId)
- .execute();
- const unitCostByItem = new Map(
- priorCosts.map((c) => [c.itemId, Number(c.unitCost) || 0])
- );
- for (const material of priorMaterials) {
- priorUnitMaterialCost +=
- (Number(material.quantity) || 0) *
- (unitCostByItem.get(material.itemId) ?? 0);
- }
}
+ const spawnSerials = await getNextSerialNumbers(trx, {
+ itemId: trackedEntity.itemId,
+ companyId,
+ count: 1,
+ locationCode,
+ locationName,
+ });
+ spawnReadableId = spawnSerials[0] ?? null;
}
- const scrapCost =
- backflush.totalMaterialCost + priorUnitMaterialCost * quantity;
- if (scrapCost > 0) {
- const accountingPeriodId = await getCurrentAccountingPeriod(
- client,
+ // Create a new trackedEntity with the same attributes but status = Reserved
+ const newTrackedEntityResult = await trx
+ .insertInto("trackedEntity")
+ .values({
+ sourceDocument: trackedEntity.sourceDocument,
+ sourceDocumentId: trackedEntity.sourceDocumentId,
+ sourceDocumentReadableId:
+ trackedEntity.sourceDocumentReadableId,
+ quantity: 1,
+ status: "Reserved",
+ attributes: trackedEntity.attributes,
+ itemId: trackedEntity.itemId ?? null,
+ expirationDate: trackedEntity.expirationDate ?? null,
+ readableId: spawnReadableId,
companyId,
- trx,
- todayScrapOp
- );
- const journalEntryId = await getNextSequence(
- trx,
- "journalEntry",
- companyId
- );
- const journalResult = await trx
- .insertInto("journal")
- .values({
- journalEntryId,
- accountingPeriodId,
- description: `Scrap — Job ${job.jobId ?? job.id}`,
- postingDate: todayScrapOp,
- companyId,
- sourceType: "Job Consumption",
- status: "Posted",
- postedAt: new Date().toISOString(),
- postedBy: userId,
- createdBy: userId,
- })
- .returning(["id"])
- .executeTakeFirstOrThrow();
-
- const scrapAccount =
- accountDefaultsScrapOp.data.scrapAccount ??
- accountDefaultsScrapOp.data.inventoryAdjustmentVarianceAccount;
- const journalLineReference = nanoid();
- const journalLineResults = await trx
- .insertInto("journalLine")
- .values([
- {
- journalId: journalResult.id,
- accountId: scrapAccount,
- description: "Scrap Account",
- amount: debit("expense", scrapCost),
- quantity,
- documentType: "Scrap",
- documentId: job.id,
- documentLineReference: `jobOperationScrap:${jobOperationId}`,
- journalLineReference,
- companyId,
- },
- {
- journalId: journalResult.id,
- accountId: accountDefaultsScrapOp.data.workInProgressAccount,
- description: "WIP Account",
- amount: credit("asset", scrapCost),
- quantity,
- documentType: "Scrap",
- documentId: job.id,
- documentLineReference: `jobOperationScrap:${jobOperationId}`,
- journalLineReference,
- companyId,
- },
- ])
- .returning(["id"])
- .execute();
+ createdBy: userId,
+ })
+ .returning(["id"])
+ .executeTakeFirst();
- const itemCostRow = makeMethod.itemId
- ? await trx
- .selectFrom("itemCost")
- .select(["itemPostingGroupId"])
- .where("itemId", "=", makeMethod.itemId)
- .where("companyId", "=", companyId)
- .executeTakeFirst()
- : null;
- const scrapDimensionValues: Array<[string, string | null]> = [
- ["Item", makeMethod.itemId ?? null],
- ["ItemPostingGroup", itemCostRow?.itemPostingGroupId ?? null],
- ["Location", job.locationId ?? null],
- ["ScrapReason", scrapReasonId],
- ["WorkCenter", operation.workCenterId ?? null],
- ["Employee", userId],
- ];
- const dimensionInserts = journalLineResults.flatMap((line) =>
- scrapDimensionValues
- .filter(
- ([entityType, valueId]) =>
- dimensionMapScrapOp.has(entityType) && valueId
- )
- .map(([entityType, valueId]) => ({
- journalLineId: line.id,
- dimensionId: dimensionMapScrapOp.get(entityType)!,
- valueId: valueId as string,
- companyId,
- }))
- );
- if (dimensionInserts.length > 0) {
- await trx
- .insertInto("journalLineDimension")
- .values(dimensionInserts)
- .execute();
- }
- }
+ newEntityId = newTrackedEntityResult?.id;
}
+
+ await issueJobOperationMaterials(trx, {
+ jobOperationId: row.jobOperationId,
+ quantity: row.quantity,
+ companyId,
+ userId,
+ accountingEnabled: accountingEnabledSerial,
+ accountDefaults: accountDefaultsSerial?.data ? accountDefaultsSerial : null,
+ dimensionMap: dimensionMapSerial,
+ client,
+ db,
+ });
});
- // Reschedule outside the transaction (trigger-rework precedent):
- // reopened/topped-up operations need fresh dates and priorities.
- try {
- const supabaseUrl = Deno.env.get("SUPABASE_URL");
- const serviceRoleKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY");
- await fetch(`${supabaseUrl}/functions/v1/reschedule`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${serviceRoleKey}`,
- },
- body: JSON.stringify({ jobId: job.id, companyId, userId }),
- // The scrap transaction already committed; don't let a stalled
- // reschedule hold the request open until the platform kills it.
- signal: AbortSignal.timeout(10_000),
- });
- } catch (rescheduleError) {
- logger.error("Failed to trigger reschedule after scrap", {
- error: String((rescheduleError as Error)?.stack ?? rescheduleError),
- });
- }
-
return jsonResponse({
success: true,
newTrackedEntityId: newEntityId,
});
}
- case "partToOperation": {
+ case "jobOperationScrap": {
const {
- id,
+ jobOperationId,
+ quantity,
+ scrapReasonId,
+ trackedEntityId: scrapEntityId,
+ notes,
+ laborProductionEventId,
+ machineProductionEventId,
+ setupProductionEventId,
companyId,
userId,
- itemId,
- quantity,
- materialId,
- jobOperationStepId,
- adjustmentType,
} = validatedPayload;
+ const client = await requirePermissions(req, companyId, userId, {
+ update: "production",
+ });
- const client = await requirePermissions(req, companyId, userId, { update: "production" });
+ const operationRes = await client
+ .from("jobOperation")
+ .select("*")
+ .eq("id", jobOperationId)
+ .eq("companyId", companyId)
+ .single();
+ const operation = operationRes.data;
+ if (!operation || !operation.jobMakeMethodId) {
+ throw new Error("Job operation not found");
+ }
- const [accountingSettings, companyRecord] = await Promise.all([
+ const [
+ makeMethodRes,
+ jobRes,
+ trackedEntitiesRes,
+ accountingSettingsScrapOp,
+ companyRecordScrapOp,
+ ] = await Promise.all([
+ client
+ .from("jobMakeMethod")
+ .select(
+ "id, itemId, requiresSerialTracking, requiresBatchTracking, parentMaterialId"
+ )
+ .eq("id", operation.jobMakeMethodId)
+ .eq("companyId", companyId)
+ .single(),
+ client
+ .from("job")
+ .select("id, jobId, locationId")
+ .eq("id", operation.jobId)
+ .eq("companyId", companyId)
+ .single(),
+ client
+ .from("trackedEntity")
+ .select("id")
+ .eq("attributes->>Job Make Method", operation.jobMakeMethodId)
+ .eq("companyId", companyId),
client
.from("companySettings")
.select("accountingEnabled")
.eq("id", companyId)
.single(),
- client.from("company").select("companyGroupId").eq("id", companyId).single(),
+ client
+ .from("company")
+ .select("companyGroupId")
+ .eq("id", companyId)
+ .single(),
]);
- if (companyRecord.error) throw new Error("Failed to fetch company");
- const accountingEnabled = accountingSettings.data?.accountingEnabled ?? false;
+ if (makeMethodRes.error || !makeMethodRes.data) {
+ throw new Error("Job make method not found");
+ }
+ if (jobRes.error || !jobRes.data) throw new Error("Job not found");
+ if (companyRecordScrapOp.error) {
+ throw new Error("Failed to fetch company");
+ }
+ const makeMethod = makeMethodRes.data;
+ const job = jobRes.data;
+ const existingEntityCount = trackedEntitiesRes.data?.length ?? 0;
- const accountDefaults = accountingEnabled
+ const accountingEnabledScrapOp =
+ accountingSettingsScrapOp.data?.accountingEnabled ?? false;
+ const accountDefaultsScrapOp = accountingEnabledScrapOp
? await getDefaultPostingGroup(client, companyId)
: null;
- if (accountingEnabled && (accountDefaults?.error || !accountDefaults?.data)) {
+ if (
+ accountingEnabledScrapOp &&
+ (accountDefaultsScrapOp?.error || !accountDefaultsScrapOp?.data)
+ ) {
throw new Error("Error getting account defaults");
}
- const dimensions = accountingEnabled
+ const dimensionsScrapOp = accountingEnabledScrapOp
? await client
.from("dimension")
.select("id, entityType")
- .eq("companyGroupId", companyRecord.data.companyGroupId)
+ .eq("companyGroupId", companyRecordScrapOp.data.companyGroupId)
.eq("active", true)
- .in("entityType", ["ItemPostingGroup", "Item", "Location"])
+ .in("entityType", [
+ "ItemPostingGroup",
+ "Item",
+ "Location",
+ "ScrapReason",
+ "WorkCenter",
+ "Employee",
+ ])
: null;
-
- const dimensionMap = new Map<string, string>();
- if (dimensions?.data) {
- for (const dim of dimensions.data) {
- if (dim.entityType) dimensionMap.set(dim.entityType, dim.id);
+ const dimensionMapScrapOp = new Map<string, string>();
+ if (dimensionsScrapOp?.data) {
+ for (const dim of dimensionsScrapOp.data) {
+ if (dim.entityType) dimensionMapScrapOp.set(dim.entityType, dim.id);
}
}
+ const isSerial = makeMethod.requiresSerialTracking === true;
+ if (isSerial && !scrapEntityId) {
+ throw new Error("trackedEntityId is required to scrap a serial unit");
+ }
+ if (isSerial && quantity !== 1) {
+ throw new Error("Serial units are scrapped one at a time");
+ }
+
+ const todayScrapOp = datetime
+ .today(await getCompanyTimeZone(client, companyId))
+ .toString();
+
+ let newEntityId: string | undefined;
await db.transaction().execute(async (trx) => {
- const jobOperation = await trx
- .selectFrom("jobOperation")
- .where("id", "=", id)
- .select(["jobId", "jobMakeMethodId"])
+ // 1. Scrap quantity record. The quantity-sync interceptor aggregates
+ // quantityScrapped; scrap no longer counts toward the auto-Done
+ // target (20260807090629), so the operation stays open until the
+ // good quantity is actually made.
+ await trx
+ .insertInto("productionQuantity")
+ .values({
+ jobOperationId,
+ quantity,
+ type: "Scrap",
+ scrapReasonId,
+ notes,
+ laborProductionEventId,
+ machineProductionEventId,
+ setupProductionEventId,
+ companyId,
+ createdBy: userId,
+ })
.executeTakeFirst();
- const [job, item] = await Promise.all([
- trx
- .selectFrom("job")
- .where("id", "=", jobOperation?.jobId!)
- .select("locationId")
- .executeTakeFirst(),
- trx
- .selectFrom("item")
- .where("id", "=", itemId)
- .select([
- "id",
- "itemTrackingType",
- "name",
- "readableIdWithRevision",
- "type",
- ])
- .executeTakeFirst(),
- ]);
+ // 2. Backflush the scrapped units\' BOM for this operation — material
+ // cost enters WIP exactly as a completion would (NetSuite "Issue
+ // for Scrap"); the WIP→scrap journal below relieves it.
+ const backflush = await issueJobOperationMaterials(trx, {
+ jobOperationId,
+ quantity,
+ companyId,
+ userId,
+ accountingEnabled: accountingEnabledScrapOp,
+ accountDefaults: accountDefaultsScrapOp?.data
+ ? accountDefaultsScrapOp
+ : null,
+ dimensionMap: dimensionMapScrapOp,
+ client,
+ db,
+ });
- if (materialId) {
- const material = await trx
- .selectFrom("jobMaterial")
- .where("id", "=", materialId)
+ // 3. Serial: terminal status + Scrap genealogy on the selected unit.
+ // The entity keeps its consumed-material input tree.
+ let scrappedEntityAttributes: TrackedEntityAttributes | null = null;
+ if (isSerial && scrapEntityId) {
+ const entity = await trx
+ .selectFrom("trackedEntity")
.selectAll()
+ .where("id", "=", scrapEntityId)
+ .where("companyId", "=", companyId)
.executeTakeFirst();
-
- let storageUnitId: string | null | undefined;
- // Prioritize material.storageUnitId if available
- if (material?.storageUnitId) {
- storageUnitId = material.storageUnitId;
- } else if (material?.defaultStorageUnit) {
- const pickMethod = await trx
- .selectFrom("pickMethod")
- .where("itemId", "=", itemId)
- .where("locationId", "=", job?.locationId!)
- .select("defaultStorageUnitId")
- .executeTakeFirst();
- storageUnitId = pickMethod?.defaultStorageUnitId;
- } else {
- storageUnitId = await getStorageUnitWithHighestQuantity(
- trx,
- itemId,
- job?.locationId!
- );
- }
-
- const quantityToIssue =
- adjustmentType === "Positive Adjmt."
- ? Number(quantity)
- : adjustmentType === "Negative Adjmt."
- ? Number(quantity)
- : Number(quantity) - Number(material?.quantityIssued); // set quantity
-
- if (material && material.methodType !== "Make to Order") {
- let remaining = Number(quantityToIssue);
- if (adjustmentType !== "Positive Adjmt." && remaining > 0) {
- const budgets = orderOldFirst(
- await getPickedBudgets(trx, {
- material,
- locationId: job?.locationId!,
- companyId,
- opStorageUnitId: await getOperationLinesideBin(trx, {
- jobOperationId: material.jobOperationId,
- companyId,
- }),
- }),
- material.itemId
- );
- const allocation = allocateAcrossBudgets(
- remaining,
- budgets,
- Number(material.quantity ?? 0)
- );
- remaining = allocation.remaining;
- for (const take of allocation.takes) {
- if (!take.budget.isInventory) continue;
- for (const row of splitTakeByBin(take)) {
- itemLedgerInserts.push({
- entryType: "Consumption",
- documentType: "Job Consumption",
- documentId: material.jobId,
- documentLineId: id,
- companyId,
- itemId: take.budget.itemId,
- locationId: job?.locationId,
- storageUnitId: row.storageUnitId,
- quantity: -row.quantity,
- createdBy: userId,
- });
- }
- }
- }
- if (item?.itemTrackingType === "Inventory" && remaining !== 0) {
- itemLedgerInserts.push({
- entryType: "Consumption",
- documentType: "Job Consumption",
- documentId: material.jobId,
- documentLineId: id,
- companyId,
- itemId: material.itemId,
- locationId: job?.locationId,
- storageUnitId,
- quantity:
- adjustmentType === "Positive Adjmt."
- ? Number(remaining)
- : -Number(remaining),
- createdBy: userId,
- });
- }
+ if (!entity) throw new Error("Tracked entity not found");
+ if (entity.status === "Consumed" || entity.status === "Scrapped") {
+ throw new Error("Tracked entity is not in progress");
}
+ scrappedEntityAttributes =
+ entity.attributes as TrackedEntityAttributes;
+ const scrapActivityId = nanoid();
await trx
- .updateTable("jobMaterial")
- .set({
- // A positive adjustment returns material to inventory, so it
- // reduces quantityIssued — otherwise the backflush cap sees
- // returned material as still issued.
- quantityIssued:
- (Number(material?.quantityIssued) ?? 0) +
- (adjustmentType === "Positive Adjmt."
- ? -Number(quantityToIssue)
- : Number(quantityToIssue)),
- })
- .where("id", "=", materialId)
- .execute();
-
- if (itemLedgerInserts.length > 0) {
- await trx
- .insertInto("itemLedger")
- .values(itemLedgerInserts)
- .execute();
-
- // Update pickMethod defaultStorageUnitId if needed for each inserted ledger
- for (const ledger of itemLedgerInserts) {
- await updatePickMethodDefaultStorageUnitIfNeeded(
- trx,
- ledger.itemId,
- ledger.locationId,
- ledger.storageUnitId,
- companyId,
- userId
- );
- }
- }
- } else {
- let storageUnitId: string | null | undefined;
- if (item?.itemTrackingType === "Inventory") {
- const pickMethod = await trx
- .selectFrom("pickMethod")
- .where("itemId", "=", itemId)
- .where("locationId", "=", job?.locationId!)
- .select("defaultStorageUnitId")
- .executeTakeFirst();
-
- storageUnitId =
- pickMethod?.defaultStorageUnitId ??
- (await getStorageUnitWithHighestQuantity(
- trx,
- itemId,
- job?.locationId!
- ));
-
- itemLedgerInserts.push({
- entryType: "Consumption",
- documentType: "Job Consumption",
- documentId: jobOperation?.jobId,
- documentLineId: id,
+ .insertInto("trackedActivity")
+ .values({
+ id: scrapActivityId,
+ type: "Scrap",
+ sourceDocument: "Job Operation",
+ sourceDocumentId: jobOperationId,
+ attributes: {
+ "Job Operation": jobOperationId,
+ "Scrap Reason": scrapReasonId,
+ Employee: userId,
+ ...(notes?.trim() ? { Notes: notes.trim() } : {}),
+ },
companyId,
- itemId: itemId!,
- quantity:
- adjustmentType === "Positive Adjmt."
- ? Number(quantity)
- : -Number(quantity),
- locationId: job?.locationId,
- storageUnitId,
createdBy: userId,
- });
- }
-
- const itemCost = await trx
- .selectFrom("itemCost")
- .where("itemId", "=", itemId!)
- .select("unitCost")
- .executeTakeFirst();
-
- const newJobMaterial = await trx
- .insertInto("jobMaterial")
+ })
+ .execute();
+ await trx
+ .insertInto("trackedActivityInput")
.values({
+ trackedActivityId: scrapActivityId,
+ trackedEntityId: scrapEntityId,
+ quantity: 1,
companyId,
createdBy: userId,
- description: item?.name ?? "",
- estimatedQuantity: 0,
- itemId: itemId!,
- itemType: item?.type ?? "Part",
- jobId: jobOperation?.jobId!,
- jobMakeMethodId: jobOperation?.jobMakeMethodId!,
- jobOperationId: id,
- storageUnitId: storageUnitId ?? undefined,
- methodType: "Pull from Inventory",
- quantity: 0,
- quantityIssued: Number(quantity ?? 0),
- unitCost: itemCost?.unitCost ?? 0,
})
- .returning("id")
+ .execute();
+ // No `Operation ...` completion stamp — the unit did NOT complete
+ // this operation; status is the terminal marker.
+ await trx
+ .updateTable("trackedEntity")
+ .set({
+ status: "Scrapped",
+ attributes: {
+ ...(entity.attributes as TrackedEntityAttributes),
+ "Scrap Reason": scrapReasonId,
+ },
+ })
+ .where("id", "=", scrapEntityId)
+ .execute();
+ }
+
+ // 4. Reopen Done ops + capacity top-up beyond the planned allowance
+ // so replacement units can run the FULL routing.
+ await applyScrapReplacement(trx, {
+ jobMakeMethodId: operation.jobMakeMethodId!,
+ jobId: job.id,
+ companyId,
+ userId,
+ });
+
+ // 5. Serial: spawn the replacement Reserved unit. Same convention as
+ // jobOperationSerialComplete — spawn while total entities <
+ // operationQuantity; the top-up above grew operationQuantity by
+ // the beyond-allowance scrap, and pre-created allowance units
+ // (job.scrapQuantity at release) already cover in-allowance scrap.
+ if (isSerial && scrapEntityId && scrappedEntityAttributes) {
+ const updatedOperation = await trx
+ .selectFrom("jobOperation")
+ .select(["operationQuantity"])
+ .where("id", "=", jobOperationId)
.executeTakeFirst();
+ const capacity = Number(updatedOperation?.operationQuantity ?? 0);
+ if (existingEntityCount < capacity) {
+ let spawnReadableId: string | null = null;
+ if (makeMethod.itemId) {
+ let locationCode: string | null = null;
+ let locationName: string | null = null;
+ if (job.locationId) {
+ const loc = await client
+ .from("location")
+ .select("code, name")
+ .eq("id", job.locationId)
+ .eq("companyId", companyId)
+ .single();
+ locationCode = loc.data?.code ?? null;
+ locationName = loc.data?.name ?? null;
+ }
+ const spawnSerials = await getNextSerialNumbers(trx, {
+ itemId: makeMethod.itemId,
+ companyId,
+ count: 1,
+ locationCode,
+ locationName,
+ });
+ spawnReadableId = spawnSerials[0] ?? null;
+ }
- // Scope this unplanned part to the step it was issued on (assembly
- // view), so it shows on that step rather than as a General material.
- if (jobOperationStepId && newJobMaterial?.id) {
- await trx
- .insertInto("jobMaterialStep")
+ const scrappedEntity = await trx
+ .selectFrom("trackedEntity")
+ .selectAll()
+ .where("id", "=", scrapEntityId)
+ .executeTakeFirst();
+ const newTrackedEntityResult = await trx
+ .insertInto("trackedEntity")
.values({
- jobMaterialId: newJobMaterial.id,
- jobOperationStepId,
+ sourceDocument: scrappedEntity?.sourceDocument ?? "Item",
+ sourceDocumentId:
+ scrappedEntity?.sourceDocumentId ?? makeMethod.itemId ?? "",
+ sourceDocumentReadableId:
+ scrappedEntity?.sourceDocumentReadableId,
+ quantity: 1,
+ status: "Reserved",
+ attributes: scrappedEntityAttributes as unknown as Json,
+ itemId: makeMethod.itemId ?? null,
+ expirationDate: scrappedEntity?.expirationDate ?? null,
+ readableId: spawnReadableId,
+ companyId,
+ createdBy: userId,
})
- .onConflict((oc) => oc.doNothing())
- .execute();
+ .returning(["id"])
+ .executeTakeFirst();
+ newEntityId = newTrackedEntityResult?.id;
}
+ }
- if (itemLedgerInserts.length > 0) {
- await trx
- .insertInto("itemLedger")
- .values(itemLedgerInserts)
- .execute();
-
- // Update pickMethod defaultStorageUnitId if needed for each inserted ledger
- for (const ledger of itemLedgerInserts) {
- await updatePickMethodDefaultStorageUnitIfNeeded(
- trx,
- ledger.itemId,
- ledger.locationId,
- ledger.storageUnitId,
- companyId,
- userId
- );
+ // 6. GL: relieve the scrapped units\' accumulated material cost from
+ // WIP into the scrap account. Valuation = this operation\'s actual
+ // backflush cost + prior operations\' estimated material cost
+ // (jobMaterial per-unit quantity × itemCost.unitCost). Labor and
+ // overhead already absorbed stay in WIP and settle via close-job
+ // variance (spec decision 6).
+ if (accountingEnabledScrapOp && accountDefaultsScrapOp?.data) {
+ let priorUnitMaterialCost = 0;
+ const priorOperations = await trx
+ .selectFrom("jobOperation")
+ .select(["id"])
+ .where("jobMakeMethodId", "=", operation.jobMakeMethodId!)
+ .where("order", "<", operation.order)
+ .execute();
+ if (priorOperations.length > 0) {
+ const priorMaterials = await trx
+ .selectFrom("jobMaterial")
+ .select(["itemId", "quantity"])
+ .where(
+ "jobOperationId",
+ "in",
+ priorOperations.map((op) => op.id)
+ )
+ .where("methodType", "!=", "Make to Order")
+ .execute();
+ if (priorMaterials.length > 0) {
+ const priorCosts = await trx
+ .selectFrom("itemCost")
+ .select(["itemId", "unitCost"])
+ .where(
+ "itemId",
+ "in",
+ priorMaterials.map((m) => m.itemId)
+ )
+ .where("companyId", "=", companyId)
+ .execute();
+ const unitCostByItem = new Map(
+ priorCosts.map((c) => [c.itemId, Number(c.unitCost) || 0])
+ );
+ for (const material of priorMaterials) {
+ priorUnitMaterialCost +=
+ (Number(material.quantity) || 0) *
+ (unitCostByItem.get(material.itemId) ?? 0);
+ }
}
}
- }
-
- if (accountingEnabled && accountDefaults?.data && itemLedgerInserts.length > 0) {
- const jobOperation = await trx
- .selectFrom("jobOperation")
- .where("id", "=", id)
- .select(["jobId"])
- .executeTakeFirst();
- const jobRecord = jobOperation?.jobId
- ? await trx
- .selectFrom("job")
- .where("id", "=", jobOperation.jobId)
- .select(["itemId", "locationId"])
- .executeTakeFirst()
- : null;
+ const scrapCost =
+ backflush.totalMaterialCost + priorUnitMaterialCost * quantity;
+ if (scrapCost > 0) {
+ const accountingPeriodId = await getCurrentAccountingPeriod(
+ client,
+ companyId,
+ trx,
+ todayScrapOp
+ );
+ const journalEntryId = await getNextSequence(
+ trx,
+ "journalEntry",
+ companyId
+ );
+ const journalResult = await trx
+ .insertInto("journal")
+ .values({
+ journalEntryId,
+ accountingPeriodId,
+ description: `Scrap — Job ${job.jobId ?? job.id}`,
+ postingDate: todayScrapOp,
+ companyId,
+ sourceType: "Job Consumption",
+ status: "Posted",
+ postedAt: new Date().toISOString(),
+ postedBy: userId,
+ createdBy: userId,
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
- await createMaterialWipEntries(trx, {
- consumptionLedgers: itemLedgerInserts.map((l) => ({
- itemId: l.itemId as string,
- quantity: Number(l.quantity),
- })),
- jobId: jobOperation?.jobId!,
- operationId: id,
- description: "Manual Material Issue",
- wipAccount: accountDefaults.data.workInProgressAccount,
- rawMaterialsAccount: accountDefaults.data.rawMaterialsAccount,
- finishedGoodsAccount: accountDefaults.data.finishedGoodsAccount,
- dimensionMap,
+ const scrapAccount =
+ accountDefaultsScrapOp.data.scrapAccount ??
+ accountDefaultsScrapOp.data.inventoryAdjustmentVarianceAccount;
+ const journalLineReference = nanoid();
+ const journalLineResults = await trx
+ .insertInto("journalLine")
+ .values([
+ {
+ journalId: journalResult.id,
+ accountId: scrapAccount,
+ description: "Scrap Account",
+ amount: debit("expense", scrapCost),
+ quantity,
+ documentType: "Scrap",
+ documentId: job.id,
+ documentLineReference: `jobOperationScrap:${jobOperationId}`,
+ journalLineReference,
+ companyId,
+ },
+ {
+ journalId: journalResult.id,
+ accountId: accountDefaultsScrapOp.data.workInProgressAccount,
+ description: "WIP Account",
+ amount: credit("asset", scrapCost),
+ quantity,
+ documentType: "Scrap",
+ documentId: job.id,
+ documentLineReference: `jobOperationScrap:${jobOperationId}`,
+ journalLineReference,
+ companyId,
+ },
+ ])
+ .returning(["id"])
+ .execute();
- jobLocationId: jobRecord?.locationId ?? null,
- client,
- db,
- companyId,
- userId,
- });
+ const itemCostRow = makeMethod.itemId
+ ? await trx
+ .selectFrom("itemCost")
+ .select(["itemPostingGroupId"])
+ .where("itemId", "=", makeMethod.itemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : null;
+ const scrapDimensionValues: Array<[string, string | null]> = [
+ ["Item", makeMethod.itemId ?? null],
+ ["ItemPostingGroup", itemCostRow?.itemPostingGroupId ?? null],
+ ["Location", job.locationId ?? null],
+ ["ScrapReason", scrapReasonId],
+ ["WorkCenter", operation.workCenterId ?? null],
+ ["Employee", userId],
+ ];
+ const dimensionInserts = journalLineResults.flatMap((line) =>
+ scrapDimensionValues
+ .filter(
+ ([entityType, valueId]) =>
+ dimensionMapScrapOp.has(entityType) && valueId
+ )
+ .map(([entityType, valueId]) => ({
+ journalLineId: line.id,
+ dimensionId: dimensionMapScrapOp.get(entityType)!,
+ valueId: valueId as string,
+ companyId,
+ }))
+ );
+ if (dimensionInserts.length > 0) {
+ await trx
+ .insertInto("journalLineDimension")
+ .values(dimensionInserts)
+ .execute();
+ }
+ }
}
});
- break;
+
+ // Reschedule outside the transaction (trigger-rework precedent):
+ // reopened/topped-up operations need fresh dates and priorities.
+ try {
+ const supabaseUrl = Deno.env.get("SUPABASE_URL");
+ const serviceRoleKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY");
+ await fetch(`${supabaseUrl}/functions/v1/reschedule`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${serviceRoleKey}`,
+ },
+ body: JSON.stringify({ jobId: job.id, companyId, userId }),
+ // The scrap transaction already committed; don't let a stalled
+ // reschedule hold the request open until the platform kills it.
+ signal: AbortSignal.timeout(10_000),
+ });
+ } catch (rescheduleError) {
+ logger.error("Failed to trigger reschedule after scrap", {
+ error: String((rescheduleError as Error)?.stack ?? rescheduleError),
+ });
+ }
+
+ return jsonResponse({
+ success: true,
+ newTrackedEntityId: newEntityId,
+ });
}
- case "scrapTrackedEntity": {
+ case "partToOperation": {
const {
- trackedEntityId,
- materialId,
- parentTrackedEntityId,
- scrapReasonId,
- makeReplacement,
+ id,
companyId,
userId,
+ itemId,
+ quantity,
+ materialId,
+ jobOperationStepId,
+ adjustmentType,
} = validatedPayload;
- const client = await requirePermissions(req, companyId, userId, {
- update: "production",
- });
-
- const [trackedEntity, jobMaterial] = await Promise.all([
- client
- .from("trackedEntity")
- .select("*")
- .eq("id", trackedEntityId)
- .eq("companyId", companyId)
- .single(),
- client
- .from("jobMaterial")
- .select("*")
- .eq("id", materialId)
- .eq("companyId", companyId)
- .single(),
- ]);
-
- if (!trackedEntity.data) {
- throw new Error("Tracked entity not found");
- }
- if (!jobMaterial.data) {
- throw new Error("Job material not found");
- }
- if (trackedEntity.data.status === "Scrapped") {
- throw new Error("Tracked entity has already been scrapped");
- }
+ const client = await requirePermissions(req, companyId, userId, { update: "production" });
- const [accountingSettingsScrap, companyRecordScrap] = await Promise.all([
+ const [accountingSettings, companyRecord] = await Promise.all([
client
.from("companySettings")
.select("accountingEnabled")
@@ -2315,497 +2666,357 @@ serve(async (req: Request) => {
.single(),
client.from("company").select("companyGroupId").eq("id", companyId).single(),
]);
- if (companyRecordScrap.error) throw new Error("Failed to fetch company");
- const accountingEnabledScrap = accountingSettingsScrap.data?.accountingEnabled ?? false;
+ if (companyRecord.error) throw new Error("Failed to fetch company");
+ const accountingEnabled = accountingSettings.data?.accountingEnabled ?? false;
- const accountDefaultsScrap = accountingEnabledScrap
+ const accountDefaults = accountingEnabled
? await getDefaultPostingGroup(client, companyId)
: null;
- if (accountingEnabledScrap && (accountDefaultsScrap?.error || !accountDefaultsScrap?.data)) {
+ if (accountingEnabled && (accountDefaults?.error || !accountDefaults?.data)) {
throw new Error("Error getting account defaults");
}
- const dimensionsScrap = accountingEnabledScrap
+ const dimensions = accountingEnabled
? await client
.from("dimension")
.select("id, entityType")
- .eq("companyGroupId", companyRecordScrap.data.companyGroupId)
+ .eq("companyGroupId", companyRecord.data.companyGroupId)
.eq("active", true)
- .in("entityType", [
- "ItemPostingGroup",
- "Item",
- "Location",
- "ScrapReason",
- "WorkCenter",
- "Employee",
- ])
+ .in("entityType", ["ItemPostingGroup", "Item", "Location"])
: null;
- const dimensionMapScrap = new Map<string, string>();
- if (dimensionsScrap?.data) {
- for (const dim of dimensionsScrap.data) {
- if (dim.entityType) dimensionMapScrap.set(dim.entityType, dim.id);
+ const dimensionMap = new Map<string, string>();
+ if (dimensions?.data) {
+ for (const dim of dimensions.data) {
+ if (dim.entityType) dimensionMap.set(dim.entityType, dim.id);
}
}
- const todayScrap = datetime
- .today(await getCompanyTimeZone(client, companyId))
- .toString();
- // Resolve the period BEFORE the transaction parks the (size 1) pool.
- const accountingPeriodIdScrap = accountingEnabledScrap
- ? await getCurrentAccountingPeriod(client, companyId, db, todayScrap)
- : null;
-
- let didReplace = false;
await db.transaction().execute(async (trx) => {
- const entity = trackedEntity.data!;
- const material = jobMaterial.data!;
- const quantity = Number(entity.quantity);
-
- const job = await trx
- .selectFrom("job")
- .select(["id", "jobId", "locationId", "itemId"])
- .where("id", "=", material.jobId!)
- .executeTakeFirst();
-
- const item = await trx
- .selectFrom("item")
- .where("id", "=", material.itemId!)
- .select(["readableIdWithRevision"])
+ const jobOperation = await trx
+ .selectFrom("jobOperation")
+ .where("id", "=", id)
+ .select(["jobId", "jobMakeMethodId"])
.executeTakeFirst();
- // Scrap genealogy (was: Consume + attributes.Scrapped). The entity
- // keeps its full input tree; status is the terminal marker.
- const activityId = nanoid();
- await trx
- .insertInto("trackedActivity")
- .values({
- id: activityId,
- type: "Scrap",
- sourceDocument: "Job Material",
- sourceDocumentId: materialId,
- sourceDocumentReadableId: item?.readableIdWithRevision ?? "",
- attributes: {
- Job: job?.id!,
- "Job Make Method": material.jobMakeMethodId!,
- "Job Material": material.id!,
- "Scrap Reason": scrapReasonId,
- Employee: userId,
- },
- companyId,
- createdBy: userId,
- })
- .execute();
-
- await trx
- .insertInto("trackedActivityInput")
- .values({
- trackedActivityId: activityId,
- trackedEntityId,
- quantity,
- companyId,
- createdBy: userId,
- })
- .execute();
-
- if (parentTrackedEntityId) {
- await trx
- .insertInto("trackedActivityOutput")
- .values({
- trackedActivityId: activityId,
- trackedEntityId: parentTrackedEntityId,
- quantity,
- companyId,
- createdBy: userId,
- })
- .execute();
- }
-
- await trx
- .updateTable("trackedEntity")
- .set({
- status: "Scrapped",
- })
- .where("id", "=", trackedEntityId)
- .execute();
-
- const consumedItemId = entity.sourceDocumentId ?? material.itemId!;
- const [itemRow, itemCostRow] = await Promise.all([
+ const [job, item] = await Promise.all([
trx
- .selectFrom("item")
- .select(["itemTrackingType", "replenishmentSystem"])
- .where("id", "=", consumedItemId)
+ .selectFrom("job")
+ .where("id", "=", jobOperation?.jobId!)
+ .select("locationId")
.executeTakeFirst(),
trx
- .selectFrom("itemCost")
+ .selectFrom("item")
+ .where("id", "=", itemId)
.select([
- "costingMethod",
- "unitCost",
- "standardCost",
- "itemPostingGroupId",
+ "id",
+ "itemTrackingType",
+ "name",
+ "readableIdWithRevision",
+ "type",
])
- .where("itemId", "=", consumedItemId)
- .where("companyId", "=", companyId)
.executeTakeFirst(),
]);
- // A missing itemCost must not fail the scrap — fall back to zero
- // cost (no journal value) so the physical/traceability scrap still
- // records; accounting can be reconciled later.
- const resolvedItemCost = {
- costingMethod: itemCostRow?.costingMethod ?? "Average",
- unitCost: Number(itemCostRow?.unitCost ?? 0),
- standardCost: Number(itemCostRow?.standardCost ?? 0),
- itemPostingGroupId: itemCostRow?.itemPostingGroupId ?? null,
- };
- // Entity STATE drives the accounting side, not methodType:
- // - Available (picked / in stock) → scrap FROM STOCK (Cr inventory)
- // - Consumed (already issued into the parent) → relieve WIP (Cr WIP)
- const isConsumed = entity.status === "Consumed";
+ if (materialId) {
+ const material = await trx
+ .selectFrom("jobMaterial")
+ .where("id", "=", materialId)
+ .selectAll()
+ .executeTakeFirst();
- const scrapWorkCenterId = material.jobOperationId
- ? ((
- await trx
- .selectFrom("jobOperation")
- .select(["workCenterId"])
- .where("id", "=", material.jobOperationId)
- .executeTakeFirst()
- )?.workCenterId ?? null)
- : null;
- const scrapExtraDimensions = [
- { entityType: "ScrapReason", valueId: scrapReasonId },
- ...(scrapWorkCenterId
- ? [{ entityType: "WorkCenter", valueId: scrapWorkCenterId }]
- : []),
- { entityType: "Employee", valueId: userId },
- ];
+ let storageUnitId: string | null | undefined;
+ // Prioritize material.storageUnitId if available
+ if (material?.storageUnitId) {
+ storageUnitId = material.storageUnitId;
+ } else if (material?.defaultStorageUnit) {
+ const pickMethod = await trx
+ .selectFrom("pickMethod")
+ .where("itemId", "=", itemId)
+ .where("locationId", "=", job?.locationId!)
+ .select("defaultStorageUnitId")
+ .executeTakeFirst();
+ storageUnitId = pickMethod?.defaultStorageUnitId;
+ } else {
+ storageUnitId = await getStorageUnitWithHighestQuantity(
+ trx,
+ itemId,
+ job?.locationId!
+ );
+ }
- if (!isConsumed) {
- // AVAILABLE → scrap from stock (Dr scrapAccount / Cr inventory via
- // the shared adjustment core) at the entity's actual on-hand bin.
- // quantityIssued is untouched — it was never consumed.
- const ledgerRows = await trx
- .selectFrom("itemLedger")
- .select(["trackedEntityId", "storageUnitId", "quantity"])
- .where("trackedEntityId", "=", trackedEntityId)
- .execute();
- const bin = resolveTrackedEntityBin(ledgerRows, trackedEntityId);
+ const quantityToIssue =
+ adjustmentType === "Positive Adjmt."
+ ? Number(quantity)
+ : adjustmentType === "Negative Adjmt."
+ ? Number(quantity)
+ : Number(quantity) - Number(material?.quantityIssued); // set quantity
- await bookAdjustment(trx, {
- ledger: {
- postingDate: todayScrap,
- itemId: consumedItemId,
- quantity: -Math.abs(quantity),
- locationId: job?.locationId ?? null,
- storageUnitId: bin,
- trackedEntityId,
- entryType: "Negative Adjmt.",
- documentType: "Scrap",
- documentId: job?.id ?? null,
- scrapReasonId,
- companyId,
- createdBy: userId,
- },
- item: {
- itemTrackingType: itemRow?.itemTrackingType ?? null,
- replenishmentSystem: itemRow?.replenishmentSystem ?? null,
- itemPostingGroupId: resolvedItemCost.itemPostingGroupId,
- },
- itemCost: {
- costingMethod: resolvedItemCost.costingMethod,
- unitCost: resolvedItemCost.unitCost,
- standardCost: resolvedItemCost.standardCost,
- },
- accounting:
- accountingEnabledScrap &&
- accountDefaultsScrap?.data &&
- accountingPeriodIdScrap
- ? {
- accountingPeriodId: accountingPeriodIdScrap,
- accountDefaults: {
- rawMaterialsAccount:
- accountDefaultsScrap.data.rawMaterialsAccount,
- finishedGoodsAccount:
- accountDefaultsScrap.data.finishedGoodsAccount,
- inventoryAdjustmentVarianceAccount:
- accountDefaultsScrap.data
- .inventoryAdjustmentVarianceAccount,
- },
- offsetAccount:
- accountDefaultsScrap.data.scrapAccount ??
- accountDefaultsScrap.data
- .inventoryAdjustmentVarianceAccount,
- offsetDescription: "Scrap Account",
- description: `Scrap — ${item?.readableIdWithRevision ?? ""}`,
- userId,
- dimensions: Object.fromEntries(dimensionMapScrap),
- extraDimensions: scrapExtraDimensions,
- }
- : null,
- });
- } else {
- // CONSUMED → the material cost was moved into WIP at consumption.
- // Relieve it to scrap (Dr scrapAccount / Cr WIP at the item's unit
- // cost — materials-only, spec decision 6) and reopen the material
- // requirement so a replacement can be issued.
- const scrapCost = resolvedItemCost.unitCost * quantity;
- if (
- accountingEnabledScrap &&
- accountDefaultsScrap?.data &&
- accountingPeriodIdScrap &&
- scrapCost > 0
- ) {
- const journalEntryId = await getNextSequence(
- trx,
- "journalEntry",
- companyId
- );
- const journalResult = await trx
- .insertInto("journal")
- .values({
- journalEntryId,
- accountingPeriodId: accountingPeriodIdScrap,
- description: `Scrap — ${item?.readableIdWithRevision ?? ""}`,
- postingDate: todayScrap,
+ if (material && material.methodType !== "Make to Order") {
+ let remaining = Number(quantityToIssue);
+ if (adjustmentType !== "Positive Adjmt." && remaining > 0) {
+ const budgets = orderOldFirst(
+ await getPickedBudgets(trx, {
+ material,
+ locationId: job?.locationId!,
+ companyId,
+ opStorageUnitId: await getOperationLinesideBin(trx, {
+ jobOperationId: material.jobOperationId,
+ companyId,
+ }),
+ }),
+ material.itemId
+ );
+ const allocation = allocateAcrossBudgets(
+ remaining,
+ budgets,
+ Number(material.quantity ?? 0)
+ );
+ remaining = allocation.remaining;
+ for (const take of allocation.takes) {
+ if (!take.budget.isInventory) continue;
+ for (const row of splitTakeByBin(take)) {
+ itemLedgerInserts.push({
+ entryType: "Consumption",
+ documentType: "Job Consumption",
+ documentId: material.jobId,
+ documentLineId: id,
+ companyId,
+ itemId: take.budget.itemId,
+ locationId: job?.locationId,
+ storageUnitId: row.storageUnitId,
+ quantity: -row.quantity,
+ createdBy: userId,
+ });
+ }
+ }
+ }
+ if (item?.itemTrackingType === "Inventory" && remaining !== 0) {
+ itemLedgerInserts.push({
+ entryType: "Consumption",
+ documentType: "Job Consumption",
+ documentId: material.jobId,
+ documentLineId: id,
companyId,
- sourceType: "Job Consumption",
- status: "Posted",
- postedAt: new Date().toISOString(),
- postedBy: userId,
+ itemId: material.itemId,
+ locationId: job?.locationId,
+ storageUnitId,
+ quantity:
+ adjustmentType === "Positive Adjmt."
+ ? Number(remaining)
+ : -Number(remaining),
createdBy: userId,
- })
- .returning(["id"])
- .executeTakeFirstOrThrow();
-
- const scrapAccount =
- accountDefaultsScrap.data.scrapAccount ??
- accountDefaultsScrap.data.inventoryAdjustmentVarianceAccount;
- const journalLineReference = nanoid();
- const journalLineResults = await trx
- .insertInto("journalLine")
- .values([
- {
- journalId: journalResult.id,
- accountId: scrapAccount,
- description: "Scrap Account",
- amount: debit("expense", scrapCost),
- quantity,
- documentType: "Scrap",
- documentId: job?.id ?? null,
- documentLineReference: `scrapTrackedEntity:${materialId}`,
- journalLineReference,
- companyId,
- },
- {
- journalId: journalResult.id,
- accountId: accountDefaultsScrap.data.workInProgressAccount,
- description: "WIP Account",
- amount: credit("asset", scrapCost),
- quantity,
- documentType: "Scrap",
- documentId: job?.id ?? null,
- documentLineReference: `scrapTrackedEntity:${materialId}`,
- journalLineReference,
- companyId,
- },
- ])
- .returning(["id"])
- .execute();
-
- const scrapDimensionValues: Array<[string, string | null]> = [
- ["Item", consumedItemId],
- ["ItemPostingGroup", resolvedItemCost.itemPostingGroupId],
- ["Location", job?.locationId ?? null],
- ["ScrapReason", scrapReasonId],
- ["WorkCenter", scrapWorkCenterId],
- ["Employee", userId],
- ];
- const dimensionInserts = journalLineResults.flatMap((line) =>
- scrapDimensionValues
- .filter(
- ([entityType, valueId]) =>
- dimensionMapScrap.has(entityType) && valueId
- )
- .map(([entityType, valueId]) => ({
- journalLineId: line.id,
- dimensionId: dimensionMapScrap.get(entityType)!,
- valueId: valueId as string,
- companyId,
- }))
- );
- if (dimensionInserts.length > 0) {
- await trx
- .insertInto("journalLineDimension")
- .values(dimensionInserts)
- .execute();
+ });
}
}
- // Reopen the requirement — the consumed part is gone, so the
- // assembly needs a replacement issued.
- const currentQuantityIssued = Number(material.quantityIssued) || 0;
await trx
.updateTable("jobMaterial")
.set({
- quantityIssued: Math.max(0, currentQuantityIssued - quantity),
+ // A positive adjustment returns material to inventory, so it
+ // reduces quantityIssued — otherwise the backflush cap sees
+ // returned material as still issued.
+ quantityIssued:
+ (Number(material?.quantityIssued) ?? 0) +
+ (adjustmentType === "Positive Adjmt."
+ ? -Number(quantityToIssue)
+ : Number(quantityToIssue)),
})
.where("id", "=", materialId)
.execute();
- }
-
- // Replacement flow ("made 3, scrapped 1 → make 1 more"): only a
- // Make-to-Order subassembly can be re-made in place. Reopen its
- // routing, spawn the replacement serial, and record a rework row.
- if (makeReplacement && job) {
- const subMakeMethod = await trx
- .selectFrom("jobMakeMethod")
- .select(["id", "itemId", "requiresSerialTracking"])
- .where("parentMaterialId", "=", material.id!)
- .where("companyId", "=", companyId)
- .executeTakeFirst();
- if (subMakeMethod) {
- didReplace = true;
- await applyScrapReplacement(trx, {
- jobMakeMethodId: subMakeMethod.id,
- jobId: job.id,
- companyId,
- userId,
- });
+ if (itemLedgerInserts.length > 0) {
+ await trx
+ .insertInto("itemLedger")
+ .values(itemLedgerInserts)
+ .execute();
- if (subMakeMethod.requiresSerialTracking && subMakeMethod.itemId) {
- let locationCode: string | null = null;
- let locationName: string | null = null;
- if (job.locationId) {
- const loc = await client
- .from("location")
- .select("code, name")
- .eq("id", job.locationId)
- .eq("companyId", companyId)
- .single();
- locationCode = loc.data?.code ?? null;
- locationName = loc.data?.name ?? null;
- }
- const spawnSerials = await getNextSerialNumbers(trx, {
- itemId: subMakeMethod.itemId,
+ // Update pickMethod defaultStorageUnitId if needed for each inserted ledger
+ for (const ledger of itemLedgerInserts) {
+ await updatePickMethodDefaultStorageUnitIfNeeded(
+ trx,
+ ledger.itemId,
+ ledger.locationId,
+ ledger.storageUnitId,
companyId,
- count: 1,
- locationCode,
- locationName,
- });
- await trx
- .insertInto("trackedEntity")
- .values({
- sourceDocument: entity.sourceDocument,
- sourceDocumentId: entity.sourceDocumentId,
- sourceDocumentReadableId: entity.sourceDocumentReadableId,
- quantity: 1,
- status: "Reserved",
- attributes: entity.attributes,
- itemId: subMakeMethod.itemId,
- expirationDate: entity.expirationDate ?? null,
- readableId: spawnSerials[0] ?? null,
- companyId,
- createdBy: userId,
- })
- .execute();
- }
-
- const firstSubOperation = await trx
- .selectFrom("jobOperation")
- .select(["id"])
- .where("jobMakeMethodId", "=", subMakeMethod.id)
- .orderBy("order", "asc")
- .executeTakeFirst();
- const scrapReason = await trx
- .selectFrom("scrapReason")
- .select(["name"])
- .where("id", "=", scrapReasonId)
- .where("companyId", "=", companyId)
- .executeTakeFirst();
- if (firstSubOperation && material.jobOperationId) {
- await trx
- .insertInto("rework")
- .values({
- jobId: job.id,
- triggeredAtJobOperationId: material.jobOperationId,
- targetJobOperationId: firstSubOperation.id,
- reason: scrapReason?.name ?? "Scrap",
- quantity,
- requestedById: userId,
- companyId,
- })
- .execute();
+ userId
+ );
}
}
- }
- });
-
- // Reschedule outside the transaction when the routing was reopened.
- if (didReplace) {
- try {
- const supabaseUrl = Deno.env.get("SUPABASE_URL");
- const serviceRoleKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY");
- await fetch(`${supabaseUrl}/functions/v1/reschedule`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${serviceRoleKey}`,
- },
- body: JSON.stringify({
- jobId: jobMaterial.data.jobId,
+ } else {
+ let storageUnitId: string | null | undefined;
+ if (item?.itemTrackingType === "Inventory") {
+ const pickMethod = await trx
+ .selectFrom("pickMethod")
+ .where("itemId", "=", itemId)
+ .where("locationId", "=", job?.locationId!)
+ .select("defaultStorageUnitId")
+ .executeTakeFirst();
+
+ storageUnitId =
+ pickMethod?.defaultStorageUnitId ??
+ (await getStorageUnitWithHighestQuantity(
+ trx,
+ itemId,
+ job?.locationId!
+ ));
+
+ itemLedgerInserts.push({
+ entryType: "Consumption",
+ documentType: "Job Consumption",
+ documentId: jobOperation?.jobId,
+ documentLineId: id,
companyId,
- userId,
- }),
- // The scrap transaction already committed; don't let a stalled
- // reschedule hold the request open until the platform kills it.
- signal: AbortSignal.timeout(10_000),
- });
- } catch (rescheduleError) {
- logger.error("Failed to trigger reschedule after scrap", {
- error: String((rescheduleError as Error)?.stack ?? rescheduleError),
- });
+ itemId: itemId!,
+ quantity:
+ adjustmentType === "Positive Adjmt."
+ ? Number(quantity)
+ : -Number(quantity),
+ locationId: job?.locationId,
+ storageUnitId,
+ createdBy: userId,
+ });
+ }
+
+ const itemCost = await trx
+ .selectFrom("itemCost")
+ .where("itemId", "=", itemId!)
+ .select("unitCost")
+ .executeTakeFirst();
+
+ const newJobMaterial = await trx
+ .insertInto("jobMaterial")
+ .values({
+ companyId,
+ createdBy: userId,
+ description: item?.name ?? "",
+ estimatedQuantity: 0,
+ itemId: itemId!,
+ itemType: item?.type ?? "Part",
+ jobId: jobOperation?.jobId!,
+ jobMakeMethodId: jobOperation?.jobMakeMethodId!,
+ jobOperationId: id,
+ storageUnitId: storageUnitId ?? undefined,
+ methodType: "Pull from Inventory",
+ quantity: 0,
+ quantityIssued: Number(quantity ?? 0),
+ unitCost: itemCost?.unitCost ?? 0,
+ })
+ .returning("id")
+ .executeTakeFirst();
+
+ // Scope this unplanned part to the step it was issued on (assembly
+ // view), so it shows on that step rather than as a General material.
+ if (jobOperationStepId && newJobMaterial?.id) {
+ await trx
+ .insertInto("jobMaterialStep")
+ .values({
+ jobMaterialId: newJobMaterial.id,
+ jobOperationStepId,
+ })
+ .onConflict((oc) => oc.doNothing())
+ .execute();
+ }
+
+ if (itemLedgerInserts.length > 0) {
+ await trx
+ .insertInto("itemLedger")
+ .values(itemLedgerInserts)
+ .execute();
+
+ // Update pickMethod defaultStorageUnitId if needed for each inserted ledger
+ for (const ledger of itemLedgerInserts) {
+ await updatePickMethodDefaultStorageUnitIfNeeded(
+ trx,
+ ledger.itemId,
+ ledger.locationId,
+ ledger.storageUnitId,
+ companyId,
+ userId
+ );
+ }
+ }
}
- }
- return jsonResponse({
- success: true,
+ if (accountingEnabled && accountDefaults?.data && itemLedgerInserts.length > 0) {
+ const jobOperation = await trx
+ .selectFrom("jobOperation")
+ .where("id", "=", id)
+ .select(["jobId"])
+ .executeTakeFirst();
+
+ const jobRecord = jobOperation?.jobId
+ ? await trx
+ .selectFrom("job")
+ .where("id", "=", jobOperation.jobId)
+ .select(["itemId", "locationId"])
+ .executeTakeFirst()
+ : null;
+
+ await createMaterialWipEntries(trx, {
+ consumptionLedgers: itemLedgerInserts.map((l) => ({
+ itemId: l.itemId as string,
+ quantity: Number(l.quantity),
+ })),
+ jobId: jobOperation?.jobId!,
+ operationId: id,
+ description: "Manual Material Issue",
+ wipAccount: accountDefaults.data.workInProgressAccount,
+ rawMaterialsAccount: accountDefaults.data.rawMaterialsAccount,
+ finishedGoodsAccount: accountDefaults.data.finishedGoodsAccount,
+ dimensionMap,
+
+ jobLocationId: jobRecord?.locationId ?? null,
+ client,
+ db,
+ companyId,
+ userId,
+ });
+ }
});
+ break;
}
- case "trackedEntitiesToOperation": {
+ case "scrapTrackedEntity": {
const {
+ trackedEntityId,
materialId,
- jobOperationId,
- itemId,
parentTrackedEntityId,
- children,
- jobOperationStepId,
- unitNumber,
- overrideExpired,
- overrideReason,
+ scrapReasonId,
+ makeReplacement,
companyId,
userId,
} = validatedPayload;
+ const client = await requirePermissions(req, companyId, userId, {
+ update: "production",
+ });
- if (!parentTrackedEntityId) {
- throw new Error("Parent ID is required");
- }
+ const [trackedEntity, jobMaterial] = await Promise.all([
+ client
+ .from("trackedEntity")
+ .select("*")
+ .eq("id", trackedEntityId)
+ .eq("companyId", companyId)
+ .single(),
+ client
+ .from("jobMaterial")
+ .select("*")
+ .eq("id", materialId)
+ .eq("companyId", companyId)
+ .single(),
+ ]);
- if (children.length === 0) {
- throw new Error("Children are required");
+ if (!trackedEntity.data) {
+ throw new Error("Tracked entity not found");
}
- // Either materialId or (jobOperationId + itemId) must be provided
- if (!materialId && (!jobOperationId || !itemId)) {
- throw new Error(
- "Either materialId or both jobOperationId and itemId must be provided"
- );
+ if (!jobMaterial.data) {
+ throw new Error("Job material not found");
+ }
+ if (trackedEntity.data.status === "Scrapped") {
+ throw new Error("Tracked entity has already been scrapped");
}
- const client = await requirePermissions(req, companyId, userId, { update: "production" });
- const companyToday = datetime.today(await getCompanyTimeZone(client, companyId));
-
- const [accountingSettingsTracked, companyRecordTracked] = await Promise.all([
+ const [accountingSettingsScrap, companyRecordScrap] = await Promise.all([
client
.from("companySettings")
.select("accountingEnabled")
@@ -2813,278 +3024,82 @@ serve(async (req: Request) => {
.single(),
client.from("company").select("companyGroupId").eq("id", companyId).single(),
]);
- if (companyRecordTracked.error) throw new Error("Failed to fetch company");
- const accountingEnabledTracked = accountingSettingsTracked.data?.accountingEnabled ?? false;
+ if (companyRecordScrap.error) throw new Error("Failed to fetch company");
+ const accountingEnabledScrap = accountingSettingsScrap.data?.accountingEnabled ?? false;
- const accountDefaultsTracked = accountingEnabledTracked
+ const accountDefaultsScrap = accountingEnabledScrap
? await getDefaultPostingGroup(client, companyId)
: null;
- if (accountingEnabledTracked && (accountDefaultsTracked?.error || !accountDefaultsTracked?.data)) {
+ if (accountingEnabledScrap && (accountDefaultsScrap?.error || !accountDefaultsScrap?.data)) {
throw new Error("Error getting account defaults");
}
- const dimensionsTracked = accountingEnabledTracked
+ const dimensionsScrap = accountingEnabledScrap
? await client
.from("dimension")
.select("id, entityType")
- .eq("companyGroupId", companyRecordTracked.data.companyGroupId)
+ .eq("companyGroupId", companyRecordScrap.data.companyGroupId)
.eq("active", true)
- .in("entityType", ["ItemPostingGroup", "Item", "Location"])
+ .in("entityType", [
+ "ItemPostingGroup",
+ "Item",
+ "Location",
+ "ScrapReason",
+ "WorkCenter",
+ "Employee",
+ ])
: null;
- const dimensionMapTracked = new Map<string, string>();
- if (dimensionsTracked?.data) {
- for (const dim of dimensionsTracked.data) {
- if (dim.entityType) dimensionMapTracked.set(dim.entityType, dim.id);
+ const dimensionMapScrap = new Map<string, string>();
+ if (dimensionsScrap?.data) {
+ for (const dim of dimensionsScrap.data) {
+ if (dim.entityType) dimensionMapScrap.set(dim.entityType, dim.id);
}
}
- let expiredWarning: string | undefined;
+ const todayScrap = datetime
+ .today(await getCompanyTimeZone(client, companyId))
+ .toString();
+ // Resolve the period BEFORE the transaction parks the (size 1) pool.
+ const accountingPeriodIdScrap = accountingEnabledScrap
+ ? await getCurrentAccountingPeriod(client, companyId, db, todayScrap)
+ : null;
- const splitEntities = await db.transaction().execute(async (trx) => {
- const trackedEntities = await trx
- .selectFrom("trackedEntity")
- .where(
- "id",
- "in",
- children.map((child) => child.trackedEntityId)
- )
- .selectAll()
- .execute();
+ let didReplace = false;
+ await db.transaction().execute(async (trx) => {
+ const entity = trackedEntity.data!;
+ const material = jobMaterial.data!;
+ const quantity = Number(entity.quantity);
- const itemLedgers = await trx
- .selectFrom("itemLedger")
- .where("trackedEntityId", "in", [
- ...children.map((child) => child.trackedEntityId),
- ])
- .orderBy("createdBy", "desc")
- .selectAll()
- .execute();
+ const job = await trx
+ .selectFrom("job")
+ .select(["id", "jobId", "locationId", "itemId"])
+ .where("id", "=", material.jobId!)
+ .executeTakeFirst();
- if (trackedEntities.length !== children.length) {
- throw new Error("Tracked entities not found");
- }
-
- if (trackedEntities.some((entity) => entity.status !== "Available")) {
- throw new Error("Tracked entities are not available");
- }
-
- // Expiry policy gate. Reads companySettings.inventoryShelfLife.
- const expiredPolicy = await getExpiredEntityPolicy(trx, companyId);
- const expiredCheck = checkExpiredEntities(
- trackedEntities.map((e) => ({
- id: e.id,
- expirationDate: e.expirationDate,
- })),
- expiredPolicy,
- { allowed: !!overrideExpired, reason: overrideReason ?? null },
- companyToday
- );
- if (!expiredCheck.ok) {
- throw new Error(expiredCheck.reason);
- }
- if (expiredCheck.warning) {
- expiredWarning = expiredCheck.warning;
- }
-
- let jobMaterial: Awaited<
- ReturnType<
- ReturnType<typeof trx.selectFrom<"jobMaterial">>["selectAll"]
- >
- >[0] | undefined;
- let actualMaterialId: string | undefined = materialId;
- const firstTrackedEntity = trackedEntities[0];
-
- if (materialId) {
- // Existing behavior: fetch the jobMaterial
- jobMaterial = await trx
- .selectFrom("jobMaterial")
- .where("id", "=", materialId)
- .selectAll()
- .executeTakeFirst();
-
- // Check if any tracked entity has a different sourceDocumentId than the material's itemId
- if (
- firstTrackedEntity &&
- jobMaterial &&
- firstTrackedEntity.sourceDocumentId !== jobMaterial.itemId
- ) {
- // Create a new jobMaterial for the tracked entity's item
- const totalChildQuantity = children.reduce((sum, child) => {
- return sum + Number(child.quantity);
- }, 0);
-
- const itemCost = await trx
- .selectFrom("itemCost")
- .where("itemId", "=", firstTrackedEntity.sourceDocumentId!)
- .select("unitCost")
- .executeTakeFirst();
-
- const newJobMaterial = await trx
- .insertInto("jobMaterial")
- .values({
- companyId,
- createdBy: userId,
- description: firstTrackedEntity.sourceDocumentReadableId ?? "",
- estimatedQuantity: 0,
- itemId: firstTrackedEntity.sourceDocumentId!,
- jobId: jobMaterial.jobId!,
- jobMakeMethodId: jobMaterial.jobMakeMethodId,
- jobOperationId: jobMaterial.jobOperationId,
- itemType: jobMaterial.itemType,
- methodType: jobMaterial.methodType,
- quantity: 0,
- quantityIssued: totalChildQuantity,
- requiresBatchTracking: jobMaterial.requiresBatchTracking,
- requiresSerialTracking: jobMaterial.requiresSerialTracking,
- unitCost: itemCost?.unitCost ?? 0,
- })
- .returning("id")
- .executeTakeFirstOrThrow();
-
- actualMaterialId = newJobMaterial.id!;
-
- // Fetch the newly created jobMaterial
- jobMaterial = await trx
- .selectFrom("jobMaterial")
- .where("id", "=", actualMaterialId)
- .selectAll()
- .executeTakeFirstOrThrow();
- }
- } else if (jobOperationId && itemId) {
- // New behavior: create a jobMaterial on the fly
- const jobOperation = await trx
- .selectFrom("jobOperation")
- .where("id", "=", jobOperationId)
- .select(["jobId", "jobMakeMethodId"])
- .executeTakeFirst();
-
- if (!jobOperation) {
- throw new Error("Job operation not found");
- }
-
- const item = await trx
- .selectFrom("item")
- .where("id", "=", itemId)
- .select(["name", "type", "itemTrackingType", "defaultMethodType"])
- .executeTakeFirst();
-
- if (!item) {
- throw new Error("Item not found");
- }
-
- const totalChildQuantity = children.reduce((sum, child) => {
- return sum + Number(child.quantity);
- }, 0);
-
- const itemCost = await trx
- .selectFrom("itemCost")
- .where("itemId", "=", itemId)
- .select("unitCost")
- .executeTakeFirst();
-
- const newJobMaterial = await trx
- .insertInto("jobMaterial")
- .values({
- companyId,
- createdBy: userId,
- description: item.name ?? "",
- estimatedQuantity: 0,
- itemId: itemId,
- jobId: jobOperation.jobId!,
- jobMakeMethodId: jobOperation.jobMakeMethodId,
- jobOperationId: jobOperationId,
- itemType: item.type ?? "Part",
- methodType: item.defaultMethodType ?? "Pull from Inventory",
- quantity: 0,
- quantityIssued: totalChildQuantity,
- requiresBatchTracking: item.itemTrackingType === "Batch",
- requiresSerialTracking: item.itemTrackingType === "Serial",
- unitCost: itemCost?.unitCost ?? 0,
- })
- .returning("id")
- .executeTakeFirstOrThrow();
-
- actualMaterialId = newJobMaterial.id!;
-
- // Scope this unplanned tracked part to the step it was issued on
- // (assembly view), so it shows on that step rather than as General.
- if (jobOperationStepId) {
- await trx
- .insertInto("jobMaterialStep")
- .values({
- jobMaterialId: actualMaterialId,
- jobOperationStepId,
- })
- .onConflict((oc) => oc.doNothing())
- .execute();
- }
-
- // Fetch the newly created jobMaterial
- jobMaterial = await trx
- .selectFrom("jobMaterial")
- .where("id", "=", actualMaterialId)
- .selectAll()
- .executeTakeFirstOrThrow();
- }
-
- if (!jobMaterial) {
- throw new Error("Job material not found");
- }
-
- // Get item details
const item = await trx
.selectFrom("item")
- .where("id", "=", jobMaterial?.itemId!)
+ .where("id", "=", material.itemId!)
.select(["readableIdWithRevision"])
.executeTakeFirst();
- // Get job location
- const job = await trx
- .selectFrom("job")
- .select(["id", "locationId"])
- .where("id", "=", jobMaterial?.jobId!)
- .executeTakeFirst();
-
- // Get parent tracked entity details
- const parentTrackedEntity = await trx
- .selectFrom("trackedEntity")
- .where("id", "=", parentTrackedEntityId)
- .select([
- "id",
- "sourceDocumentId",
- "quantity",
- "attributes",
- "status",
- ])
- .executeTakeFirst();
-
- if (!parentTrackedEntity) {
- throw new Error("Parent tracked entity not found");
- }
-
- // Create tracked activity
+ // Scrap genealogy (was: Consume + attributes.Scrapped). The entity
+ // keeps its full input tree; status is the terminal marker.
const activityId = nanoid();
await trx
.insertInto("trackedActivity")
.values({
id: activityId,
- type: "Consume",
+ type: "Scrap",
sourceDocument: "Job Material",
- sourceDocumentId: actualMaterialId,
+ sourceDocumentId: materialId,
sourceDocumentReadableId: item?.readableIdWithRevision ?? "",
attributes: {
Job: job?.id!,
- "Job Make Method": jobMaterial?.jobMakeMethodId!,
- "Job Material": jobMaterial?.id!,
+ "Job Make Method": material.jobMakeMethodId!,
+ "Job Material": material.id!,
+ "Scrap Reason": scrapReasonId,
Employee: userId,
- // Assembly view: which step + 1-based unit this consume was for, so
- // the MES can attribute issued quantities per-unit even for a batch
- // parent (where all units share one lot entity).
- ...(jobOperationStepId
- ? { "Job Operation Step": jobOperationStepId }
- : {}),
- ...(unitNumber !== undefined ? { Unit: unitNumber } : {}),
},
companyId,
createdBy: userId,
@@ -3092,256 +3107,796 @@ serve(async (req: Request) => {
.execute();
await trx
- .insertInto("trackedActivityOutput")
+ .insertInto("trackedActivityInput")
.values({
trackedActivityId: activityId,
- trackedEntityId: parentTrackedEntityId,
- quantity: parentTrackedEntity.quantity,
+ trackedEntityId,
+ quantity,
companyId,
createdBy: userId,
})
.execute();
- const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =
- [];
- const trackedActivityInputs: Database["public"]["Tables"]["trackedActivityInput"]["Insert"][] =
- [];
+ if (parentTrackedEntityId) {
+ await trx
+ .insertInto("trackedActivityOutput")
+ .values({
+ trackedActivityId: activityId,
+ trackedEntityId: parentTrackedEntityId,
+ quantity,
+ companyId,
+ createdBy: userId,
+ })
+ .execute();
+ }
- const splitEntities: Array<{
- originalId: string;
- newId: string;
- readableId: string;
- quantity: number;
- remainingQuantity: number;
- }> = [];
+ await trx
+ .updateTable("trackedEntity")
+ .set({
+ status: "Scrapped",
+ })
+ .where("id", "=", trackedEntityId)
+ .execute();
- // Process each child tracked entity
- for (const child of children) {
- const trackedEntity = trackedEntities.find(
- (entity) => entity.id === child.trackedEntityId
- );
- if (!trackedEntity) {
- throw new Error("Tracked entity not found");
+ const consumedItemId = entity.sourceDocumentId ?? material.itemId!;
+ const [itemRow, itemCostRow] = await Promise.all([
+ trx
+ .selectFrom("item")
+ .select(["itemTrackingType", "replenishmentSystem"])
+ .where("id", "=", consumedItemId)
+ .executeTakeFirst(),
+ trx
+ .selectFrom("itemCost")
+ .select([
+ "costingMethod",
+ "unitCost",
+ "standardCost",
+ "itemPostingGroupId",
+ ])
+ .where("itemId", "=", consumedItemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst(),
+ ]);
+ // A missing itemCost must not fail the scrap — fall back to zero
+ // cost (no journal value) so the physical/traceability scrap still
+ // records; accounting can be reconciled later.
+ const resolvedItemCost = {
+ costingMethod: itemCostRow?.costingMethod ?? "Average",
+ unitCost: Number(itemCostRow?.unitCost ?? 0),
+ standardCost: Number(itemCostRow?.standardCost ?? 0),
+ itemPostingGroupId: itemCostRow?.itemPostingGroupId ?? null,
+ };
+
+ // Entity STATE drives the accounting side, not methodType:
+ // - Available (picked / in stock) → scrap FROM STOCK (Cr inventory)
+ // - Consumed (already issued into the parent) → relieve WIP (Cr WIP)
+ const isConsumed = entity.status === "Consumed";
+
+ const scrapWorkCenterId = material.jobOperationId
+ ? ((
+ await trx
+ .selectFrom("jobOperation")
+ .select(["workCenterId"])
+ .where("id", "=", material.jobOperationId)
+ .executeTakeFirst()
+ )?.workCenterId ?? null)
+ : null;
+ const scrapExtraDimensions = [
+ { entityType: "ScrapReason", valueId: scrapReasonId },
+ ...(scrapWorkCenterId
+ ? [{ entityType: "WorkCenter", valueId: scrapWorkCenterId }]
+ : []),
+ { entityType: "Employee", valueId: userId },
+ ];
+
+ if (!isConsumed) {
+ // AVAILABLE → scrap from stock (Dr scrapAccount / Cr inventory via
+ // the shared adjustment core) at the entity's actual on-hand bin.
+ // quantityIssued is untouched — it was never consumed.
+ const ledgerRows = await trx
+ .selectFrom("itemLedger")
+ .select(["trackedEntityId", "storageUnitId", "quantity"])
+ .where("trackedEntityId", "=", trackedEntityId)
+ .execute();
+ const bin = resolveTrackedEntityBin(ledgerRows, trackedEntityId);
+
+ await bookAdjustment(trx, {
+ ledger: {
+ postingDate: todayScrap,
+ itemId: consumedItemId,
+ quantity: -Math.abs(quantity),
+ locationId: job?.locationId ?? null,
+ storageUnitId: bin,
+ trackedEntityId,
+ entryType: "Negative Adjmt.",
+ documentType: "Scrap",
+ documentId: job?.id ?? null,
+ scrapReasonId,
+ companyId,
+ createdBy: userId,
+ },
+ item: {
+ itemTrackingType: itemRow?.itemTrackingType ?? null,
+ replenishmentSystem: itemRow?.replenishmentSystem ?? null,
+ itemPostingGroupId: resolvedItemCost.itemPostingGroupId,
+ },
+ itemCost: {
+ costingMethod: resolvedItemCost.costingMethod,
+ unitCost: resolvedItemCost.unitCost,
+ standardCost: resolvedItemCost.standardCost,
+ },
+ accounting:
+ accountingEnabledScrap &&
+ accountDefaultsScrap?.data &&
+ accountingPeriodIdScrap
+ ? {
+ accountingPeriodId: accountingPeriodIdScrap,
+ accountDefaults: {
+ rawMaterialsAccount:
+ accountDefaultsScrap.data.rawMaterialsAccount,
+ finishedGoodsAccount:
+ accountDefaultsScrap.data.finishedGoodsAccount,
+ inventoryAdjustmentVarianceAccount:
+ accountDefaultsScrap.data
+ .inventoryAdjustmentVarianceAccount,
+ },
+ offsetAccount:
+ accountDefaultsScrap.data.scrapAccount ??
+ accountDefaultsScrap.data
+ .inventoryAdjustmentVarianceAccount,
+ offsetDescription: "Scrap Account",
+ description: `Scrap — ${item?.readableIdWithRevision ?? ""}`,
+ userId,
+ dimensions: Object.fromEntries(dimensionMapScrap),
+ extraDimensions: scrapExtraDimensions,
+ }
+ : null,
+ });
+ } else {
+ // CONSUMED → the material cost was moved into WIP at consumption.
+ // Relieve it to scrap (Dr scrapAccount / Cr WIP at the item's unit
+ // cost — materials-only, spec decision 6) and reopen the material
+ // requirement so a replacement can be issued.
+ const scrapCost = resolvedItemCost.unitCost * quantity;
+ if (
+ accountingEnabledScrap &&
+ accountDefaultsScrap?.data &&
+ accountingPeriodIdScrap &&
+ scrapCost > 0
+ ) {
+ const journalEntryId = await getNextSequence(
+ trx,
+ "journalEntry",
+ companyId
+ );
+ const journalResult = await trx
+ .insertInto("journal")
+ .values({
+ journalEntryId,
+ accountingPeriodId: accountingPeriodIdScrap,
+ description: `Scrap — ${item?.readableIdWithRevision ?? ""}`,
+ postingDate: todayScrap,
+ companyId,
+ sourceType: "Job Consumption",
+ status: "Posted",
+ postedAt: new Date().toISOString(),
+ postedBy: userId,
+ createdBy: userId,
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ const scrapAccount =
+ accountDefaultsScrap.data.scrapAccount ??
+ accountDefaultsScrap.data.inventoryAdjustmentVarianceAccount;
+ const journalLineReference = nanoid();
+ const journalLineResults = await trx
+ .insertInto("journalLine")
+ .values([
+ {
+ journalId: journalResult.id,
+ accountId: scrapAccount,
+ description: "Scrap Account",
+ amount: debit("expense", scrapCost),
+ quantity,
+ documentType: "Scrap",
+ documentId: job?.id ?? null,
+ documentLineReference: `scrapTrackedEntity:${materialId}`,
+ journalLineReference,
+ companyId,
+ },
+ {
+ journalId: journalResult.id,
+ accountId: accountDefaultsScrap.data.workInProgressAccount,
+ description: "WIP Account",
+ amount: credit("asset", scrapCost),
+ quantity,
+ documentType: "Scrap",
+ documentId: job?.id ?? null,
+ documentLineReference: `scrapTrackedEntity:${materialId}`,
+ journalLineReference,
+ companyId,
+ },
+ ])
+ .returning(["id"])
+ .execute();
+
+ const scrapDimensionValues: Array<[string, string | null]> = [
+ ["Item", consumedItemId],
+ ["ItemPostingGroup", resolvedItemCost.itemPostingGroupId],
+ ["Location", job?.locationId ?? null],
+ ["ScrapReason", scrapReasonId],
+ ["WorkCenter", scrapWorkCenterId],
+ ["Employee", userId],
+ ];
+ const dimensionInserts = journalLineResults.flatMap((line) =>
+ scrapDimensionValues
+ .filter(
+ ([entityType, valueId]) =>
+ dimensionMapScrap.has(entityType) && valueId
+ )
+ .map(([entityType, valueId]) => ({
+ journalLineId: line.id,
+ dimensionId: dimensionMapScrap.get(entityType)!,
+ valueId: valueId as string,
+ companyId,
+ }))
+ );
+ if (dimensionInserts.length > 0) {
+ await trx
+ .insertInto("journalLineDimension")
+ .values(dimensionInserts)
+ .execute();
+ }
}
- const { trackedEntityId, quantity } = child;
- // Partial consume → split: the lineside entity keeps its id and
- // is decremented; a NEW child entity carries the consumed
- // quantity. EVERYTHING below (Consumed status, Consume input,
- // Consumption ledger) books against the child — flipping the
- // entity half without the ledger half would double-count on-hand.
- let consumedEntityId = trackedEntityId;
- if (Number(trackedEntity.quantity) !== quantity) {
- const consumedChildId = nanoid();
- consumedEntityId = consumedChildId;
+ // Reopen the requirement — the consumed part is gone, so the
+ // assembly needs a replacement issued.
+ const currentQuantityIssued = Number(material.quantityIssued) || 0;
+ await trx
+ .updateTable("jobMaterial")
+ .set({
+ quantityIssued: Math.max(0, currentQuantityIssued - quantity),
+ })
+ .where("id", "=", materialId)
+ .execute();
+ }
- const split = buildBatchSplitRecords({
- parent: {
- id: trackedEntity.id!,
- readableId: trackedEntity.readableId,
- quantity: Number(trackedEntity.quantity),
- sourceDocument: trackedEntity.sourceDocument,
- sourceDocumentId: trackedEntity.sourceDocumentId,
- sourceDocumentReadableId:
- trackedEntity.sourceDocumentReadableId,
- itemId:
- trackedEntity.itemId ?? trackedEntity.sourceDocumentId,
- expirationDate: trackedEntity.expirationDate ?? null,
- attributes: trackedEntity.attributes as Record<
- string,
- unknown
- > | null
- },
- drawQuantity: quantity,
- childId: consumedChildId,
- splitActivityId: nanoid(),
- activitySourceDocument: "Job Material",
- activitySourceDocumentId: actualMaterialId,
- bin: {
- storageUnitId: resolveTrackedEntityBin(
- itemLedgers,
- trackedEntityId
- ),
- locationId: job?.locationId ?? null
- },
- itemLedgerItemId: trackedEntity.sourceDocumentId,
+ // Replacement flow ("made 3, scrapped 1 → make 1 more"): only a
+ // Make-to-Order subassembly can be re-made in place. Reopen its
+ // routing, spawn the replacement serial, and record a rework row.
+ if (makeReplacement && job) {
+ const subMakeMethod = await trx
+ .selectFrom("jobMakeMethod")
+ .select(["id", "itemId", "requiresSerialTracking"])
+ .where("parentMaterialId", "=", material.id!)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+
+ if (subMakeMethod) {
+ didReplace = true;
+ await applyScrapReplacement(trx, {
+ jobMakeMethodId: subMakeMethod.id,
+ jobId: job.id,
companyId,
userId,
- postingDate: companyToday.toString(),
- // Created Available; the shared status update below flips the
- // child to Consumed in the same transaction.
- childStatus: "Available",
- extraChildAttributes: {
- ...(jobOperationStepId
- ? { "Job Operation Step": jobOperationStepId }
- : {}),
- ...(unitNumber !== undefined ? { Unit: unitNumber } : {})
- }
});
- // Track split entity for the MES confirmation: quantity = what
- // was consumed (the child), remainingQuantity = what the
- // surviving lineside entity still holds.
- splitEntities.push({
- originalId: trackedEntityId,
- newId: consumedChildId,
- readableId: trackedEntity.sourceDocumentReadableId ?? "",
- quantity,
- remainingQuantity: split.parentUpdate.quantity,
- });
+ if (subMakeMethod.requiresSerialTracking && subMakeMethod.itemId) {
+ let locationCode: string | null = null;
+ let locationName: string | null = null;
+ if (job.locationId) {
+ const loc = await client
+ .from("location")
+ .select("code, name")
+ .eq("id", job.locationId)
+ .eq("companyId", companyId)
+ .single();
+ locationCode = loc.data?.code ?? null;
+ locationName = loc.data?.name ?? null;
+ }
+ const spawnSerials = await getNextSerialNumbers(trx, {
+ itemId: subMakeMethod.itemId,
+ companyId,
+ count: 1,
+ locationCode,
+ locationName,
+ });
+ await trx
+ .insertInto("trackedEntity")
+ .values({
+ sourceDocument: entity.sourceDocument,
+ sourceDocumentId: entity.sourceDocumentId,
+ sourceDocumentReadableId: entity.sourceDocumentReadableId,
+ quantity: 1,
+ status: "Reserved",
+ attributes: entity.attributes,
+ itemId: subMakeMethod.itemId,
+ expirationDate: entity.expirationDate ?? null,
+ readableId: spawnSerials[0] ?? null,
+ companyId,
+ createdBy: userId,
+ })
+ .execute();
+ }
+
+ const firstSubOperation = await trx
+ .selectFrom("jobOperation")
+ .select(["id"])
+ .where("jobMakeMethodId", "=", subMakeMethod.id)
+ .orderBy("order", "asc")
+ .executeTakeFirst();
+ const scrapReason = await trx
+ .selectFrom("scrapReason")
+ .select(["name"])
+ .where("id", "=", scrapReasonId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (firstSubOperation && material.jobOperationId) {
+ await trx
+ .insertInto("rework")
+ .values({
+ jobId: job.id,
+ triggeredAtJobOperationId: material.jobOperationId,
+ targetJobOperationId: firstSubOperation.id,
+ reason: scrapReason?.name ?? "Scrap",
+ quantity,
+ requestedById: userId,
+ companyId,
+ })
+ .execute();
+ }
+ }
+ }
+ });
+
+ // Reschedule outside the transaction when the routing was reopened.
+ if (didReplace) {
+ try {
+ const supabaseUrl = Deno.env.get("SUPABASE_URL");
+ const serviceRoleKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY");
+ await fetch(`${supabaseUrl}/functions/v1/reschedule`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${serviceRoleKey}`,
+ },
+ body: JSON.stringify({
+ jobId: jobMaterial.data.jobId,
+ companyId,
+ userId,
+ }),
+ // The scrap transaction already committed; don't let a stalled
+ // reschedule hold the request open until the platform kills it.
+ signal: AbortSignal.timeout(10_000),
+ });
+ } catch (rescheduleError) {
+ logger.error("Failed to trigger reschedule after scrap", {
+ error: String((rescheduleError as Error)?.stack ?? rescheduleError),
+ });
+ }
+ }
+
+ return jsonResponse({
+ success: true,
+ });
+ }
+ case "trackedEntitiesToOperation": {
+ const {
+ materialId,
+ jobOperationId,
+ itemId,
+ parentTrackedEntityId,
+ children,
+ jobOperationStepId,
+ unitNumber,
+ overrideExpired,
+ overrideReason,
+ companyId,
+ userId,
+ } = validatedPayload;
+
+ if (!parentTrackedEntityId) {
+ throw new Error("Parent ID is required");
+ }
+
+ if (children.length === 0) {
+ throw new Error("Children are required");
+ }
- await trx
- .insertInto("trackedActivity")
- .values(split.activityInsert)
- .execute();
+ // Either materialId or (jobOperationId + itemId) must be provided
+ if (!materialId && (!jobOperationId || !itemId)) {
+ throw new Error(
+ "Either materialId or both jobOperationId and itemId must be provided"
+ );
+ }
- await trx
- .insertInto("trackedEntity")
- .values(split.childEntityInsert)
- .execute();
+ const client = await requirePermissions(req, companyId, userId, { update: "production" });
+ const companyToday = datetime.today(await getCompanyTimeZone(client, companyId));
+ const accounting = await loadConsumeAccountingContext(client, companyId);
- await trx
- .insertInto("trackedActivityInput")
- .values(split.activityInputInsert)
- .execute();
+ const result = await db.transaction().execute((trx) =>
+ consumeTrackedEntitiesIntoOperation(trx, {
+ materialId,
+ jobOperationId,
+ itemId,
+ parentTrackedEntityId,
+ children,
+ jobOperationStepId,
+ unitNumber,
+ overrideExpired,
+ overrideReason,
+ companyId,
+ userId,
+ companyToday,
+ client,
+ ...accounting,
+ })
+ );
- await trx
- .insertInto("trackedActivityOutput")
- .values(split.activityOutputInsert)
- .execute();
+ return jsonResponse({
+ success: true,
+ splitEntities: result.splitEntities,
+ warning: result.warning,
+ });
+ }
+ case "trackedEntitiesToBatch": {
+ const {
+ batchId,
+ itemId,
+ children,
+ overrideExpired,
+ overrideReason,
+ companyId,
+ userId,
+ } = validatedPayload;
- await trx
- .updateTable("trackedEntity")
- .set(split.parentUpdate)
- .where("id", "=", trackedEntityId)
- .execute();
+ if (children.length === 0) {
+ throw new Error("Children are required");
+ }
- // MTO skips ONLY the ledger inserts; entity/activity writes
- // above still happen.
- if (jobMaterial?.methodType !== "Make to Order") {
- itemLedgerInserts.push(...split.ledgerInserts);
- }
- }
+ const client = await requirePermissions(req, companyId, userId, { update: "production" });
+ const companyToday = datetime.today(await getCompanyTimeZone(client, companyId));
+ const accounting = await loadConsumeAccountingContext(client, companyId);
+
+ // Resolve (and lazily create) the accounting period BEFORE the member
+ // transaction opens. getCurrentAccountingPeriod reads over HTTP but
+ // writes in-transaction, so two members inside ONE transaction would
+ // each try to create a missing period — the second cannot see the
+ // first's uncommitted insert and the unique index rolls the whole pick
+ // back. Committed here, every member's read finds it.
+ if (accounting.accountingEnabled) {
+ await getCurrentAccountingPeriod(
+ client,
+ companyId,
+ db,
+ companyToday.toString()
+ );
+ }
- // Consume the drawn entity — the split child, or the whole
- // entity on a full draw.
- await trx
- .updateTable("trackedEntity")
- .set({
- status: "Consumed",
- })
- .where("id", "=", consumedEntityId)
- .execute();
+ const batchResult = await db.transaction().execute(async (trx) => {
+ const batch = await trx
+ .selectFrom("jobOperationBatch")
+ .select(["id", "status"])
+ .where("id", "=", batchId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!batch) {
+ throw new Error("Batch not found");
+ }
+ if (batch.status === "Completed") {
+ throw new Error("Batch is already completed");
+ }
- trackedActivityInputs.push({
- trackedActivityId: activityId,
- trackedEntityId: consumedEntityId,
- quantity,
- companyId,
- createdBy: userId,
- });
+ const members = await trx
+ .selectFrom("jobOperation")
+ .select(["id", "jobId", "jobMakeMethodId"])
+ .where("jobOperationBatchId", "=", batchId)
+ .where("companyId", "=", companyId)
+ .execute();
+ if (members.length === 0) {
+ throw new Error("Batch has no member operations");
+ }
+ const memberIds = members.map((m) => m.id);
+ const memberIdSet = new Set(memberIds);
+ // A member's materials are what its operation view lists: the
+ // operation's make method BOM. A row linked straight to a member
+ // operation stays with it; the rest belong to the member on its make
+ // method (BOMs are usually not assigned per operation, and jobs built
+ // from an item never carry the link).
+ const memberByMakeMethod = new Map(
+ members
+ .filter((m) => m.jobMakeMethodId)
+ .map((m) => [m.jobMakeMethodId as string, m.id])
+ );
- if (jobMaterial?.methodType !== "Make to Order") {
- itemLedgerInserts.push({
- entryType: "Consumption",
- documentType: "Job Consumption",
- documentId: job?.id!,
- companyId,
- itemId: trackedEntity.sourceDocumentId,
- quantity: -quantity,
- locationId: job?.locationId,
- // The split child has no rows in the pre-transaction ledger
- // snapshot — it sits at the parent's resolved bin.
- storageUnitId: resolveTrackedEntityBin(itemLedgers, trackedEntityId),
- trackedEntityId: consumedEntityId,
- createdBy: userId,
- });
+ // Lock the member material rows so a concurrent batch pick (or a
+ // member-level manual issue) cannot double-allocate the remaining
+ // requirement.
+ const materialRows = await trx
+ .selectFrom("jobMaterial")
+ .select([
+ "id",
+ "jobOperationId",
+ "jobMakeMethodId",
+ "estimatedQuantity",
+ "quantityIssued",
+ ])
+ .where("companyId", "=", companyId)
+ .where("itemId", "=", itemId)
+ .where((eb) =>
+ eb.or([
+ eb("jobOperationId", "in", memberIds),
+ ...(memberByMakeMethod.size
+ ? [eb("jobMakeMethodId", "in", [...memberByMakeMethod.keys()])]
+ : []),
+ ])
+ )
+ .forUpdate()
+ .execute();
+
+ const rowByOp = new Map<string, string>();
+ const remainingByOp = new Map<string, number>();
+ for (const row of materialRows) {
+ const opId =
+ row.jobOperationId && memberIdSet.has(row.jobOperationId)
+ ? row.jobOperationId
+ : memberByMakeMethod.get(row.jobMakeMethodId as string);
+ if (!opId) continue;
+ const remaining = Math.max(
+ 0,
+ Number(row.estimatedQuantity ?? 0) - Number(row.quantityIssued ?? 0)
+ );
+ remainingByOp.set(opId, (remainingByOp.get(opId) ?? 0) + remaining);
+ // The write target: an OPEN row for this member/item when one
+ // exists, else any row (which one is arbitrary either way).
+ if (!rowByOp.has(opId) || remaining > 0) {
+ rowByOp.set(opId, row.id as string);
}
}
- if (trackedActivityInputs.length > 0) {
- await trx
- .insertInto("trackedActivityInput")
- .values(trackedActivityInputs)
- .execute();
+ // Per picked lot, split pro-rata by each member's CURRENT remaining —
+ // every member links to every lot it physically drew from, and a
+ // multi-lot pick converges on exact per-member BOM totals.
+ const drawsByOp = new Map<
+ string,
+ { trackedEntityId: string; quantity: number }[]
+ >();
+ for (const child of children) {
+ const open = members
+ .map((m) => ({
+ jobOperationId: m.id,
+ remaining: remainingByOp.get(m.id) ?? 0,
+ }))
+ .filter((m) => m.remaining > 0);
+ const shares = splitPickAcrossMembers(open, Number(child.quantity));
+ for (const share of shares) {
+ if (share.quantity <= 0) continue;
+ remainingByOp.set(
+ share.jobOperationId,
+ (remainingByOp.get(share.jobOperationId) ?? 0) - share.quantity
+ );
+ const draws = drawsByOp.get(share.jobOperationId) ?? [];
+ draws.push({
+ trackedEntityId: child.trackedEntityId,
+ quantity: share.quantity,
+ });
+ drawsByOp.set(share.jobOperationId, draws);
+ }
}
- if (itemLedgerInserts.length > 0) {
- await trx
- .insertInto("itemLedger")
- .values(itemLedgerInserts)
- .execute();
+ const splitEntities: Array<{
+ originalId: string;
+ newId: string;
+ readableId: string;
+ quantity: number;
+ remainingQuantity: number;
+ }> = [];
+ let warning: string | undefined;
- // Update pickMethod defaultStorageUnitId if needed for each inserted ledger
- for (const ledger of itemLedgerInserts) {
- await updatePickMethodDefaultStorageUnitIfNeeded(
- trx,
- ledger.itemId,
- ledger.locationId,
- ledger.storageUnitId,
- companyId,
- userId
+ for (const member of members) {
+ const draws = drawsByOp.get(member.id);
+ if (!draws || draws.length === 0) continue;
+ if (!member.jobMakeMethodId) {
+ throw new Error(`Job operation ${member.id} has no make method`);
+ }
+ // The member's WIP entity — what its consumption books into (the
+ // same entity the single-operation page passes as the parent).
+ const parent = await trx
+ .selectFrom("trackedEntity")
+ .select(["id"])
+ .where(sql`"attributes"->>'Job Make Method'`, "=", member.jobMakeMethodId)
+ .where("companyId", "=", companyId)
+ // Scrap and split children inherit the attribute, so an earlier
+ // run's dead entity can be the oldest match — it must not absorb
+ // this member's consumption.
+ .where("status", "not in", ["Consumed", "Scrapped", "Rejected"])
+ .orderBy("createdAt", "asc")
+ .executeTakeFirst();
+ if (!parent) {
+ throw new Error(
+ `No tracked entity found for job operation ${member.id} — release the member job before picking to the batch`
);
}
+
+ const memberResult = await consumeTrackedEntitiesIntoOperation(trx, {
+ materialId: rowByOp.get(member.id),
+ jobOperationId: member.id,
+ itemId,
+ parentTrackedEntityId: parent.id as string,
+ children: draws,
+ overrideExpired,
+ overrideReason,
+ companyId,
+ userId,
+ companyToday,
+ client,
+ ...accounting,
+ });
+ splitEntities.push(...memberResult.splitEntities);
+ warning = warning ?? memberResult.warning;
}
- if (accountingEnabledTracked && accountDefaultsTracked?.data && itemLedgerInserts.length > 0) {
- const consumptionEntries = itemLedgerInserts
- .filter((l) => l.entryType === "Consumption")
- .map((l) => ({ itemId: l.itemId as string, quantity: Number(l.quantity) }));
+ return { splitEntities, warning };
+ });
- if (consumptionEntries.length > 0) {
- await createMaterialWipEntries(trx, {
- consumptionLedgers: consumptionEntries,
- jobId: job?.id!,
- operationId: jobMaterial?.jobOperationId ?? actualMaterialId!,
- description: "Tracked Entity Material Issue",
- wipAccount: accountDefaultsTracked.data.workInProgressAccount,
- rawMaterialsAccount: accountDefaultsTracked.data.rawMaterialsAccount,
- finishedGoodsAccount: accountDefaultsTracked.data.finishedGoodsAccount,
- dimensionMap: dimensionMapTracked,
-
- jobLocationId: job?.locationId ?? null,
- client,
- db,
- companyId,
- userId,
- });
- }
+ return jsonResponse({
+ success: true,
+ ...batchResult,
+ });
+ }
+ case "mergeTrackedEntities": {
+ const { trackedEntityIds, readableId, companyId, userId } =
+ validatedPayload;
+
+ const client = await requirePermissions(req, companyId, userId, { update: "inventory" });
+ const companyToday = datetime.today(await getCompanyTimeZone(client, companyId));
+
+ const mergeResult = await db.transaction().execute(async (trx) => {
+ const parents = await trx
+ .selectFrom("trackedEntity")
+ .selectAll()
+ .where("id", "in", trackedEntityIds)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .execute();
+
+ if (parents.length !== trackedEntityIds.length) {
+ throw new Error("Tracked entities not found");
}
- const totalChildQuantity = children.reduce((sum, child) => {
- return sum + Number(child.quantity);
- }, 0);
+ // Order by the caller's list, not the DB's row order: the builder
+ // reads the FIRST parent for the merged lot's number, bin, and
+ // attribute base, so an unordered read makes those non-deterministic.
+ const parentById = new Map(parents.map((p) => [p.id, p]));
+ const orderedParents = trackedEntityIds.map((id) => {
+ const row = parentById.get(id);
+ if (!row) throw new Error("Tracked entities not found");
+ return row;
+ });
- // Only update if we didn't create a new jobMaterial (in which case it's already set)
- if (actualMaterialId === materialId) {
- const currentQuantityIssued =
- Number(jobMaterial?.quantityIssued) || 0;
- const newQuantityIssued =
- currentQuantityIssued + totalChildQuantity;
+ const parentLedgers = await trx
+ .selectFrom("itemLedger")
+ .select([
+ "trackedEntityId",
+ "storageUnitId",
+ "locationId",
+ "quantity",
+ "createdAt",
+ ])
+ .where("trackedEntityId", "in", trackedEntityIds)
+ .where("companyId", "=", companyId)
+ .orderBy("createdAt", "desc")
+ .execute();
+
+ // The parent's on-ledger balance: what its job receipt has put into
+ // stock so far. The merge only moves this — unreceived quantity
+ // reaches inventory later, through the member job's own receipt.
+ const receivedOf = (entityId: string) =>
+ // deno-lint-ignore no-explicit-any
+ (parentLedgers as any[])
+ .filter((l) => l.trackedEntityId === entityId)
+ .reduce((acc, l) => acc + Number(l.quantity), 0);
+
+ const locationOf = (entityId: string) =>
+ // deno-lint-ignore no-explicit-any
+ (parentLedgers as any[]).find(
+ (l) => l.trackedEntityId === entityId && l.locationId
+ )?.locationId ?? null;
+
+ const mergedId = nanoid();
+ const mergeActivityId = nanoid();
+
+ const records = buildBatchMergeRecords({
+ parents: orderedParents.map((p) => ({
+ id: p.id,
+ readableId: p.readableId,
+ quantity: Number(p.quantity),
+ receivedQuantity: receivedOf(p.id),
+ status: p.status as string,
+ sourceDocument: p.sourceDocument,
+ sourceDocumentId: p.sourceDocumentId,
+ sourceDocumentReadableId: p.sourceDocumentReadableId,
+ itemId: p.itemId ?? null,
+ expirationDate: (p.expirationDate as string | null) ?? null,
+ attributes: p.attributes as Record<string, unknown> | null,
+ bin: {
+ storageUnitId: resolveTrackedEntityBin(
+ // deno-lint-ignore no-explicit-any
+ parentLedgers as any[],
+ p.id
+ ),
+ locationId: locationOf(p.id),
+ },
+ })),
+ mergedId,
+ mergeActivityId,
+ readableId: readableId ?? null,
+ activitySourceDocument: "Tracked Entity",
+ activitySourceDocumentId: mergedId,
+ companyId,
+ userId,
+ postingDate: companyToday.toString(),
+ });
+
+ await trx
+ .insertInto("trackedEntity")
+ .values({
+ ...records.mergedEntityInsert,
+ // TEXT NOT NULL columns; the builder sources them from the first
+ // parent, which the schema guarantees is non-null.
+ sourceDocument: records.mergedEntityInsert.sourceDocument as string,
+ sourceDocumentId: records.mergedEntityInsert.sourceDocumentId as string,
+ attributes: records.mergedEntityInsert.attributes as Json,
+ })
+ .execute();
+
+ await trx
+ .insertInto("trackedActivity")
+ .values({
+ ...records.activityInsert,
+ attributes: records.activityInsert.attributes as Json,
+ })
+ .execute();
+
+ await trx
+ .insertInto("trackedActivityInput")
+ .values(records.activityInputInserts)
+ .execute();
+
+ await trx
+ .insertInto("trackedActivityOutput")
+ .values(records.activityOutputInsert)
+ .execute();
+
+ await trx
+ .insertInto("itemLedger")
+ .values(
+ records.ledgerInserts.map((l) => ({
+ ...l,
+ itemId: l.itemId as string,
+ }))
+ )
+ .execute();
+ for (const update of records.parentUpdates) {
await trx
- .updateTable("jobMaterial")
- .set({
- quantityIssued: newQuantityIssued,
- })
- .where("id", "=", actualMaterialId)
+ .updateTable("trackedEntity")
+ .set({ status: update.status })
+ .where("id", "=", update.id)
.execute();
-
- logger.info("Job material quantity updated", {
- materialId: actualMaterialId,
- newQuantityIssued,
- });
}
- return splitEntities;
+ return {
+ trackedEntityId: mergedId,
+ readableId: records.mergedEntityInsert.readableId,
+ quantity: records.mergedEntityInsert.quantity,
+ };
});
return jsonResponse({
success: true,
- splitEntities,
- warning: expiredWarning,
+ ...mergeResult,
});
}
case "unconsumeTrackedEntities": {
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 27c4ae3bb5..54c60d241c 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -25361,7 +25361,9 @@ export type Database = {
customFields: Json | null
id: string
locationId: string
+ mergeOutput: boolean
notes: string | null
+ outputLotNumber: string | null
processId: string
readableId: string
status: Database["public"]["Enums"]["jobOperationBatchStatus"]
@@ -25376,7 +25378,9 @@ export type Database = {
customFields?: Json | null
id?: string
locationId: string
+ mergeOutput?: boolean
notes?: string | null
+ outputLotNumber?: string | null
processId: string
readableId: string
status?: Database["public"]["Enums"]["jobOperationBatchStatus"]
@@ -25391,7 +25395,9 @@ export type Database = {
customFields?: Json | null
id?: string
locationId?: string
+ mergeOutput?: boolean
notes?: string | null
+ outputLotNumber?: string | null
processId?: string
readableId?: string
status?: Database["public"]["Enums"]["jobOperationBatchStatus"]
@@ -82460,15 +82466,19 @@ export type Database = {
description: string
id: string
itemDescription: string
+ itemId: string
itemReadableId: string
jobDueDate: string
jobId: string
jobOperationBatchId: string
jobReadableId: string
jobStatus: Database["public"]["Enums"]["jobStatus"]
+ lotNumber: string
materials: Json
operationQuantity: number
+ requiresBatchTracking: boolean
status: Database["public"]["Enums"]["jobOperationStatus"]
+ trackedEntityId: string
workCenterId: string
}[]
}
@@ -85041,6 +85051,7 @@ export type Database = {
| "Inventory Count"
| "Scrap"
| "Sales Return Shipment"
+ | "Batch Merge"
itemLedgerType:
| "Purchase"
| "Sale"
@@ -85142,6 +85153,7 @@ export type Database = {
| "Non-Conformance"
| "Inbound Inspection"
| "Scrap"
+ | "Batch Merge"
| "Card Transaction"
kanbanOutput: "label" | "qrcode" | "url"
kanbanReplenishmentSystem: "Buy" | "Make" | "Transfer"
@@ -86467,6 +86479,7 @@ export const Constants = {
"Inventory Count",
"Scrap",
"Sales Return Shipment",
+ "Batch Merge",
],
itemLedgerType: [
"Purchase",
@@ -86576,6 +86589,7 @@ export const Constants = {
"Non-Conformance",
"Inbound Inspection",
"Scrap",
+ "Batch Merge",
"Card Transaction",
],
kanbanOutput: ["label", "qrcode", "url"],
diff --git a/packages/database/supabase/functions/lib/utils.ts b/packages/database/supabase/functions/lib/utils.ts
index 0e808eb6c4..f69475d67d 100644
--- a/packages/database/supabase/functions/lib/utils.ts
+++ b/packages/database/supabase/functions/lib/utils.ts
@@ -41,6 +41,7 @@ export interface TrackedEntityAttributes {
Shipment?: string;
"Split Entity ID"?: string;
"Split From Entity ID"?: string;
+ "Merged From Entity IDs"?: string[];
Shelf?: string;
}
diff --git a/packages/database/supabase/functions/shared/batch-compatibility.ts b/packages/database/supabase/functions/shared/batch-compatibility.ts
index 4b6bea15d6..dd8eb7e671 100644
--- a/packages/database/supabase/functions/shared/batch-compatibility.ts
+++ b/packages/database/supabase/functions/shared/batch-compatibility.ts
@@ -8,15 +8,18 @@
export type BatchRuleLevel = "must" | "guide" | "ignore";
-// The six BOM dimensions a batch can be gated on. `item` is the material line's
-// own item; the other five are its material properties.
+// The dimensions a batch can be gated on. `item` is the material line's own
+// item and the five properties are that line's material properties;
+// `producedItem` is the member's own produced item (candidate-level, not a
+// BOM line).
export const BATCH_RULE_DIMENSIONS = [
"item",
"substance",
"grade",
"dimension",
"form",
- "finish"
+ "finish",
+ "producedItem"
] as const;
export type BatchRuleDimension = (typeof BATCH_RULE_DIMENSIONS)[number];
@@ -32,7 +35,8 @@ export const DEFAULT_BATCH_RULES: Required<BatchRules> = {
grade: "guide",
dimension: "guide",
form: "ignore",
- finish: "ignore"
+ finish: "ignore",
+ producedItem: "ignore"
};
const LEVELS: ReadonlySet<BatchRuleLevel> = new Set([
diff --git a/packages/database/supabase/functions/shared/batch-merge.test.ts b/packages/database/supabase/functions/shared/batch-merge.test.ts
new file mode 100644
index 0000000000..64eb45bbc0
--- /dev/null
+++ b/packages/database/supabase/functions/shared/batch-merge.test.ts
@@ -0,0 +1,239 @@
+import {
+ assertEquals,
+ assertThrows
+} from "https://deno.land/[email protected]/testing/asserts.ts";
+import { type BatchMergeParent, buildBatchMergeRecords } from "./batch-merge.ts";
+
+function parent(overrides: Partial<BatchMergeParent> = {}): BatchMergeParent {
+ return {
+ id: "p1",
+ readableId: "LOT-A",
+ quantity: 10,
+ receivedQuantity: 10,
+ status: "Available",
+ sourceDocument: "Job",
+ sourceDocumentId: "item-1",
+ sourceDocumentReadableId: "SALAD-01",
+ itemId: "item-1",
+ expirationDate: null,
+ attributes: null,
+ bin: { storageUnitId: "bin-1", locationId: "loc-1" },
+ ...overrides
+ };
+}
+
+const base = {
+ mergedId: "merged-1",
+ mergeActivityId: "act-1",
+ readableId: "LOT-M",
+ companyId: "co",
+ userId: "user",
+ postingDate: "2026-09-16"
+};
+
+Deno.test("merges two lots into one entity with the summed quantity", () => {
+ const records = buildBatchMergeRecords({
+ ...base,
+ parents: [
+ parent({ id: "p1", quantity: 45 }),
+ parent({ id: "p2", readableId: "LOT-B", quantity: 44 })
+ ]
+ });
+
+ assertEquals(records.mergedEntityInsert.quantity, 89);
+ assertEquals(records.mergedEntityInsert.status, "Available");
+ assertEquals(records.mergedEntityInsert.readableId, "LOT-M");
+ assertEquals(records.mergedEntityInsert.attributes["Merged From Entity IDs"], [
+ "p1",
+ "p2"
+ ]);
+ assertEquals(records.parentUpdates, [
+ { id: "p1", status: "Consumed" },
+ { id: "p2", status: "Consumed" }
+ ]);
+ assertEquals(records.activityInsert.type, "Merge");
+ assertEquals(records.activityInputInserts.length, 2);
+ assertEquals(records.activityInputInserts[0].quantity, 45);
+ assertEquals(records.activityInputInserts[1].quantity, 44);
+ assertEquals(records.activityOutputInsert.trackedEntityId, "merged-1");
+ assertEquals(records.activityOutputInsert.quantity, 89);
+});
+
+Deno.test("ledger rows are net-zero and never move stock between bins", () => {
+ const records = buildBatchMergeRecords({
+ ...base,
+ parents: [
+ parent({ id: "p1", quantity: 45, receivedQuantity: 45, bin: { storageUnitId: "bin-1", locationId: "loc-1" } }),
+ parent({ id: "p2", quantity: 44, receivedQuantity: 44, bin: { storageUnitId: "bin-2", locationId: "loc-1" } })
+ ]
+ });
+
+ assertEquals(records.ledgerInserts.length, 4);
+ const net = records.ledgerInserts.reduce((sum, l) => sum + l.quantity, 0);
+ assertEquals(net, 0);
+ // Every bin nets to zero: the merged lot gets each parent's stock where it
+ // already sits.
+ const byBin = new Map<string, number>();
+ for (const l of records.ledgerInserts) {
+ byBin.set(l.storageUnitId ?? "", (byBin.get(l.storageUnitId ?? "") ?? 0) + l.quantity);
+ }
+ assertEquals(byBin.get("bin-1"), 0);
+ assertEquals(byBin.get("bin-2"), 0);
+ const merged = records.ledgerInserts.filter((l) => l.quantity > 0);
+ assertEquals(
+ merged.map((l) => [l.storageUnitId, l.quantity]),
+ [["bin-1", 45], ["bin-2", 44]]
+ );
+ for (const l of records.ledgerInserts) {
+ assertEquals(l.documentType, "Batch Merge");
+ }
+});
+
+Deno.test("merged lot inherits the first parent's number when none is given", () => {
+ const { readableId, ...rest } = base;
+ const records = buildBatchMergeRecords({
+ ...rest,
+ parents: [
+ parent({ id: "p1", readableId: "LOT-A" }),
+ parent({ id: "p2", readableId: "LOT-B" })
+ ]
+ });
+ // An Available lot with a null number is unidentifiable on the floor; the
+ // split builder's child inherits parent.readableId for the same reason.
+ assertEquals(records.mergedEntityInsert.readableId, "LOT-A");
+});
+
+Deno.test("earliest parent expiry wins", () => {
+ const records = buildBatchMergeRecords({
+ ...base,
+ parents: [
+ parent({ id: "p1", expirationDate: "2026-10-01" }),
+ parent({ id: "p2", expirationDate: "2026-09-20" }),
+ parent({ id: "p3", expirationDate: null })
+ ]
+ });
+ assertEquals(records.mergedEntityInsert.expirationDate, "2026-09-20");
+});
+
+Deno.test("attributes kept only where every parent agrees; pointer keys dropped", () => {
+ const records = buildBatchMergeRecords({
+ ...base,
+ parents: [
+ parent({
+ id: "p1",
+ attributes: {
+ Supplier: "Acme",
+ "Grow Room": "R1",
+ "Split From Entity ID": "old"
+ }
+ }),
+ parent({
+ id: "p2",
+ attributes: { Supplier: "Acme", "Grow Room": "R2" }
+ })
+ ]
+ });
+ assertEquals(records.mergedEntityInsert.attributes.Supplier, "Acme");
+ assertEquals(records.mergedEntityInsert.attributes["Grow Room"], undefined);
+ assertEquals(
+ records.mergedEntityInsert.attributes["Split From Entity ID"],
+ undefined
+ );
+});
+
+Deno.test("rejects mixed items", () => {
+ assertThrows(
+ () =>
+ buildBatchMergeRecords({
+ ...base,
+ parents: [
+ parent({ id: "p1" }),
+ parent({ id: "p2", itemId: "item-2", sourceDocumentId: "item-2" })
+ ]
+ }),
+ Error,
+ "same item"
+ );
+});
+
+Deno.test("rejects fewer than two lots", () => {
+ assertThrows(
+ () => buildBatchMergeRecords({ ...base, parents: [parent()] }),
+ Error,
+ "At least two"
+ );
+});
+
+Deno.test("rejects unavailable or empty parents", () => {
+ assertThrows(
+ () =>
+ buildBatchMergeRecords({
+ ...base,
+ parents: [parent(), parent({ id: "p2", status: "Consumed" })]
+ }),
+ Error,
+ "not available"
+ );
+ assertThrows(
+ () =>
+ buildBatchMergeRecords({
+ ...base,
+ parents: [parent(), parent({ id: "p2", quantity: 0 })]
+ }),
+ Error,
+ "no quantity"
+ );
+});
+
+Deno.test("ledger books the FK-enforced itemId, not the polymorphic sourceDocumentId", () => {
+ // sourceDocumentId is legacy and polymorphic — on a WIP output entity it can
+ // point at a jobMakeMethod, or be "". The ledger must book the same item the
+ // same-item check validated.
+ const records = buildBatchMergeRecords({
+ ...base,
+ parents: [
+ parent({ id: "p1", itemId: "item-1", sourceDocumentId: "jmm-1" }),
+ parent({ id: "p2", itemId: "item-1", sourceDocumentId: "" })
+ ]
+ });
+
+ for (const row of records.ledgerInserts) {
+ assertEquals(row.itemId, "item-1");
+ }
+});
+
+Deno.test("unreceived parents contribute no ledger rows; receipts stay per job", () => {
+ // Lots straight off a completed batch: nothing received yet. The merge is
+ // identity-only — no stock exists to move, so no ledger rows at all.
+ const records = buildBatchMergeRecords({
+ ...base,
+ parents: [
+ parent({ id: "p1", quantity: 2, receivedQuantity: 0 }),
+ parent({ id: "p2", quantity: 2, receivedQuantity: 0 }),
+ parent({ id: "p3", quantity: 2, receivedQuantity: 0 })
+ ]
+ });
+ assertEquals(records.ledgerInserts.length, 0);
+ // identity level is untouched: the merged lot still carries all six units
+ assertEquals(records.mergedEntityInsert.quantity, 6);
+});
+
+Deno.test("partially received merge moves exactly the received balance", () => {
+ const records = buildBatchMergeRecords({
+ ...base,
+ parents: [
+ parent({ id: "p1", quantity: 2, receivedQuantity: 2 }),
+ parent({ id: "p2", quantity: 2, receivedQuantity: 0 })
+ ]
+ });
+ const rows = records.ledgerInserts;
+ assertEquals(rows.length, 2);
+ assertEquals(rows[0].trackedEntityId, "p1");
+ assertEquals(rows[0].quantity, -2);
+ assertEquals(rows[1].trackedEntityId, "merged-1");
+ assertEquals(rows[1].quantity, 2);
+ assertEquals(
+ rows.reduce((acc, r) => acc + r.quantity, 0),
+ 0
+ );
+});
diff --git a/packages/database/supabase/functions/shared/batch-merge.ts b/packages/database/supabase/functions/shared/batch-merge.ts
new file mode 100644
index 0000000000..e270fe1b31
--- /dev/null
+++ b/packages/database/supabase/functions/shared/batch-merge.ts
@@ -0,0 +1,276 @@
+// Pure record builders for merging N same-item tracked entities into ONE new
+// entity — the deliberate lot merge behind batch-completion outputs ("2 lots of
+// the same item — merge into one?"). The inverse shape of buildBatchSplitRecords
+// in ./batch-split.ts: parents become Consumed, a fresh entity carries the
+// summed quantity, one Merge activity records inputs = each parent at its
+// quantity and output = the merged entity, and the ledger gets net-zero Batch
+// Merge rows (−q at each parent's bin, +Σq at the merged entity's bin).
+//
+// No imports — consumed from Deno edge functions AND node-side app code, so it
+// must not touch lib/database.ts or any Deno API.
+// See .ai/specs/2026-09-16-batch-materials-and-output-lots.md.
+
+export type BatchMergeParent = {
+ id: string;
+ readableId: string | null;
+ quantity: number;
+ /** the parent's on-ledger balance (Σ itemLedger.quantity). A lot straight
+ * off a completed batch has 0 until its job is received — the merge is an
+ * identity operation and must only move stock that actually exists. */
+ receivedQuantity: number;
+ status: string;
+ sourceDocument: string | null;
+ sourceDocumentId: string | null;
+ sourceDocumentReadableId: string | null;
+ itemId: string | null;
+ expirationDate: string | null;
+ attributes: Record<string, unknown> | null;
+ /** the parent's resolved bin — its −q ledger row books here */
+ bin: { storageUnitId: string | null; locationId: string | null };
+};
+
+type MergeLedgerRecord = {
+ postingDate: string;
+ itemId: string | null;
+ quantity: number;
+ locationId: string | null;
+ storageUnitId: string | null;
+ entryType: "Negative Adjmt." | "Positive Adjmt.";
+ documentType: "Batch Merge";
+ documentId: string;
+ trackedEntityId: string;
+ createdBy: string;
+ companyId: string;
+};
+
+type MergeActivityEdgeRecord = {
+ trackedActivityId: string;
+ trackedEntityId: string;
+ quantity: number;
+ companyId: string;
+ createdBy: string;
+};
+
+// Pointer keys from the split convention never carry onto a merged entity —
+// its provenance is the Merge activity plus "Merged From Entity IDs".
+const POINTER_KEYS = ["Split Entity ID", "Split From Entity ID"];
+
+export function buildBatchMergeRecords(input: {
+ parents: BatchMergeParent[];
+ /** caller-supplied nanoid for the merged entity */
+ mergedId: string;
+ /** caller-supplied nanoid for the Merge activity */
+ mergeActivityId: string;
+ /** the merged lot's batch number. Omitted/null inherits the FIRST parent's,
+ * matching buildBatchSplitRecords (a split child keeps parent.readableId).
+ * An Available lot with no number is unidentifiable on the floor. */
+ readableId?: string | null;
+ activitySourceDocument?: string;
+ activitySourceDocumentId?: string;
+ companyId: string;
+ userId: string;
+ /** yyyy-MM-dd */
+ postingDate: string;
+}): {
+ mergedEntityInsert: {
+ id: string;
+ readableId: string | null;
+ sourceDocument: string | null;
+ sourceDocumentId: string | null;
+ sourceDocumentReadableId: string | null;
+ quantity: number;
+ status: "Available";
+ attributes: Record<string, unknown>;
+ itemId: string | null;
+ expirationDate: string | null;
+ companyId: string;
+ createdBy: string;
+ };
+ /** parents keep their quantity (historical record, like any consumption) and flip Consumed */
+ parentUpdates: { id: string; status: "Consumed" }[];
+ activityInsert: {
+ id: string;
+ type: "Merge";
+ sourceDocument?: string;
+ sourceDocumentId?: string;
+ attributes: Record<string, unknown>;
+ companyId: string;
+ createdBy: string;
+ };
+ activityInputInserts: MergeActivityEdgeRecord[];
+ activityOutputInsert: MergeActivityEdgeRecord;
+ ledgerInserts: MergeLedgerRecord[];
+} {
+ const {
+ parents,
+ mergedId,
+ mergeActivityId,
+ readableId,
+ activitySourceDocument,
+ activitySourceDocumentId,
+ companyId,
+ userId,
+ postingDate
+ } = input;
+
+ if (parents.length < 2) {
+ throw new Error("At least two lots are required to merge");
+ }
+ for (const parent of parents) {
+ if (parent.status !== "Available") {
+ throw new Error(
+ `Lot ${parent.readableId ?? parent.id} is not available to merge`
+ );
+ }
+ if (!(parent.quantity > 0)) {
+ throw new Error(
+ `Lot ${parent.readableId ?? parent.id} has no quantity to merge`
+ );
+ }
+ if (parent.receivedQuantity < 0) {
+ throw new Error(
+ `Lot ${parent.readableId ?? parent.id} has a negative ledger balance`
+ );
+ }
+ }
+ const itemOf = (p: BatchMergeParent) => p.itemId ?? p.sourceDocumentId;
+ const firstItem = itemOf(parents[0]!);
+ if (!firstItem || parents.some((p) => itemOf(p) !== firstItem)) {
+ throw new Error("Only lots of the same item can be merged");
+ }
+
+ const totalQuantity = parents.reduce((sum, p) => sum + p.quantity, 0);
+
+ // Earliest parent expiry wins — the conservative policy for a blended lot.
+ let expirationDate: string | null = null;
+ for (const p of parents) {
+ if (p.expirationDate && (!expirationDate || p.expirationDate < expirationDate)) {
+ expirationDate = p.expirationDate;
+ }
+ }
+
+ // Keep only the attributes every parent agrees on; anything contested is
+ // dropped rather than guessed.
+ const first = parents[0]!;
+ const agreed: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(
+ (first.attributes ?? {}) as Record<string, unknown>
+ )) {
+ if (POINTER_KEYS.includes(key)) continue;
+ const everyoneAgrees = parents.every(
+ (p) =>
+ JSON.stringify(
+ ((p.attributes ?? {}) as Record<string, unknown>)[key]
+ ) === JSON.stringify(value)
+ );
+ if (everyoneAgrees) agreed[key] = value;
+ }
+
+ return {
+ mergedEntityInsert: {
+ id: mergedId,
+ readableId: readableId ?? first.readableId,
+ sourceDocument: first.sourceDocument,
+ sourceDocumentId: first.sourceDocumentId,
+ sourceDocumentReadableId: first.sourceDocumentReadableId,
+ quantity: totalQuantity,
+ status: "Available",
+ attributes: {
+ ...agreed,
+ "Merged From Entity IDs": parents.map((p) => p.id)
+ },
+ itemId: first.itemId,
+ expirationDate,
+ companyId,
+ createdBy: userId
+ },
+ parentUpdates: parents.map((p) => ({ id: p.id, status: "Consumed" })),
+ activityInsert: {
+ id: mergeActivityId,
+ type: "Merge",
+ ...(activitySourceDocument
+ ? { sourceDocument: activitySourceDocument }
+ : {}),
+ ...(activitySourceDocumentId
+ ? { sourceDocumentId: activitySourceDocumentId }
+ : {}),
+ attributes: {
+ "Merged Quantity": totalQuantity,
+ "Merged From Entity IDs": parents.map((p) => p.id),
+ "Merged Entity ID": mergedId
+ },
+ companyId,
+ createdBy: userId
+ },
+ activityInputInserts: parents.map((p) => ({
+ trackedActivityId: mergeActivityId,
+ trackedEntityId: p.id,
+ quantity: p.quantity,
+ companyId,
+ createdBy: userId
+ })),
+ activityOutputInsert: {
+ trackedActivityId: mergeActivityId,
+ trackedEntityId: mergedId,
+ quantity: totalQuantity,
+ companyId,
+ createdBy: userId
+ },
+ // Ledger rows move only stock the parents actually had: each job's
+ // receipt is still what brings its quantity into inventory (and lands on
+ // the merged lot once the parent is consumed). A parent received in full
+ // makes these net to zero, which is the old behaviour.
+ ledgerInserts: [
+ ...parents
+ .filter((p) => p.receivedQuantity > 0)
+ .map(
+ (p): MergeLedgerRecord => ({
+ postingDate,
+ itemId: p.itemId ?? p.sourceDocumentId,
+ quantity: -p.receivedQuantity,
+ locationId: p.bin.locationId,
+ storageUnitId: p.bin.storageUnitId,
+ entryType: "Negative Adjmt.",
+ documentType: "Batch Merge",
+ documentId: mergeActivityId,
+ trackedEntityId: p.id,
+ createdBy: userId,
+ companyId
+ })
+ ),
+ // One positive row per bin the parents occupied: the merge changes
+ // which lot the stock belongs to, never where it is.
+ ...receivedByBin(parents).map(
+ ({ bin, quantity }): MergeLedgerRecord => ({
+ postingDate,
+ itemId: first.itemId ?? first.sourceDocumentId,
+ quantity,
+ locationId: bin.locationId,
+ storageUnitId: bin.storageUnitId,
+ entryType: "Positive Adjmt.",
+ documentType: "Batch Merge",
+ documentId: mergeActivityId,
+ trackedEntityId: mergedId,
+ createdBy: userId,
+ companyId
+ })
+ )
+ ]
+ };
+}
+
+// Received quantity summed per bin, in the order the bins first appear.
+function receivedByBin(parents: BatchMergeParent[]) {
+ const byBin = new Map<
+ string,
+ { bin: BatchMergeParent["bin"]; quantity: number }
+ >();
+ for (const p of parents) {
+ if (p.receivedQuantity <= 0) continue;
+ const key = `${p.bin.locationId}|${p.bin.storageUnitId}`;
+ const entry = byBin.get(key) ?? { bin: p.bin, quantity: 0 };
+ entry.quantity += p.receivedQuantity;
+ byBin.set(key, entry);
+ }
+ return [...byBin.values()];
+}
diff --git a/packages/database/supabase/functions/shared/batch-pick-split.ts b/packages/database/supabase/functions/shared/batch-pick-split.ts
new file mode 100644
index 0000000000..02c5c9ba6a
--- /dev/null
+++ b/packages/database/supabase/functions/shared/batch-pick-split.ts
@@ -0,0 +1,58 @@
+// Pro-rata split of one physical material pick across a batch's member
+// operations, weighted by each member's REMAINING requirement so a multi-lot
+// pick sequence converges on exactly the per-member BOM quantities.
+//
+// Canonical source (with the vitest coverage in packages/utils). Deno edge
+// functions cannot import workspace packages, so @carbon/utils RE-EXPORTS this
+// file (see packages/utils/src/batch-pick-split.ts) — one source of truth, no
+// drift. Dependency-free pure TS aside from the sibling precision module.
+// See .ai/specs/2026-09-16-batch-materials-and-output-lots.md.
+
+import { distributeRoundingResidual, EPSILON } from "./precision.ts";
+
+export interface PickMember {
+ jobOperationId: string;
+ /** This member's remaining requirement for the picked item (estimated − already consumed). */
+ remaining: number;
+}
+
+export interface PickShare {
+ jobOperationId: string;
+ quantity: number;
+}
+
+/**
+ * Split `pickedQuantity` across members pro-rata by remaining requirement.
+ * Members with no remaining requirement are skipped; the returned shares are
+ * rounded at internal scale and sum EXACTLY to `pickedQuantity`
+ * (largest-remainder via distributeRoundingResidual — parts are never rounded
+ * independently). Throws when nothing remains or the pick exceeds the total
+ * remaining; callers surface the message verbatim.
+ */
+export function splitPickAcrossMembers(
+ members: PickMember[],
+ pickedQuantity: number
+): PickShare[] {
+ if (!Number.isFinite(pickedQuantity) || pickedQuantity <= 0) {
+ throw new Error("Pick quantity must be greater than zero");
+ }
+
+ const open = members.filter((m) => m.remaining > 0);
+ const totalRemaining = open.reduce((sum, m) => sum + m.remaining, 0);
+ if (open.length === 0 || totalRemaining <= 0) {
+ throw new Error("No member operation still requires this item");
+ }
+ if (pickedQuantity > totalRemaining + EPSILON) {
+ throw new Error(
+ `Pick of ${pickedQuantity} exceeds the batch's remaining requirement of ${totalRemaining}`
+ );
+ }
+
+ const exact = open.map((m) => (pickedQuantity * m.remaining) / totalRemaining);
+ const shares = distributeRoundingResidual(exact, pickedQuantity);
+
+ return open.map((m, i) => ({
+ jobOperationId: m.jobOperationId,
+ quantity: shares[i] ?? 0
+ }));
+}
diff --git a/packages/database/supabase/migrations/20260915201233_batch-merge-ledger-enum.sql b/packages/database/supabase/migrations/20260915201233_batch-merge-ledger-enum.sql
new file mode 100644
index 0000000000..133f46ecf7
--- /dev/null
+++ b/packages/database/supabase/migrations/20260915201233_batch-merge-ledger-enum.sql
@@ -0,0 +1,5 @@
+-- Lot merge (inverse of Batch Split): net-zero ledger rows for combining
+-- same-item tracked entities into one. Mirrors 'Batch Split'
+-- (20250225145619_tracked-entities.sql, 20260504000000_cost-layers.sql).
+ALTER TYPE "itemLedgerDocumentType" ADD VALUE IF NOT EXISTS 'Batch Merge';
+ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Batch Merge';
diff --git a/packages/database/supabase/migrations/20260916131445_merge-aware-job-receipt.sql b/packages/database/supabase/migrations/20260916131445_merge-aware-job-receipt.sql
new file mode 100644
index 0000000000..b77e8098de
--- /dev/null
+++ b/packages/database/supabase/migrations/20260916131445_merge-aware-job-receipt.sql
@@ -0,0 +1,860 @@
+-- Job receipts resolve through lot merges.
+--
+-- The MES batch-completion prompt merges member output lots BEFORE the member
+-- jobs are received, and the merge is identity-only: its ledger rows move only
+-- stock the parents actually had (see shared/batch-merge.ts). Each member
+-- job's receipt therefore still brings that job's quantity into inventory —
+-- but the job's own lot is Consumed by then, and the old lookup
+-- (status != 'Consumed') raised "Tracked entity not found", stranding every
+-- job received after a merge.
+--
+-- complete_job_to_inventory is redefined verbatim from
+-- 20260914095239_complete-job-received-quantity.sql with one addition in the
+-- batch-tracking branch: when no live lot carries the job's make method, walk
+-- Merge activities from the job's lot to the terminal output lot and post the
+-- receipt against it.
+
+CREATE OR REPLACE FUNCTION complete_job_to_inventory(
+ p_job_id TEXT,
+ p_quantity_complete NUMERIC,
+ p_storage_unit_id TEXT DEFAULT NULL,
+ p_location_id TEXT DEFAULT NULL,
+ p_company_id TEXT DEFAULT NULL,
+ p_user_id TEXT DEFAULT NULL
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_item_id TEXT;
+ v_item_tracking_type "itemTrackingType";
+ v_cogs_account TEXT;
+ v_sales_order_line_id TEXT;
+ v_line_quantity_complete NUMERIC;
+ v_job_company_id TEXT;
+ v_prior_quantity_received NUMERIC;
+ v_quantity_received_to_inventory NUMERIC;
+ v_job_id_readable TEXT;
+ v_job_make_method RECORD;
+ v_tracked_entity RECORD;
+ v_accounting_enabled BOOLEAN;
+ v_company_group_id TEXT;
+ v_raw_materials_account TEXT;
+ v_finished_goods_account TEXT;
+ v_item_inventory_account TEXT;
+ v_item_inventory_description TEXT;
+ v_wip_account TEXT;
+ v_labor_absorption_account TEXT;
+ v_overhead_absorption_account TEXT;
+ v_dimension_item_posting_group TEXT;
+ v_dimension_item TEXT;
+ v_dimension_location TEXT;
+ v_dimension_cost_center TEXT;
+ v_dimension_employee TEXT;
+ v_event RECORD;
+ v_duration_hours NUMERIC;
+ v_rate NUMERIC;
+ v_labor_cost NUMERIC;
+ v_overhead_cost NUMERIC;
+ v_event_reference TEXT;
+ v_labor_journal_line_reference TEXT;
+ v_labor_accounting_period_id TEXT;
+ v_labor_journal_entry_id TEXT;
+ v_labor_journal_id TEXT;
+ v_labor_jl_id TEXT;
+ v_accumulated_wip_cost NUMERIC;
+ v_today DATE;
+ v_journal_line_reference TEXT;
+ v_accounting_period_id TEXT;
+ v_journal_entry_id TEXT;
+ v_journal_id TEXT;
+ v_jl_ids TEXT[];
+ v_new_per_unit_cost NUMERIC;
+ v_costing_method TEXT;
+ v_existing_unit_cost NUMERIC;
+ v_item_posting_group_id TEXT;
+ v_job_location_id TEXT;
+ v_total_qty_on_hand NUMERIC;
+ v_prior_qty NUMERIC;
+ v_prior_value NUMERIC;
+ v_new_unit_cost NUMERIC;
+ v_serial_unit_ids TEXT[];
+ v_company_today DATE := company_today(p_company_id);
+BEGIN
+ -- Never let a NULL user reach NOT NULL audit columns; fall back to the job creator
+ p_user_id := COALESCE(p_user_id, (SELECT "createdBy" FROM "job" WHERE id = p_job_id));
+
+ -- Fetch job details. The row lock makes a concurrent completion wait and then
+ -- read this completion's cumulative quantity, so both cannot compute the same
+ -- receipt delta.
+ SELECT "itemId", "quantityReceivedToInventory", "jobId", "locationId", "salesOrderLineId", "companyId"
+ INTO STRICT v_item_id, v_prior_quantity_received, v_job_id_readable, v_job_location_id, v_sales_order_line_id, v_job_company_id
+ FROM "job"
+ WHERE id = p_job_id
+ FOR UPDATE;
+
+ -- SECURITY DEFINER bypasses RLS: bind the call to the job's own company so a
+ -- caller can never complete another tenant's job or post into a mismatched
+ -- company's ledger/journal.
+ IF p_company_id IS NULL OR v_job_company_id IS DISTINCT FROM p_company_id THEN
+ RAISE EXCEPTION 'Job % does not belong to company %', p_job_id, COALESCE(p_company_id, '<null>');
+ END IF;
+
+ -- Non-Inventory items (services) never enter inventory
+ SELECT "itemTrackingType"
+ INTO v_item_tracking_type
+ FROM "item"
+ WHERE id = v_item_id
+ AND "companyId" = p_company_id;
+
+ -- A stocked item completed at zero marks the job Completed, receives nothing
+ -- and backflushes nothing. Refuse it at the one function every completion path
+ -- crosses (ERP complete route, API/MCP, sync_finish_job_operation).
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'
+ AND COALESCE(p_quantity_complete, 0) <= 0 THEN
+ RAISE EXCEPTION 'Quantity completed must be greater than 0 for job %', v_job_id_readable;
+ END IF;
+
+ -- Delta for this completion: drives the itemLedger/costLedger quantities and
+ -- the WIP-discharge journal. The job column itself stores the CUMULATIVE
+ -- quantity (get_inventory_quantities computes on-production supply as
+ -- production + scrap - received - shipped, which requires cumulative).
+ v_quantity_received_to_inventory := p_quantity_complete - COALESCE(v_prior_quantity_received, 0);
+
+ -- Fetch jobMakeMethod for the top-level (no parentMaterialId)
+ SELECT *
+ INTO STRICT v_job_make_method
+ FROM "jobMakeMethod"
+ WHERE "jobId" = p_job_id
+ AND "parentMaterialId" IS NULL;
+
+ -- Serial units are received one tracked entity at a time, so a fractional
+ -- quantity cannot be honoured; it would be stored on the job and rounded by
+ -- the receipt.
+ IF v_job_make_method."requiresSerialTracking"
+ AND p_quantity_complete <> trunc(p_quantity_complete) THEN
+ RAISE EXCEPTION 'Quantity completed must be a whole number for serial-tracked job %', v_job_id_readable;
+ END IF;
+
+ -- The quantity is cumulative, so a stocked job cannot be completed at less than
+ -- it has already received: the negative delta would post a negative receipt,
+ -- cost layer and WIP journal. Received stock is corrected through inventory
+ -- adjustments, not by re-completing the job. Non-Inventory jobs never receive.
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'
+ AND p_quantity_complete < COALESCE(v_prior_quantity_received, 0) THEN
+ RAISE EXCEPTION 'Quantity completed cannot be lower than the % already received for job %',
+ COALESCE(v_prior_quantity_received, 0), v_job_id_readable;
+ END IF;
+
+ -- Update job status. quantityReceivedToInventory is CUMULATIVE (not the
+ -- delta): re-completions previously overwrote it with the delta, corrupting
+ -- get_inventory_quantities' on-production supply math. Non-Inventory items
+ -- never receive to inventory, so their value is left unchanged.
+ UPDATE "job"
+ SET status = 'Completed',
+ "completedDate" = NOW(),
+ "quantityComplete" = p_quantity_complete,
+ "quantityReceivedToInventory" = CASE
+ WHEN v_item_tracking_type = 'Non-Inventory' THEN v_prior_quantity_received
+ ELSE p_quantity_complete
+ END,
+ "updatedAt" = NOW(),
+ "updatedBy" = p_user_id
+ WHERE id = p_job_id;
+
+ -- Services never ship, so job completion is the fulfillment event: advance
+ -- the linked sales-order line the way post-shipment does for physical lines.
+ -- Lives HERE (not in app code) because completion has multiple entry points —
+ -- the ERP complete route AND the sync_finish_job_operation interceptor that
+ -- auto-completes when the last operation finishes. Recomputed from ALL jobs
+ -- on the line, so it is idempotent and lot-split safe. Runs before the
+ -- accounting-enabled / zero-WIP early returns.
+ -- NARROWED: only genuine Service lines (salesOrderLineType = 'Service') fulfill
+ -- by completion. They never receive a shipment line (the `create` edge fn skips
+ -- salesOrderLineType='Service'), so completion is their only fulfillment event.
+ -- A Non-Inventory *Part* (or Material/Tool/etc.) still ships via post-shipment and
+ -- must NOT be auto-fulfilled here — that was marking SO lines "Shipped" with no shipment.
+ IF v_item_tracking_type = 'Non-Inventory' AND v_sales_order_line_id IS NOT NULL
+ AND EXISTS (
+ SELECT 1 FROM "salesOrderLine" sol
+ WHERE sol.id = v_sales_order_line_id
+ AND sol."companyId" = p_company_id
+ AND sol."salesOrderLineType" = 'Service'
+ ) THEN
+ SELECT COALESCE(SUM("quantityComplete"), 0)
+ INTO v_line_quantity_complete
+ FROM "job"
+ WHERE "salesOrderLineId" = v_sales_order_line_id
+ AND "companyId" = p_company_id
+ AND status != 'Cancelled';
+
+ UPDATE "salesOrderLine" sol
+ SET "quantitySent" = v_line_quantity_complete,
+ "sentComplete" = (COALESCE(sol."saleQuantity", 0) > 0 AND v_line_quantity_complete >= sol."saleQuantity"),
+ "sentDate" = CASE
+ WHEN COALESCE(sol."saleQuantity", 0) > 0
+ AND v_line_quantity_complete >= sol."saleQuantity"
+ AND sol."sentDate" IS NULL
+ THEN v_company_today
+ ELSE sol."sentDate"
+ END,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE sol.id = v_sales_order_line_id
+ AND sol."companyId" = p_company_id;
+ END IF;
+
+ -- Insert itemLedger entries based on tracking type.
+ -- Non-Inventory items (services) never enter inventory, and a re-completion at
+ -- the quantity already received has nothing new to receive.
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'
+ AND v_quantity_received_to_inventory > 0 THEN
+ IF v_job_make_method."requiresBatchTracking" THEN
+ SELECT *
+ INTO v_tracked_entity
+ FROM "trackedEntity"
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND "companyId" = p_company_id
+ AND status != 'Consumed'
+ ORDER BY "createdAt" DESC
+ LIMIT 1;
+
+ -- The job's own lot can already be Consumed by a lot MERGE: the batch
+ -- completion prompt offers the merge before member jobs are received,
+ -- and the merge is identity-only (it moves no unreceived stock). This
+ -- job's receipt must then land on the merge's output lot — walk Merge
+ -- activities from the job's lot to the terminal, still-live output.
+ IF v_tracked_entity.id IS NULL THEN
+ WITH RECURSIVE merge_walk(id) AS (
+ SELECT te.id
+ FROM "trackedEntity" te
+ WHERE te.attributes->>'Job Make Method' = v_job_make_method.id
+ AND te."companyId" = p_company_id
+ UNION
+ SELECT tao."trackedEntityId"
+ FROM merge_walk
+ JOIN "trackedActivityInput" tai
+ ON tai."trackedEntityId" = merge_walk.id
+ AND tai."companyId" = p_company_id
+ JOIN "trackedActivity" ta
+ ON ta.id = tai."trackedActivityId"
+ AND ta."companyId" = p_company_id
+ AND ta.type = 'Merge'
+ JOIN "trackedActivityOutput" tao
+ ON tao."trackedActivityId" = ta.id
+ AND tao."companyId" = p_company_id
+ )
+ SELECT te.*
+ INTO v_tracked_entity
+ FROM merge_walk
+ JOIN "trackedEntity" te ON te.id = merge_walk.id
+ WHERE te.status != 'Consumed'
+ ORDER BY te."createdAt" DESC
+ LIMIT 1;
+ END IF;
+
+ IF v_tracked_entity.id IS NULL THEN
+ RAISE EXCEPTION 'Tracked entity not found';
+ END IF;
+
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+
+ ELSIF v_job_make_method."requiresSerialTracking" THEN
+ -- Receive exactly the newly completed units: units finished on the shop floor
+ -- (Available) first, then by serial number. A unit this job already received
+ -- is never received again, so re-completion cannot double-count. Rejected
+ -- (failed inspection) and Scrapped units never enter stock. The candidates
+ -- are locked so a concurrent completion cannot take the same units.
+ v_serial_unit_ids := ARRAY(
+ SELECT te.id
+ FROM "trackedEntity" te
+ WHERE te.attributes->>'Job Make Method' = v_job_make_method.id
+ AND te."companyId" = p_company_id
+ AND te.status NOT IN ('Consumed', 'Rejected', 'Scrapped')
+ AND te.quantity = 1
+ AND NOT EXISTS (
+ SELECT 1
+ FROM "itemLedger" il
+ WHERE il."trackedEntityId" = te.id
+ AND il."documentType" = 'Job Receipt'
+ AND il."documentId" = p_job_id
+ )
+ ORDER BY
+ CASE te.status WHEN 'Available' THEN 0 WHEN 'Reserved' THEN 1 ELSE 2 END,
+ te."readableId" NULLS LAST,
+ te."createdAt",
+ te.id
+ FOR UPDATE OF te
+ );
+
+ IF COALESCE(array_length(v_serial_unit_ids, 1), 0) >= v_quantity_received_to_inventory THEN
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ )
+ SELECT
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, 1, p_location_id, p_storage_unit_id,
+ unit_id, p_user_id
+ FROM unnest(v_serial_unit_ids[1:v_quantity_received_to_inventory::INTEGER]) AS unit_id;
+
+ UPDATE "trackedEntity"
+ SET status = 'Available'
+ WHERE id = ANY(v_serial_unit_ids[1:v_quantity_received_to_inventory::INTEGER]);
+
+ ELSE
+ -- An item with no serial sequence never reaches assign-serial-numbers, so
+ -- the job still holds ONE seed entity covering every unit and there is
+ -- nothing to receive one at a time. Receive the delta against that seed,
+ -- the way the batch branch does. Raising here instead would abort the
+ -- jobOperation UPDATE itself: completion also runs inside
+ -- sync_finish_job_operation, a BEFORE trigger interceptor.
+ SELECT *
+ INTO v_tracked_entity
+ FROM "trackedEntity" te
+ WHERE te.attributes->>'Job Make Method' = v_job_make_method.id
+ AND te."companyId" = p_company_id
+ AND te.status NOT IN ('Consumed', 'Rejected', 'Scrapped')
+ AND te.quantity > 1
+ ORDER BY te."createdAt"
+ LIMIT 1
+ FOR UPDATE;
+
+ -- Genuinely short of units (some scrapped, some already received) rather
+ -- than un-numbered: receiving fewer than completed would leave the job's
+ -- received quantity ahead of the ledger.
+ IF v_tracked_entity.id IS NULL THEN
+ RAISE EXCEPTION 'Job % has % serial unit(s) left to receive, fewer than the % being completed',
+ v_job_id_readable, COALESCE(array_length(v_serial_unit_ids, 1), 0), v_quantity_received_to_inventory;
+ END IF;
+
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+
+ UPDATE "trackedEntity"
+ SET status = 'Available'
+ WHERE id = v_tracked_entity.id;
+ END IF;
+
+ ELSE
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ p_user_id
+ );
+ END IF;
+ END IF;
+
+ -- Update pickMethod defaultStorageUnitId if needed
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' AND p_storage_unit_id IS NOT NULL AND p_location_id IS NOT NULL THEN
+ IF NOT EXISTS (
+ SELECT 1 FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id
+ AND "storageUnitId" IS NOT NULL
+ AND "storageUnitId" != p_storage_unit_id
+ LIMIT 1
+ ) THEN
+ IF EXISTS (
+ SELECT 1 FROM "pickMethod"
+ WHERE "itemId" = v_item_id AND "locationId" = p_location_id
+ ) THEN
+ UPDATE "pickMethod"
+ SET "defaultStorageUnitId" = p_storage_unit_id,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id;
+ ELSE
+ INSERT INTO "pickMethod" (
+ "itemId", "locationId", "defaultStorageUnitId",
+ "companyId", "createdBy", "createdAt"
+ ) VALUES (
+ v_item_id, p_location_id, p_storage_unit_id,
+ p_company_id, p_user_id, NOW()
+ );
+ END IF;
+ END IF;
+ END IF;
+
+ -- Backflush unissued materials (delegated to shared function)
+ PERFORM backflush_job_materials(p_job_id, p_quantity_complete, p_company_id, p_user_id);
+
+ -- Check if accounting is enabled
+ SELECT "accountingEnabled"
+ INTO v_accounting_enabled
+ FROM "companySettings"
+ WHERE id = p_company_id;
+
+ v_accounting_enabled := COALESCE(v_accounting_enabled, false);
+
+ IF NOT v_accounting_enabled THEN
+ RETURN;
+ END IF;
+
+ -- Fetch company group
+ SELECT "companyGroupId"
+ INTO STRICT v_company_group_id
+ FROM company
+ WHERE id = p_company_id;
+
+ -- Fetch account defaults
+ SELECT "rawMaterialsAccount", "finishedGoodsAccount", "workInProgressAccount", "laborAbsorptionAccount", "overheadAbsorptionAccount", "costOfGoodsSoldAccount"
+ INTO STRICT v_raw_materials_account, v_finished_goods_account, v_wip_account, v_labor_absorption_account, v_overhead_absorption_account, v_cogs_account
+ FROM "accountDefault"
+ WHERE "companyId" = p_company_id;
+
+ -- Resolve Raw Materials vs Finished Goods from the produced item:
+ -- Buy → Raw Materials; Make / Buy and Make → Finished Goods.
+ SELECT
+ CASE WHEN i."replenishmentSystem" = 'Buy' THEN v_raw_materials_account ELSE v_finished_goods_account END,
+ CASE WHEN i."replenishmentSystem" = 'Buy' THEN 'Raw Materials Account' ELSE 'Finished Goods Account' END
+ INTO v_item_inventory_account, v_item_inventory_description
+ FROM "item" i
+ WHERE i."id" = v_item_id
+ AND i."companyId" = p_company_id;
+
+ -- Non-Inventory (Service): the produced output is never stocked, so completion
+ -- relieves WIP straight to Cost of Goods Sold (Epicor "Make Direct" pattern).
+ -- >>> REV-REC SEAM (spec .ai/specs/2026-07-04-revenue-recognition.md, issue #1048):
+ -- when revenue recognition lands, Percent-of-Completion elements will gate THIS
+ -- branch off and post COGS as-incurred in the recognition run instead. <<<
+ IF v_item_tracking_type = 'Non-Inventory' THEN
+ v_item_inventory_account := v_cogs_account;
+ v_item_inventory_description := 'Cost of Goods Sold';
+ END IF;
+
+ -- Fetch dimension IDs
+ SELECT
+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Item' THEN "id" END),
+ MAX(CASE WHEN "entityType" = 'Location' THEN id END),
+ MAX(CASE WHEN "entityType" = 'CostCenter' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Employee' THEN id END)
+ INTO v_dimension_item_posting_group, v_dimension_item, v_dimension_location,
+ v_dimension_cost_center, v_dimension_employee
+ FROM dimension
+ WHERE "companyGroupId" = v_company_group_id
+ AND active = true
+ AND "entityType" IN ('ItemPostingGroup', 'Item', 'Location', 'CostCenter', 'Employee');
+
+ -- Post unposted production events as labor/machine + overhead absorption JEs
+ -- (mirrors post-production-event; this is the catch-up path for events that
+ -- were never posted individually)
+ FOR v_event IN
+ SELECT
+ pe.id,
+ pe.duration,
+ pe.type,
+ pe."employeeId",
+ wc."laborRate",
+ wc."machineRate",
+ wc."overheadRate"
+ FROM "productionEvent" pe
+ INNER JOIN "jobOperation" jo ON jo.id = pe."jobOperationId"
+ INNER JOIN "workCenter" wc ON wc.id = pe."workCenterId"
+ WHERE jo."jobId" = p_job_id
+ AND pe."endTime" IS NOT NULL
+ AND pe."postedToGL" = false
+ AND pe.duration > 0
+ LOOP
+ v_duration_hours := v_event.duration::NUMERIC / 3600;
+ v_rate := CASE
+ WHEN v_event.type = 'Machine' THEN COALESCE(v_event."machineRate", 0)
+ ELSE COALESCE(v_event."laborRate", 0)
+ END;
+ v_labor_cost := v_duration_hours * v_rate;
+ v_overhead_cost := v_duration_hours * COALESCE(v_event."overheadRate", 0);
+ v_event_reference := 'production-event:' || v_event.id;
+
+ IF (v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL)
+ OR (v_overhead_cost > 0 AND v_overhead_absorption_account IS NOT NULL) THEN
+ v_labor_journal_line_reference := nanoid();
+
+ -- Get current accounting period
+ SELECT id INTO v_labor_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_company_today
+ AND "endDate" >= v_company_today
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_company_today
+ AND "endDate" >= v_company_today
+ RETURNING id INTO v_labor_accounting_period_id;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', v_company_today)::DATE,
+ (date_trunc('month', v_company_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_labor_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_labor_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_labor_journal_entry_id, v_labor_accounting_period_id,
+ v_event.type || ' Time — Job ' || v_job_id_readable,
+ v_company_today, p_company_id, 'Production Event', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_labor_journal_id;
+
+ IF v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL THEN
+ -- DR WIP (labor/machine)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_wip_account, 'WIP Account',
+ v_labor_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on WIP line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on WIP line (the finished good this labor rolls into)
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ -- CR Labor/Machine Absorption
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_labor_absorption_account, 'Labor/Machine Absorption',
+ -v_labor_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on absorption line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on absorption line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+ END IF;
+
+ IF v_overhead_cost > 0 AND v_overhead_absorption_account IS NOT NULL THEN
+ -- DR WIP (overhead)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_wip_account, 'WIP Account (Overhead)',
+ v_overhead_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on WIP overhead line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on WIP overhead line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ -- CR Overhead Absorption
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_overhead_absorption_account, 'Overhead Absorption',
+ -v_overhead_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on overhead absorption line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on overhead absorption line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+ END IF;
+ END IF;
+
+ UPDATE "productionEvent"
+ SET "postedToGL" = true
+ WHERE id = v_event.id;
+ END LOOP;
+
+ -- Calculate accumulated WIP cost for this job
+ SELECT COALESCE(ABS(SUM(jl.amount)), 0)
+ INTO v_accumulated_wip_cost
+ FROM "journalLine" jl
+ INNER JOIN journal j ON j.id = jl."journalId"
+ WHERE jl."accountId" = v_wip_account
+ AND jl."documentId" = p_job_id
+ AND j."companyId" = p_company_id;
+
+ IF v_accumulated_wip_cost <= 0 THEN
+ RETURN;
+ END IF;
+
+ -- A stocked re-completion at the quantity already received has no units to
+ -- carry this cost. The catch-up WIP above stays in WIP and is discharged with
+ -- the next receipt; the per-unit cost below would otherwise divide by zero.
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'
+ AND v_quantity_received_to_inventory <= 0 THEN
+ RETURN;
+ END IF;
+
+ v_today := v_company_today;
+ v_journal_line_reference := nanoid();
+
+ -- Get accounting period for WIP discharge
+ SELECT id INTO v_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ RETURNING id INTO v_accounting_period_id;
+
+ IF v_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', v_today)::DATE,
+ (date_trunc('month', v_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_journal_entry_id, v_accounting_period_id,
+ 'Job Completion ' || v_job_id_readable,
+ v_today, p_company_id, 'Job Receipt', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_journal_id;
+
+ -- DR Inventory (Raw Materials or Finished Goods by item)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_item_inventory_account, v_item_inventory_description,
+ v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := ARRAY[v_labor_jl_id];
+
+ -- CR WIP
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_wip_account, 'WIP Account',
+ -v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := v_jl_ids || v_labor_jl_id;
+
+ -- Write costLedger entry for finished good (skipped for Non-Inventory: no
+ -- output layer exists for a service — its cost went straight to COGS above)
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ INSERT INTO "costLedger" (
+ "itemLedgerType", "costLedgerType", adjustment,
+ "documentType", "documentId", "itemId",
+ quantity, cost, "remainingQuantity", "companyId"
+ ) VALUES (
+ 'Output', 'Direct Cost', false,
+ 'Job Receipt', p_job_id, v_item_id,
+ v_quantity_received_to_inventory, v_accumulated_wip_cost,
+ v_quantity_received_to_inventory, p_company_id
+ );
+ END IF;
+
+ -- Update item cost
+ SELECT "costingMethod", "unitCost", "itemPostingGroupId"
+ INTO v_costing_method, v_existing_unit_cost, v_item_posting_group_id
+ FROM "itemCost"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ -- Update itemCost.unitCost (skipped for Non-Inventory: a service has no
+ -- stocked unit cost; the read above still feeds the dimension inserts below)
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ v_new_per_unit_cost := v_accumulated_wip_cost / v_quantity_received_to_inventory;
+
+ IF v_costing_method = 'Average' THEN
+ SELECT COALESCE(SUM(quantity), 0)
+ INTO v_total_qty_on_hand
+ FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ v_prior_qty := v_total_qty_on_hand - v_quantity_received_to_inventory;
+ v_prior_value := v_prior_qty * COALESCE(v_existing_unit_cost, 0);
+
+ IF v_total_qty_on_hand > 0 THEN
+ v_new_unit_cost := (v_prior_value + v_accumulated_wip_cost) / v_total_qty_on_hand;
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ ELSIF v_costing_method IN ('FIFO', 'LIFO') THEN
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_per_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+ END IF;
+
+ -- Insert dimensions on WIP discharge journal lines
+ IF v_jl_ids IS NOT NULL AND array_length(v_jl_ids, 1) > 0 THEN
+ FOR i IN 1..array_length(v_jl_ids, 1)
+ LOOP
+ IF v_item_posting_group_id IS NOT NULL AND v_dimension_item_posting_group IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_item_posting_group, v_item_posting_group_id, p_company_id
+ );
+ END IF;
+
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id
+ );
+ END IF;
+ END LOOP;
+ END IF;
+END;
+$$;
diff --git a/packages/database/supabase/migrations/20260916155634_batch-completion-completes-draft-jobs.sql b/packages/database/supabase/migrations/20260916155634_batch-completion-completes-draft-jobs.sql
new file mode 100644
index 0000000000..a9b6b00fea
--- /dev/null
+++ b/packages/database/supabase/migrations/20260916155634_batch-completion-completes-draft-jobs.sql
@@ -0,0 +1,142 @@
+-- Batch completion completes Draft member jobs.
+--
+-- A released batch puts Draft/Planned jobs' operations on the shop floor
+-- (batch release outranks job release), but sync_finish_job_operation only
+-- auto-completed and received jobs in Ready/In Progress/Paused. A completed
+-- batch of Draft jobs therefore left every member job in Draft, its receipts
+-- unposted, and a merged output lot holding only the one received job's
+-- stock instead of the combined quantity.
+--
+-- sync_finish_job_operation is redefined verbatim from
+-- 20260914095239_complete-job-received-quantity.sql with one widened gate:
+-- Draft/Planned jobs proceed when the completed operation belongs to a
+-- batch. Nothing changes for single (non-batched) operations -- a Draft
+-- job's operation cannot flip Done outside a batch on the floor.
+
+CREATE OR REPLACE FUNCTION sync_finish_job_operation(
+ p_table TEXT,
+ p_operation TEXT,
+ p_new JSONB,
+ p_old JSONB
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_job_location_id TEXT;
+ v_job_storage_unit_id TEXT;
+ v_job_quantity NUMERIC;
+ v_sales_order_id TEXT;
+ v_quantity_complete NUMERIC;
+ v_quantity_lost NUMERIC;
+ v_quantity_received NUMERIC;
+ v_job_status TEXT;
+BEGIN
+ IF p_operation != 'UPDATE' THEN RETURN; END IF;
+ IF (p_new->>'status') != 'Done' OR (p_old->>'status') = 'Done' THEN RETURN; END IF;
+
+ UPDATE "productionEvent"
+ SET "endTime" = NOW()
+ WHERE "jobOperationId" = p_new->>'id'
+ AND "endTime" IS NULL;
+
+ UPDATE "jobOperation" op
+ SET status = 'Ready'
+ WHERE EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep
+ WHERE dep."operationId" = op.id
+ AND dep."dependsOnId" = p_new->>'id'
+ AND op.status = 'Waiting'
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep2
+ JOIN "jobOperation" jo2 ON jo2.id = dep2."dependsOnId"
+ WHERE dep2."operationId" = op.id
+ AND jo2.status != 'Done'
+ AND jo2.id != p_new->>'id'
+ );
+
+ SELECT status INTO v_job_status FROM "job" WHERE id = p_new->>'jobId';
+ -- A Draft/Planned job's operation can only reach Done through a released
+ -- BATCH (batch release outranks job release for floor visibility), so the
+ -- run genuinely happened. Completing the batch must complete those jobs
+ -- too: otherwise their output lots exist while their receipts never post,
+ -- and a merged output lot carries only the received fraction of its
+ -- quantity.
+ IF v_job_status NOT IN ('Ready', 'In Progress', 'Paused')
+ AND NOT (
+ (p_new->>'jobOperationBatchId') IS NOT NULL
+ AND v_job_status IN ('Draft', 'Planned')
+ ) THEN
+ RETURN;
+ END IF;
+
+ IF is_last_job_operation(p_new->>'id') THEN
+ SELECT "locationId", "storageUnitId", quantity, "salesOrderId", "quantityReceivedToInventory"
+ INTO v_job_location_id, v_job_storage_unit_id, v_job_quantity, v_sales_order_id, v_quantity_received
+ FROM "job"
+ WHERE id = p_new->>'jobId';
+
+ v_quantity_complete := (
+ SELECT COALESCE(SUM(terminal_jo."quantityComplete"), 0)
+ FROM "jobOperation" terminal_jo
+ INNER JOIN "jobMakeMethod" terminal_jmm ON terminal_jmm.id = terminal_jo."jobMakeMethodId"
+ WHERE terminal_jo."jobId" = p_new->>'jobId'
+ AND terminal_jmm."parentMaterialId" IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep
+ INNER JOIN "jobOperation" child_jo ON child_jo.id = dep."operationId"
+ INNER JOIN "jobMakeMethod" child_jmm ON child_jmm.id = child_jo."jobMakeMethodId"
+ WHERE dep."dependsOnId" = terminal_jo.id
+ AND child_jmm."parentMaterialId" IS NULL
+ )
+ );
+
+ IF COALESCE(v_quantity_complete, 0) = 0 THEN
+ -- The zero fallback exists for the quantity-less Finish flow (no
+ -- productionQuantity ever recorded). When the job DID record scrap or
+ -- rework, zero completions is a real outcome (e.g. a fully-scrapped
+ -- lot) — falling back would receive scrapped units into stock.
+ SELECT COALESCE(SUM(COALESCE("quantityScrapped", 0) + COALESCE("quantityReworked", 0)), 0)
+ INTO v_quantity_lost
+ FROM "jobOperation"
+ WHERE "jobId" = p_new->>'jobId';
+
+ IF v_quantity_lost = 0 THEN
+ v_quantity_complete := v_job_quantity;
+ ELSE
+ -- Nothing to receive: close the job without posting Assembly Output.
+ -- Materials were already consumed by the scrap/complete flows; WIP
+ -- cost disposition for fully-scrapped jobs is a costing follow-up.
+ UPDATE "job"
+ SET status = 'Completed',
+ "completedDate" = NOW(),
+ "quantityComplete" = 0,
+ "updatedBy" = COALESCE(p_new->>'updatedBy', p_new->>'createdBy'),
+ "updatedAt" = NOW()
+ WHERE id = p_new->>'jobId';
+ RETURN;
+ END IF;
+ END IF;
+
+ -- A reopened job may already have received more than its operations now
+ -- report. complete_job_to_inventory refuses a quantity below what was
+ -- received, and refusing here would block the Done update itself.
+ v_quantity_complete := GREATEST(v_quantity_complete, COALESCE(v_quantity_received, 0));
+
+ PERFORM complete_job_to_inventory(
+ p_job_id := p_new->>'jobId',
+ p_quantity_complete := v_quantity_complete,
+ p_storage_unit_id := v_job_storage_unit_id,
+ p_location_id := v_job_location_id,
+ p_company_id := p_new->>'companyId',
+ p_user_id := COALESCE(p_new->>'updatedBy', p_new->>'createdBy')
+ );
+ END IF;
+END;
+$$;
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20260918094217_batch-output-lot-at-creation.sql b/packages/database/supabase/migrations/20260918094217_batch-output-lot-at-creation.sql
new file mode 100644
index 0000000000..f9f6eb1569
--- /dev/null
+++ b/packages/database/supabase/migrations/20260918094217_batch-output-lot-at-creation.sql
@@ -0,0 +1,137 @@
+-- Output lot identity is decided when a batch is PLANNED, not on the floor.
+--
+-- mergeOutput: every member's output completes into one lot, outputLotNumber.
+-- Otherwise each member keeps its own lot, numbered by its WIP entity's
+-- readableId (the job's batch number property) — set in the batch builder or
+-- the job sidebar, and required by completion either way.
+ALTER TABLE "jobOperationBatch"
+ ADD COLUMN "mergeOutput" BOOLEAN NOT NULL DEFAULT false,
+ ADD COLUMN "outputLotNumber" TEXT;
+
+ALTER TABLE "jobOperationBatch"
+ ADD CONSTRAINT "jobOperationBatch_mergeOutput_lot_check"
+ CHECK (
+ NOT "mergeOutput"
+ OR ("outputLotNumber" IS NOT NULL AND length(btrim("outputLotNumber")) > 0)
+ );
+
+-- Candidates now carry what the builder's Output card needs: the produced
+-- item, whether it is batch-tracked, and the job's live WIP entity with its
+-- current lot number (pre-fills the per-job lot fields). Redefined from
+-- 20260905132037_job-operation-batching.sql; the return type changes, so
+-- drop first.
+DROP FUNCTION IF EXISTS get_batchable_operations(TEXT, TEXT);
+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"
+ JOIN "item" i ON i."id" = j."itemId"
+ LEFT JOIN "jobMakeMethod" jmm
+ ON jmm."id" = jo."jobMakeMethodId" AND jmm."companyId" = jo."companyId"
+ 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 (
+ jm."jobOperationId" = jo."id"
+ OR (
+ jm."jobId" = jo."jobId"
+ AND jm."jobOperationId" IS NULL
+ AND NOT EXISTS (
+ SELECT 1 FROM "jobMaterial" jml
+ WHERE jml."jobId" = jo."jobId"
+ AND jml."companyId" = jo."companyId"
+ AND jml."jobOperationId" = jo."id"
+ )
+ )
+ )
+ ) 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 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/migrations/20260918132911_method-tree-top-level-operation.sql b/packages/database/supabase/migrations/20260918132911_method-tree-top-level-operation.sql
new file mode 100644
index 0000000000..aac417f193
--- /dev/null
+++ b/packages/database/supabase/migrations/20260918132911_method-tree-top-level-operation.sql
@@ -0,0 +1,184 @@
+-- The root make method's own BOM lines lost their operation assignment:
+-- get_method_tree's anchor member selected NULL AS "operationId" while the
+-- recursive member (sub-assembly lines) selected "methodOperationId". The NULL
+-- was a placeholder from when "operationId" was first added (4faa220c44), the
+-- twin of the anchor's hardcoded "order" that the tree-order fix later
+-- corrected. get-method maps this column onto jobMaterial.jobOperationId /
+-- quoteMaterial.quoteOperationId (itemToJob, itemToJobMakeMethod,
+-- itemToQuoteLine, itemToQuoteMakeMethod), so jobs and quotes created from an
+-- item never carried the operation a top-level line was assigned to. No other
+-- caller reads the column. Same signature and return type, so no DROP needed.
+
+CREATE OR REPLACE FUNCTION get_method_tree(uid TEXT)
+RETURNS TABLE (
+ "methodMaterialId" TEXT,
+ "makeMethodId" TEXT,
+ "materialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "itemType" TEXT,
+ "description" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "unitCost" NUMERIC,
+ "quantity" NUMERIC,
+ "methodType" "methodType",
+ "itemTrackingType" TEXT,
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "operationId" TEXT,
+ "methodOperationStepIds" JSONB,
+ "isRoot" BOOLEAN,
+ "kit" BOOLEAN,
+ "revision" TEXT,
+ "externalId" JSONB,
+ "version" NUMERIC,
+ "storageUnitIds" JSONB,
+ "isPickDescendant" BOOLEAN,
+ "replenishmentSystem" "itemReplenishmentSystem"
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "id",
+ "makeMethodId",
+ "methodType",
+ COALESCE(
+ "materialMakeMethodId",
+ CASE WHEN "methodType" = 'Pull from Inventory' THEN (
+ SELECT amm.id FROM "activeMakeMethods" amm WHERE amm."itemId" = "methodMaterial"."itemId" LIMIT 1
+ ) END
+ ) AS "materialMakeMethodId",
+ "itemId",
+ "itemType",
+ "quantity",
+ "makeMethodId" AS "parentMaterialId",
+ "methodOperationId" AS "operationId",
+ COALESCE("order", 1) AS "order",
+ "kit",
+ "storageUnitIds",
+ false AS "isPickDescendant"
+ FROM
+ "methodMaterial"
+ WHERE
+ "makeMethodId" = uid
+ UNION
+ SELECT
+ child."id",
+ child."makeMethodId",
+ child."methodType",
+ COALESCE(
+ child."materialMakeMethodId",
+ CASE WHEN child."methodType" = 'Pull from Inventory' THEN (
+ SELECT amm.id FROM "activeMakeMethods" amm WHERE amm."itemId" = child."itemId" LIMIT 1
+ ) END
+ ) AS "materialMakeMethodId",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ parent."id" AS "parentMaterialId",
+ child."methodOperationId" AS "operationId",
+ child."order",
+ child."kit",
+ child."storageUnitIds",
+ (parent."methodType" = 'Pull from Inventory' OR parent."isPickDescendant") AS "isPickDescendant"
+ FROM
+ "methodMaterial" child
+ INNER JOIN material parent ON parent."materialMakeMethodId" = child."makeMethodId"
+)
+SELECT
+ material.id as "methodMaterialId",
+ material."makeMethodId",
+ material."materialMakeMethodId",
+ material."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ material."itemType",
+ item."name" AS "description",
+ item."unitOfMeasureCode",
+ cost."unitCost",
+ material."quantity",
+ material."methodType",
+ item."itemTrackingType",
+ material."parentMaterialId",
+ material."order",
+ material."operationId",
+ (
+ SELECT COALESCE(jsonb_agg(jsonb_build_object('id', mms."methodOperationStepId", 'quantity', mms."quantity")), '[]'::jsonb)
+ FROM "methodMaterialStep" mms
+ WHERE mms."methodMaterialId" = material.id
+ ) AS "methodOperationStepIds",
+ false AS "isRoot",
+ material."kit",
+ item."revision",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = item.id
+ ) AS "externalId",
+ mm2."version",
+ material."storageUnitIds",
+ material."isPickDescendant",
+ item."replenishmentSystem"
+FROM material
+INNER JOIN item
+ ON material."itemId" = item.id
+INNER JOIN "itemCost" cost
+ ON item.id = cost."itemId"
+INNER JOIN "makeMethod" mm
+ ON material."makeMethodId" = mm.id
+LEFT JOIN "makeMethod" mm2
+ ON material."materialMakeMethodId" = mm2.id
+UNION
+SELECT
+ mm."id" AS "methodMaterialId",
+ NULL AS "makeMethodId",
+ mm.id AS "materialMakeMethodId",
+ mm."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ item."type"::text,
+ item."name" AS "description",
+ item."unitOfMeasureCode",
+ cost."unitCost",
+ 1 AS "quantity",
+ 'Make to Order' AS "methodType",
+ item."itemTrackingType",
+ NULL AS "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ NULL AS "operationId",
+ '[]'::jsonb AS "methodOperationStepIds",
+ true AS "isRoot",
+ false AS "kit",
+ item."revision",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = item.id
+ ) AS "externalId",
+ mm."version",
+ '{}'::JSONB AS "storageUnitIds",
+ false AS "isPickDescendant",
+ item."replenishmentSystem"
+FROM "makeMethod" mm
+INNER JOIN item
+ ON mm."itemId" = item.id
+INNER JOIN "itemCost" cost
+ ON item.id = cost."itemId"
+WHERE mm.id = uid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
diff --git a/packages/dev/docker/docker-compose.dev.yml b/packages/dev/docker/docker-compose.dev.yml
index 6c1133c633..427ccef035 100644
--- a/packages/dev/docker/docker-compose.dev.yml
+++ b/packages/dev/docker/docker-compose.dev.yml
@@ -12,8 +12,12 @@ services:
deploy:
resources:
limits:
- memory: ${MEM_POSTGRES:-384m}
- cpus: ${CPU_POSTGRES:-1.0}
+ # Defaults are sized so one stack runs smoothly while a machine can
+ # host several worktree stacks at once (limits are ceilings, not
+ # reservations — idle usage is far below them). Override any of these
+ # per worktree via MEM_*/CPU_* in that worktree's .env.
+ memory: ${MEM_POSTGRES:-1g}
+ cpus: ${CPU_POSTGRES:-2}
networks:
default:
aliases:
@@ -73,7 +77,7 @@ services:
deploy:
resources:
limits:
- memory: ${MEM_GOTRUE:-48m}
+ memory: ${MEM_GOTRUE:-96m}
cpus: ${CPU_GOTRUE:-0.25}
environment:
GOTRUE_API_HOST: 0.0.0.0
@@ -129,8 +133,8 @@ services:
deploy:
resources:
limits:
- memory: ${MEM_POSTGREST:-160m}
- cpus: ${CPU_POSTGREST:-0.25}
+ memory: ${MEM_POSTGREST:-256m}
+ cpus: ${CPU_POSTGREST:-1}
depends_on:
postgres:
condition: service_healthy
@@ -155,8 +159,8 @@ services:
deploy:
resources:
limits:
- memory: ${MEM_REALTIME:-256m}
- cpus: ${CPU_REALTIME:-0.25}
+ memory: ${MEM_REALTIME:-384m}
+ cpus: ${CPU_REALTIME:-0.5}
depends_on:
postgres:
condition: service_healthy
@@ -253,7 +257,7 @@ services:
deploy:
resources:
limits:
- memory: ${MEM_META:-96m}
+ memory: ${MEM_META:-128m}
cpus: ${CPU_META:-0.25}
profiles: ["full"]
depends_on:
@@ -273,8 +277,8 @@ services:
deploy:
resources:
limits:
- memory: ${MEM_STUDIO:-256m}
- cpus: ${CPU_STUDIO:-0.25}
+ memory: ${MEM_STUDIO:-384m}
+ cpus: ${CPU_STUDIO:-0.5}
profiles: ["full"]
depends_on:
meta:
@@ -297,7 +301,7 @@ services:
deploy:
resources:
limits:
- memory: ${MEM_INBUCKET:-32m}
+ memory: ${MEM_INBUCKET:-64m}
cpus: ${CPU_INBUCKET:-0.25}
profiles: ["full"]
ports:
@@ -314,7 +318,7 @@ services:
# business function. Starved of CPU, worker boot outlives the isolate
# CPU budget and requests hang mid-kill — give it app-tier resources.
memory: ${MEM_EDGE:-1g}
- cpus: ${CPU_EDGE:-2}
+ cpus: ${CPU_EDGE:-3}
depends_on:
postgres:
condition: service_healthy
@@ -353,7 +357,7 @@ services:
deploy:
resources:
limits:
- memory: ${MEM_KONG:-192m}
+ memory: ${MEM_KONG:-256m}
cpus: ${CPU_KONG:-0.5}
depends_on:
gotrue:
@@ -395,8 +399,8 @@ services:
deploy:
resources:
limits:
- memory: ${MEM_INNGEST:-128m}
- cpus: ${CPU_INNGEST:-0.25}
+ memory: ${MEM_INNGEST:-256m}
+ cpus: ${CPU_INNGEST:-0.5}
ports:
- "${PORT_INNGEST}:8288"
command:
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index a6de7da8b8..ffa773169b 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -1,11 +1,11 @@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20260917213637",
+ "schemaVersion": "20260918132911",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-09-18T14:24:54.326Z",
+ "exportedAt": "2026-09-19T17:17:38.334Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",
@@ -129,59 +129,59 @@
"id",
"endingBalanceDate",
"companyId",
- "createdAt",
- "updatedAt"
+ "updatedAt",
+ "createdAt"
]
},
{
"name": "accountingSyncOperation",
"rows": 0,
"columns": [
- "direction",
- "lastAttemptAt",
- "id",
- "idempotencyKey",
- "attemptCount",
- "status",
- "companyId",
- "errorCode",
- "metadata",
- "createdBy",
- "externalId",
- "updatedAt",
"completedAt",
+ "updatedAt",
"entityId",
- "trigger",
+ "createdBy",
+ "externalId",
+ "integration",
+ "errorMessage",
+ "entityType",
"createdAt",
"updatedBy",
- "entityType",
- "errorMessage",
- "integration"
+ "trigger",
+ "idempotencyKey",
+ "id",
+ "lastAttemptAt",
+ "direction",
+ "metadata",
+ "companyId",
+ "errorCode",
+ "status",
+ "attemptCount"
]
},
{
"name": "accountingSyncTieOut",
"rows": 0,
"columns": [
- "computedAt",
- "createdAt",
- "accountId",
- "providerAmount",
- "syncedAmount",
- "updatedAt",
- "updatedBy",
- "externalDelta",
- "integration",
- "accountingPeriodId",
- "carbonPostedAmount",
- "blockedAmount",
- "excludedAmount",
- "id",
- "pendingAmount",
"docBackedAmount",
+ "pendingAmount",
+ "createdBy",
"internalDelta",
"companyId",
- "createdBy"
+ "carbonPostedAmount",
+ "excludedAmount",
+ "id",
+ "blockedAmount",
+ "syncedAmount",
+ "integration",
+ "externalDelta",
+ "accountingPeriodId",
+ "updatedAt",
+ "updatedBy",
+ "computedAt",
+ "createdAt",
+ "accountId",
+ "providerAmount"
]
},
{
@@ -204,15 +204,15 @@
"name": "agentThread",
"rows": 0,
"columns": [
- "userId",
"title",
+ "userId",
"createdBy",
"modelId",
"companyId",
"updatedAt",
"createdAt",
- "updatedBy",
"id",
+ "updatedBy",
"lastContext"
]
},
@@ -220,83 +220,83 @@
"name": "agentMessage",
"rows": 0,
"columns": [
- "feedback",
- "inputTokens",
- "id",
- "createdBy",
- "finishReason",
"outputTokens",
- "threadId",
+ "finishReason",
"updatedBy",
- "createdAt",
- "context",
+ "threadId",
+ "feedback",
+ "createdBy",
+ "id",
+ "inputTokens",
"feedbackNote",
- "updatedAt",
+ "role",
"companyId",
- "role"
+ "updatedAt",
+ "context",
+ "createdAt"
]
},
{
"name": "agentMessagePart",
"rows": 0,
"columns": [
- "toolOutput",
- "id",
- "toolCallId",
- "textContent",
- "toolDurationMs",
- "messageId",
- "createdAt",
- "toolInput",
- "toolClassification",
- "type",
- "toolState",
- "createdBy",
- "updatedBy",
+ "toolName",
"updatedAt",
- "orderIndex",
"errorMessage",
"companyId",
- "toolName"
+ "orderIndex",
+ "updatedBy",
+ "createdBy",
+ "toolState",
+ "type",
+ "toolInput",
+ "toolClassification",
+ "messageId",
+ "toolDurationMs",
+ "createdAt",
+ "textContent",
+ "toolOutput",
+ "toolCallId",
+ "id"
]
},
{
"name": "approvalRequest",
"rows": 0,
"columns": [
- "createdBy",
- "documentType",
- "updatedAt",
- "decisionAt",
- "decisionNotes",
- "decisionBy",
- "id",
- "requestedBy",
+ "requestedAt",
"documentId",
"createdAt",
"status",
- "requestedAt",
+ "updatedBy",
"amount",
"companyId",
- "updatedBy"
+ "decisionAt",
+ "createdBy",
+ "documentType",
+ "updatedAt",
+ "requestedBy",
+ "decisionNotes",
+ "decisionBy",
+ "id"
]
},
{
"name": "approvalRule",
"rows": 0,
"columns": [
- "updatedAt",
- "defaultApproverId",
- "escalationDays",
- "approverGroupIds",
- "enabled",
"lowerBoundAmount",
- "id",
- "createdBy",
"updatedBy",
- "companyId",
+ "createdBy",
+ "id",
"createdAt",
- "documentType"
+ "companyId",
+ "documentType",
+ "defaultApproverId",
+ "updatedAt",
+ "escalationDays",
+ "enabled",
+ "approverGroupIds"
]
},
{
@@ -308,8 +308,8 @@
"companyId",
"createdAt",
"endDate",
- "archivePath",
"startDate",
+ "archivePath",
"sizeBytes"
]
},
@@ -317,66 +317,66 @@
"name": "changeOrderRequiredAction",
"rows": 0,
"columns": [
- "updatedBy",
- "active",
- "name",
- "createdBy",
- "updatedAt",
"companyId",
- "createdAt",
+ "updatedAt",
"id",
- "customFields"
+ "customFields",
+ "createdAt",
+ "active",
+ "name",
+ "updatedBy",
+ "createdBy"
]
},
{
"name": "changeOrderType",
"rows": 0,
"columns": [
- "id",
- "updatedAt",
- "name",
- "createdBy",
- "createdAt",
"companyId",
- "updatedBy"
+ "createdAt",
+ "updatedBy",
+ "createdBy",
+ "name",
+ "id",
+ "updatedAt"
]
},
{
"name": "companyAccountsPayableBillingAddress",
"rows": 0,
"columns": [
- "city",
- "updatedAt",
- "addressLine2",
- "addressLine1",
- "postalCode",
- "email",
- "id",
- "phone",
- "state",
+ "fax",
+ "countryCode",
"updatedBy",
"name",
- "fax",
- "countryCode"
+ "state",
+ "email",
+ "phone",
+ "id",
+ "postalCode",
+ "addressLine1",
+ "addressLine2",
+ "city",
+ "updatedAt"
]
},
{
"name": "companyAccountsReceivableBillingAddress",
"rows": 0,
"columns": [
- "email",
- "phone",
- "id",
- "state",
- "updatedBy",
- "name",
- "fax",
- "countryCode",
+ "postalCode",
+ "addressLine2",
+ "addressLine1",
"city",
"updatedAt",
- "addressLine1",
- "addressLine2",
- "postalCode"
+ "countryCode",
+ "fax",
+ "updatedBy",
+ "name",
+ "state",
+ "id",
+ "phone",
+ "email"
]
},
{
@@ -486,16 +486,16 @@
"name": "costCenter",
"rows": 0,
"columns": [
- "createdBy",
- "updatedBy",
- "companyId",
- "parentCostCenterId",
- "createdAt",
- "id",
"customFields",
+ "id",
+ "createdAt",
+ "name",
"ownerId",
"updatedAt",
- "name"
+ "createdBy",
+ "parentCostCenterId",
+ "companyId",
+ "updatedBy"
]
},
{
@@ -591,8 +591,8 @@
"status",
"periodEnd",
"postedAt",
- "updatedBy",
"createdAt",
+ "updatedBy",
"depreciationRunId",
"postedBy",
"id",
@@ -603,32 +603,32 @@
"name": "dimension",
"rows": 0,
"columns": [
+ "active",
"createdBy",
"entityType",
"companyGroupId",
- "active",
- "createdAt",
- "updatedAt",
- "name",
"required",
"updatedBy",
- "id"
+ "id",
+ "updatedAt",
+ "createdAt",
+ "name"
]
},
{
"name": "dimensionValue",
"rows": 0,
"columns": [
- "id",
- "createdAt",
- "dimensionId",
- "updatedAt",
- "createdBy",
- "name",
+ "updatedBy",
"companyGroupId",
- "updatedBy"
- ]
- },
+ "name",
+ "createdBy",
+ "updatedAt",
+ "dimensionId",
+ "createdAt",
+ "id"
+ ]
+ },
{
"name": "document",
"rows": 0,
@@ -655,6 +655,12 @@
"name": "documentExtraction",
"rows": 0,
"columns": [
+ "storagePath",
+ "createdAt",
+ "sourceDocument",
+ "updatedAt",
+ "sourceDocumentId",
+ "status",
"filteredData",
"id",
"createdBy",
@@ -662,13 +668,7 @@
"updatedBy",
"companyId",
"extractedData",
- "error",
- "storagePath",
- "createdAt",
- "sourceDocument",
- "updatedAt",
- "sourceDocumentId",
- "status"
+ "error"
]
},
{
@@ -685,33 +685,33 @@
"name": "documentSection",
"rows": 0,
"columns": [
- "companyId",
- "updatedAt",
- "createdAt",
- "id",
- "updatedBy",
- "config",
+ "content",
"placement",
"name",
"createdBy",
- "content"
+ "id",
+ "updatedBy",
+ "config",
+ "companyId",
+ "updatedAt",
+ "createdAt"
]
},
{
"name": "documentTemplate",
"rows": 0,
"columns": [
- "documentType",
"formatVersion",
+ "documentType",
"settings",
- "blocks",
"updatedBy",
- "updatedAt",
+ "blocks",
"companyId",
+ "updatedAt",
"headerSectionId",
"createdBy",
- "footerSectionId",
"id",
+ "footerSectionId",
"createdAt",
"theme"
]
@@ -764,96 +764,96 @@
"name": "enforcementRule",
"rows": 0,
"columns": [
- "family",
- "filteredItemMatchAll",
- "name",
- "updatedAt",
- "updatedBy",
- "severity",
- "description",
- "filteredItemTypes",
- "customFields",
- "active",
- "createdAt",
- "createdBy",
- "filteredItemGroupIds",
- "companyId",
- "conditionAst",
- "targetType",
- "surfaces",
- "id",
+ "message",
"appliesToAll",
- "message"
+ "id",
+ "surfaces",
+ "targetType",
+ "conditionAst",
+ "companyId",
+ "filteredItemGroupIds",
+ "createdBy",
+ "createdAt",
+ "active",
+ "customFields",
+ "filteredItemTypes",
+ "description",
+ "severity",
+ "updatedBy",
+ "updatedAt",
+ "name",
+ "family",
+ "filteredItemMatchAll"
]
},
{
"name": "enforcementRuleAcknowledgment",
"rows": 0,
"columns": [
- "message",
- "severity",
- "id",
- "documentId",
- "createdAt",
- "companyId",
- "outcome",
- "itemId",
- "documentType",
"createdBy",
- "updatedBy",
- "ruleId",
+ "documentType",
+ "documentLineId",
"ruleName",
- "documentLineId"
+ "ruleId",
+ "updatedBy",
+ "documentId",
+ "id",
+ "severity",
+ "message",
+ "itemId",
+ "outcome",
+ "companyId",
+ "createdAt"
]
},
{
"name": "eventSystemSubscription",
"rows": 0,
"columns": [
- "operations",
"handlerType",
"table",
"companyId",
- "filter",
- "createdAt",
- "id",
+ "operations",
"active",
"config",
- "name"
+ "name",
+ "filter",
+ "createdAt",
+ "id"
]
},
{
"name": "exchangeRateOverride",
"rows": 0,
"columns": [
+ "rate",
+ "currencyCode",
+ "updatedBy",
+ "createdBy",
"companyId",
"updatedAt",
"id",
- "createdAt",
- "currencyCode",
- "rate",
- "updatedBy",
- "createdBy"
+ "createdAt"
]
},
{
"name": "externalIntegrationMapping",
"rows": 0,
"columns": [
- "id",
- "remoteUpdatedAt",
- "updatedAt",
- "allowDuplicateExternalId",
+ "entityId",
+ "updatedBy",
+ "integration",
+ "metadata",
+ "externalId",
+ "createdBy",
"companyId",
"entityType",
- "lastSyncedAt",
"createdAt",
- "externalId",
- "createdBy",
- "integration",
- "updatedBy",
- "entityId",
- "metadata"
+ "lastSyncedAt",
+ "updatedAt",
+ "remoteUpdatedAt",
+ "id",
+ "allowDuplicateExternalId"
]
},
{
@@ -865,31 +865,31 @@
"name": "fixedAssetClass",
"rows": 0,
"columns": [
- "accumulatedDepreciationAccountId",
- "customFields",
- "writeOffAccountId",
- "macrsPropertyClass",
- "taxDepreciationMethod",
- "name",
- "residualValuePercent",
- "gainOnDisposalAccountId",
- "id",
- "depreciationExpenseAccountId",
- "writeDownAccountId",
- "updatedBy",
- "assetAccountId",
- "depreciationMethod",
- "description",
- "taxUsefulLifeMonths",
- "companyId",
- "bonusDepreciationPercent",
- "createdBy",
- "taxResidualValuePercent",
- "macrsConvention",
"updatedAt",
"usefulLifeMonths",
+ "lossOnDisposalAccountId",
"createdAt",
- "lossOnDisposalAccountId"
+ "taxResidualValuePercent",
+ "createdBy",
+ "macrsConvention",
+ "taxUsefulLifeMonths",
+ "description",
+ "depreciationMethod",
+ "companyId",
+ "bonusDepreciationPercent",
+ "assetAccountId",
+ "updatedBy",
+ "depreciationExpenseAccountId",
+ "id",
+ "writeDownAccountId",
+ "residualValuePercent",
+ "gainOnDisposalAccountId",
+ "macrsPropertyClass",
+ "taxDepreciationMethod",
+ "name",
+ "accumulatedDepreciationAccountId",
+ "customFields",
+ "writeOffAccountId"
]
},
{
@@ -943,29 +943,29 @@
"name": "implementationCheckState",
"rows": 0,
"columns": [
- "createdAt",
- "kind",
- "itemKey",
- "value",
- "updatedBy",
- "companyId",
"createdBy",
"id",
- "updatedAt"
+ "updatedAt",
+ "updatedBy",
+ "companyId",
+ "value",
+ "createdAt",
+ "kind",
+ "itemKey"
]
},
{
"name": "implementationFieldValue",
"rows": 0,
"columns": [
- "id",
"createdAt",
- "companyId",
+ "id",
"updatedAt",
+ "companyId",
"createdBy",
+ "updatedBy",
"value",
- "fieldKey",
- "updatedBy"
+ "fieldKey"
]
},
{
@@ -973,14 +973,14 @@
"rows": 0,
"columns": [
"sortOrder",
- "payload",
- "collection",
"createdAt",
- "id",
- "updatedAt",
+ "collection",
+ "payload",
"createdBy",
- "companyId",
- "updatedBy"
+ "updatedAt",
+ "id",
+ "updatedBy",
+ "companyId"
]
},
{
@@ -1006,23 +1006,23 @@
"name": "itarCertification",
"rows": 0,
"columns": [
- "certifiedAt",
- "title",
- "companyId",
- "expiresAt",
- "updatedBy",
- "docHash",
- "ipAddress",
- "complianceContact",
- "id",
- "fullLegalName",
+ "docVersion",
+ "userAgent",
+ "createdAt",
+ "updatedAt",
+ "userId",
"type",
"createdBy",
- "userId",
- "updatedAt",
- "createdAt",
- "userAgent",
- "docVersion"
+ "fullLegalName",
+ "id",
+ "complianceContact",
+ "ipAddress",
+ "docHash",
+ "updatedBy",
+ "expiresAt",
+ "companyId",
+ "title",
+ "certifiedAt"
]
},
{
@@ -1102,40 +1102,40 @@
"name": "intercompanyTransaction",
"rows": 0,
"columns": [
- "targetJournalLineId",
- "documentId",
- "description",
- "id",
- "documentType",
- "currencyCode",
- "companyGroupId",
- "eliminationJournalId",
- "updatedAt",
"status",
"sourceJournalLineId",
- "amount",
- "createdAt",
+ "updatedAt",
+ "targetCompanyId",
"sourceCompanyId",
- "targetCompanyId"
+ "createdAt",
+ "amount",
+ "id",
+ "description",
+ "documentId",
+ "targetJournalLineId",
+ "companyGroupId",
+ "eliminationJournalId",
+ "currencyCode",
+ "documentType"
]
},
{
"name": "intercompanyEliminationLine",
"rows": 0,
"columns": [
- "journalLineId",
- "updatedBy",
- "intercompanyTransactionId",
- "role",
- "amount",
- "quantity",
"id",
+ "quantity",
"createdAt",
"accountId",
- "updatedAt",
"companyId",
+ "updatedAt",
"itemId",
- "createdBy"
+ "createdBy",
+ "updatedBy",
+ "journalLineId",
+ "role",
+ "intercompanyTransactionId",
+ "amount"
]
},
{
@@ -1146,8 +1146,8 @@
"id",
"journalLineId",
"companyId",
- "valueId",
- "dimensionId"
+ "dimensionId",
+ "valueId"
]
},
{
@@ -1180,121 +1180,121 @@
"name": "fixedAsset",
"rows": 0,
"columns": [
- "name",
- "fixedAssetClassId",
- "macrsPropertyClass",
- "acquisitionDate",
- "depreciationStartDate",
- "createdAt",
- "locationId",
- "status",
- "notes",
- "assetLifetimeUsage",
+ "disposalMethod",
+ "serialNumber",
+ "companyId",
+ "taxDepreciationMethod",
+ "id",
+ "usefulLifeMonths",
+ "disposalDate",
+ "customFields",
+ "residualValuePercent",
+ "updatedAt",
+ "depreciationMethod",
+ "createdBy",
+ "taxResidualValuePercent",
+ "fixedAssetId",
+ "bonusDepreciationPercent",
+ "macrsConvention",
+ "accumulatedTaxDepreciation",
+ "saleProceeds",
+ "acquisitionCost",
+ "description",
"accumulatedDepreciation",
"updatedBy",
"taxUsefulLifeMonths",
- "description",
- "saleProceeds",
- "acquisitionCost",
- "macrsConvention",
- "accumulatedTaxDepreciation",
- "bonusDepreciationPercent",
- "fixedAssetId",
- "taxResidualValuePercent",
- "depreciationMethod",
- "updatedAt",
- "createdBy",
- "customFields",
- "residualValuePercent",
- "disposalDate",
- "id",
- "usefulLifeMonths",
- "companyId",
- "taxDepreciationMethod",
- "serialNumber",
- "disposalMethod"
+ "assetLifetimeUsage",
+ "notes",
+ "locationId",
+ "status",
+ "createdAt",
+ "depreciationStartDate",
+ "acquisitionDate",
+ "name",
+ "macrsPropertyClass",
+ "fixedAssetClassId"
]
},
{
"name": "depreciationRunLine",
"rows": 0,
"columns": [
- "fixedAssetId",
- "amount",
- "companyId",
- "taxAmount",
- "depreciationRunId",
+ "journalId",
"id",
- "journalId"
+ "depreciationRunId",
+ "taxAmount",
+ "companyId",
+ "fixedAssetId",
+ "amount"
]
},
{
"name": "fixedAssetDisposal",
"rows": 0,
"columns": [
- "netBookValueAtDisposal",
- "companyId",
- "id",
- "createdBy",
+ "gainLoss",
+ "disposalDate",
+ "disposalMethod",
+ "updatedBy",
+ "saleProceeds",
"journalId",
"createdAt",
"fixedAssetId",
- "updatedBy",
- "saleProceeds",
- "gainLoss",
- "disposalMethod",
- "disposalDate"
+ "netBookValueAtDisposal",
+ "id",
+ "companyId",
+ "createdBy"
]
},
{
"name": "fixedAssetUsageLog",
"rows": 0,
"columns": [
- "fixedAssetId",
- "createdBy",
- "updatedBy",
- "id",
- "companyId",
+ "createdAt",
"periodStart",
"periodEnd",
- "createdAt",
- "unitsProduced"
+ "unitsProduced",
+ "createdBy",
+ "fixedAssetId",
+ "companyId",
+ "updatedBy",
+ "id"
]
},
{
"name": "inventoryCount",
"rows": 0,
"columns": [
- "customFields",
- "companyId",
- "createdAt",
- "snapshotAt",
- "postedBy",
- "notes",
- "id",
- "postedAt",
- "isBlind",
- "inventoryCountId",
- "updatedBy",
"locationId",
+ "updatedBy",
+ "inventoryCountId",
"scope",
"createdBy",
"status",
- "updatedAt"
+ "updatedAt",
+ "companyId",
+ "createdAt",
+ "customFields",
+ "postedBy",
+ "snapshotAt",
+ "postedAt",
+ "id",
+ "notes",
+ "isBlind"
]
},
{
"name": "maintenanceFailureMode",
"rows": 0,
"columns": [
- "createdAt",
- "companyId",
- "createdBy",
- "updatedAt",
- "id",
"updatedBy",
+ "id",
+ "type",
"name",
- "type"
+ "createdAt",
+ "updatedAt",
+ "createdBy",
+ "companyId"
]
},
{
@@ -1417,17 +1417,17 @@
"name": "assemblyPlanJob",
"rows": 0,
"columns": [
- "planPath",
- "error",
- "status",
- "kind",
- "stats",
+ "modelUploadId",
+ "createdAt",
+ "companyId",
"updatedAt",
"id",
"createdBy",
- "createdAt",
- "companyId",
- "modelUploadId"
+ "stats",
+ "status",
+ "kind",
+ "error",
+ "planPath"
]
},
{
@@ -1529,52 +1529,52 @@
"name": "changeOrder",
"rows": 0,
"columns": [
- "priority",
- "updatedBy",
- "nonConformanceId",
- "sourceId",
- "requiredActionIds",
- "changeOrderId",
- "type",
- "changeOrderTypeId",
- "id",
- "openDate",
- "status",
- "updatedAt",
+ "reasonForChange",
"name",
"approvalRequirements",
- "reasonForChange",
- "tags",
"customFields",
- "sourceType",
- "createdAt",
- "assignee",
+ "tags",
+ "updatedAt",
+ "status",
"createdBy",
- "description",
+ "companyId",
"dueDate",
- "companyId"
+ "description",
+ "assignee",
+ "createdAt",
+ "sourceType",
+ "sourceId",
+ "changeOrderId",
+ "requiredActionIds",
+ "priority",
+ "nonConformanceId",
+ "updatedBy",
+ "id",
+ "changeOrderTypeId",
+ "openDate",
+ "type"
]
},
{
"name": "changeOrderActionTask",
"rows": 0,
"columns": [
- "assignee",
- "name",
- "updatedAt",
- "status",
- "updatedBy",
- "dueDate",
- "createdAt",
- "notes",
+ "completedDate",
+ "companyId",
+ "id",
+ "sortOrder",
"tags",
- "actionTypeId",
+ "notes",
"createdBy",
"changeOrderId",
- "completedDate",
- "sortOrder",
- "id",
- "companyId"
+ "actionTypeId",
+ "updatedBy",
+ "dueDate",
+ "createdAt",
+ "assignee",
+ "status",
+ "updatedAt",
+ "name"
]
},
{
@@ -1636,21 +1636,21 @@
"name": "notification",
"rows": 0,
"columns": [
+ "documentType",
+ "id",
+ "payload",
+ "title",
"seenAt",
"userId",
"from",
"documentId",
- "id",
- "documentType",
- "payload",
- "title",
- "topic",
- "companyId",
- "digestedInto",
- "description",
"event",
"readAt",
- "createdAt"
+ "createdAt",
+ "digestedInto",
+ "companyId",
+ "topic",
+ "description"
]
},
{
@@ -1658,27 +1658,27 @@
"rows": 0,
"columns": [
"documentId",
- "lastDeliveryId",
"event",
"userId",
- "successCount",
+ "lastDeliveryId",
"id",
"createdAt",
- "lastDeliveredAt",
- "companyId"
+ "successCount",
+ "companyId",
+ "lastDeliveredAt"
]
},
{
"name": "notificationPreference",
"rows": 0,
"columns": [
- "topic",
"updatedAt",
"companyId",
"channel",
+ "topic",
+ "userId",
"enabled",
- "id",
- "userId"
+ "id"
]
},
{
@@ -1740,22 +1740,22 @@
"name": "periodCloseTaskDefinition",
"rows": 0,
"columns": [
- "createdBy",
- "autoCheckKey",
- "updatedAt",
- "taskType",
- "name",
- "updatedBy",
- "required",
- "id",
- "active",
- "defaultAssigneeId",
- "sortOrder",
+ "severity",
+ "isSystem",
"customFields",
"companyId",
"createdAt",
- "severity",
- "isSystem"
+ "sortOrder",
+ "id",
+ "active",
+ "defaultAssigneeId",
+ "required",
+ "taskType",
+ "name",
+ "updatedBy",
+ "updatedAt",
+ "createdBy",
+ "autoCheckKey"
]
},
{
@@ -1763,112 +1763,112 @@
"rows": 0,
"columns": [
"taskType",
- "id",
- "required",
"status",
- "sortOrder",
+ "required",
+ "id",
"severity",
- "evidenceJournalId",
- "companyId",
+ "sortOrder",
"completedBy",
- "notes",
- "skippedReason",
+ "companyId",
+ "evidenceJournalId",
"updatedAt",
- "updatedBy",
- "assigneeId",
+ "skippedReason",
+ "notes",
"name",
+ "assigneeId",
+ "updatedBy",
"autoCheckKey",
- "definitionId",
- "accountingPeriodId",
- "completedAt",
+ "createdAt",
"createdBy",
- "createdAt"
+ "completedAt",
+ "accountingPeriodId",
+ "definitionId"
]
},
{
"name": "pickingList",
"rows": 0,
"columns": [
- "notes",
- "status",
- "locationId",
- "assignee",
- "updatedAt",
"createdAt",
"companyId",
"customFields",
"pickingListId",
"dueDate",
"updatedBy",
+ "id",
"createdBy",
- "id"
+ "notes",
+ "locationId",
+ "status",
+ "assignee",
+ "updatedAt"
]
},
{
"name": "pricingRule",
"rows": 0,
"columns": [
- "active",
- "updatedBy",
- "updatedAt",
- "createdAt",
- "itemPostingGroupId",
- "amount",
- "minQuantity",
- "amountType",
- "ruleType",
- "validTo",
- "companyId",
- "createdBy",
- "priority",
- "id",
- "customerIds",
"itemIds",
- "maxQuantity",
- "customerTypeIds",
+ "customerIds",
+ "id",
+ "priority",
+ "validFrom",
"name",
- "validFrom"
+ "customerTypeIds",
+ "maxQuantity",
+ "amount",
+ "itemPostingGroupId",
+ "createdAt",
+ "updatedAt",
+ "updatedBy",
+ "active",
+ "createdBy",
+ "companyId",
+ "validTo",
+ "ruleType",
+ "amountType",
+ "minQuantity"
]
},
{
"name": "printJob",
- "rows": 0,
- "columns": [
- "printerUrl",
- "origin",
- "id",
- "sourceDocumentReadableId",
- "description",
- "sourceDocumentId",
+ "rows": 0,
+ "columns": [
"attempts",
"companyId",
"updatedAt",
- "createdAt",
- "updatedBy",
- "content",
- "error",
- "sourceDocument",
+ "description",
+ "sourceDocumentId",
+ "origin",
+ "sourceDocumentReadableId",
+ "id",
+ "printerUrl",
"completedAt",
- "contentType",
+ "status",
"createdBy",
- "status"
+ "contentType",
+ "sourceDocument",
+ "content",
+ "error",
+ "createdAt",
+ "updatedBy"
]
},
{
"name": "printerRoute",
"rows": 0,
"columns": [
+ "name",
+ "locationId",
+ "printerUrl",
+ "format",
+ "companyId",
"updatedAt",
"apiKey",
- "companyId",
- "mediaSizeId",
"templateId",
"id",
"createdAt",
- "printerUrl",
- "name",
- "locationId",
- "format"
+ "mediaSizeId"
]
},
{
@@ -1958,42 +1958,27 @@
"key"
]
},
- {
- "name": "project",
- "rows": 0,
- "columns": [
- "active",
- "description",
- "name",
- "createdAt",
- "id",
- "updatedAt",
- "createdBy",
- "companyId",
- "updatedBy"
- ]
- },
{
"name": "purchasingRfq",
"rows": 0,
"columns": [
- "id",
- "notes",
- "assignee",
- "rfqDate",
- "updatedAt",
- "rfqId",
- "customFields",
- "internalNotes",
- "locationId",
- "companyId",
- "employeeId",
- "updatedBy",
"createdBy",
+ "updatedBy",
+ "employeeId",
+ "companyId",
+ "expirationDate",
"status",
"revisionId",
"createdAt",
- "expirationDate"
+ "rfqDate",
+ "assignee",
+ "id",
+ "notes",
+ "locationId",
+ "internalNotes",
+ "customFields",
+ "rfqId",
+ "updatedAt"
]
},
{
@@ -2024,45 +2009,45 @@
"name": "reportPin",
"rows": 0,
"columns": [
- "updatedBy",
"companyId",
"pinned",
+ "updatedBy",
"createdBy",
- "updatedAt",
"userId",
- "createdAt",
- "reportKey"
+ "updatedAt",
+ "reportKey",
+ "createdAt"
]
},
{
"name": "reportView",
"rows": 0,
"columns": [
- "config",
- "reportKey",
- "name",
- "createdBy",
- "updatedBy",
"id",
+ "updatedBy",
"visibility",
"companyId",
+ "updatedAt",
"createdAt",
- "updatedAt"
+ "config",
+ "name",
+ "reportKey",
+ "createdBy"
]
},
{
"name": "returnReason",
"rows": 0,
"columns": [
- "inventoryValueZero",
- "companyId",
- "updatedBy",
- "createdBy",
- "name",
- "updatedAt",
+ "createdAt",
"customFields",
"id",
- "createdAt"
+ "updatedAt",
+ "name",
+ "createdBy",
+ "updatedBy",
+ "inventoryValueZero",
+ "companyId"
]
},
{
@@ -2082,7 +2067,7 @@
{
"name": "searchIndexRegistry",
"rows": 0,
- "columns": ["companyId", "createdAt", "lastRebuiltAt"]
+ "columns": ["lastRebuiltAt", "createdAt", "companyId"]
},
{
"name": "sequence",
@@ -2172,16 +2157,16 @@
"name": "peopleAbsence",
"rows": 0,
"columns": [
- "companyId",
- "updatedAt",
- "createdAt",
- "updatedBy",
- "id",
- "note",
+ "shiftId",
"employeeId",
"date",
"createdBy",
- "shiftId"
+ "updatedBy",
+ "id",
+ "note",
+ "companyId",
+ "createdAt",
+ "updatedAt"
]
},
{
@@ -2238,34 +2223,34 @@
"name": "ssoConnection",
"rows": 0,
"columns": [
- "updatedBy",
- "createdBy",
+ "metadataUrl",
+ "providerId",
+ "requireSso",
+ "metadataXml",
"companyId",
- "active",
- "updatedAt",
+ "createdBy",
+ "updatedBy",
"id",
"createdAt",
- "requireSso",
- "metadataUrl",
- "providerId",
- "metadataXml"
+ "updatedAt",
+ "active"
]
},
{
"name": "ssoDomain",
"rows": 0,
"columns": [
- "verificationToken",
- "connectionId",
- "domain",
"verifiedAt",
- "updatedAt",
- "createdAt",
- "id",
- "status",
- "companyId",
+ "domain",
+ "connectionId",
+ "verificationToken",
+ "createdBy",
"updatedBy",
- "createdBy"
+ "companyId",
+ "status",
+ "id",
+ "createdAt",
+ "updatedAt"
]
},
{
@@ -2306,15 +2291,15 @@
"name": "suggestion",
"rows": 0,
"columns": [
- "userId",
- "emoji",
- "path",
- "attachmentPath",
- "companyId",
"suggestion",
- "tags",
+ "companyId",
+ "id",
"createdAt",
- "id"
+ "tags",
+ "path",
+ "emoji",
+ "userId",
+ "attachmentPath"
]
},
{
@@ -2381,13 +2366,13 @@
"name": "timeCardEntry",
"rows": 0,
"columns": [
- "updatedAt",
"createdAt",
"id",
+ "updatedAt",
"note",
"employeeId",
- "updatedBy",
"createdBy",
+ "updatedBy",
"clockOut",
"companyId",
"clockIn",
@@ -2557,76 +2542,76 @@
"name": "assemblyComponentMapping",
"rows": 0,
"columns": [
- "updatedAt",
- "createdAt",
- "modelUploadId",
- "companyId",
- "updatedBy",
- "id",
- "createdBy",
- "geometryHash",
+ "confidence",
"itemId",
- "confidence"
+ "geometryHash",
+ "createdBy",
+ "id",
+ "updatedBy",
+ "companyId",
+ "modelUploadId",
+ "updatedAt",
+ "createdAt"
]
},
{
"name": "assemblyInstruction",
"rows": 0,
"columns": [
- "status",
- "customFields",
- "settings",
- "id",
"companyId",
"publishedAt",
- "name",
"createdBy",
+ "name",
"updatedAt",
- "rootInstructionId",
- "updatedBy",
- "tags",
- "assemblyPlanJobId",
+ "status",
+ "customFields",
+ "id",
+ "settings",
"version",
- "createdAt",
+ "itemId",
"modelUploadId",
- "itemId"
+ "createdAt",
+ "updatedBy",
+ "rootInstructionId",
+ "assemblyPlanJobId",
+ "tags"
]
},
{
"name": "assemblyInstructionStep",
"rows": 0,
"columns": [
- "companyId",
- "unitOfMeasureCode",
- "instructionText",
- "buildWave",
- "status",
- "listValues",
- "assemblyInstructionId",
- "componentNodeIds",
- "createdBy",
- "type",
- "updatedBy",
- "minValue",
- "id",
- "required",
- "durationSeconds",
- "description",
- "updatedAt",
- "explode",
- "camera",
- "sortOrder",
- "parentStepId",
- "fileTypes",
+ "motion",
+ "createdAt",
"warnings",
"notes",
- "createdAt",
- "motion",
- "title",
- "fastener",
"maxValue",
"rootStepId",
- "planConfidence"
+ "fastener",
+ "title",
+ "planConfidence",
+ "updatedAt",
+ "description",
+ "durationSeconds",
+ "camera",
+ "explode",
+ "fileTypes",
+ "parentStepId",
+ "sortOrder",
+ "createdBy",
+ "type",
+ "minValue",
+ "updatedBy",
+ "required",
+ "id",
+ "unitOfMeasureCode",
+ "companyId",
+ "status",
+ "buildWave",
+ "instructionText",
+ "assemblyInstructionId",
+ "listValues",
+ "componentNodeIds"
]
},
{
@@ -2635,11 +2620,11 @@
"columns": [
"sortOrder",
"createdBy",
- "quantity",
"itemId",
+ "quantity",
"companyId",
- "id",
"updatedBy",
+ "id",
"createdAt",
"updatedAt",
"stepId"
@@ -2649,52 +2634,52 @@
"name": "assemblyInstructionStepSlide",
"rows": 0,
"columns": [
- "createdBy",
- "annotations",
- "stepId",
"updatedAt",
- "sortOrder",
- "createdAt",
+ "stepId",
+ "annotations",
+ "createdBy",
"id",
"companyId",
- "size",
+ "createdAt",
+ "sortOrder",
"modelUploadId",
"imagePath",
- "updatedBy",
- "caption"
+ "size",
+ "caption",
+ "updatedBy"
]
},
{
"name": "assemblyInstructionStepTool",
"rows": 0,
"columns": [
- "sortOrder",
- "quantity",
- "itemId",
"createdBy",
- "id",
- "updatedBy",
- "companyId",
- "stepId",
+ "itemId",
+ "quantity",
+ "sortOrder",
"createdAt",
- "updatedAt"
+ "updatedAt",
+ "stepId",
+ "companyId",
+ "updatedBy",
+ "id"
]
},
{
"name": "assemblyUnit",
"rows": 0,
"columns": [
- "itemId",
- "componentNodeIds",
- "name",
- "createdBy",
+ "companyId",
"id",
"updatedBy",
"sourceGroupId",
- "companyId",
- "modelUploadId",
"createdAt",
- "updatedAt"
+ "updatedAt",
+ "modelUploadId",
+ "itemId",
+ "createdBy",
+ "componentNodeIds",
+ "name"
]
},
{
@@ -2718,16 +2703,16 @@
"name": "changeOrderSupersession",
"rows": 0,
"columns": [
- "changeOrderId",
- "companyId",
"createdBy",
+ "companyId",
+ "changeOrderId",
+ "discontinuationDate",
+ "updatedAt",
"id",
"createdAt",
- "updatedAt",
- "discontinuationDate",
+ "successorEffectivityDate",
"successorItemId",
"predecessorItemId",
- "successorEffectivityDate",
"supersessionMode",
"updatedBy"
]
@@ -2817,111 +2802,111 @@
"name": "enforcementRuleItemAssignment",
"rows": 0,
"columns": [
- "companyId",
"createdBy",
+ "companyId",
"createdAt",
"ruleId",
- "itemId",
- "updatedBy"
+ "updatedBy",
+ "itemId"
]
},
{
"name": "inspectionDocument",
"rows": 0,
"columns": [
- "updatedAt",
- "samplingSeverity",
"samplingSampleSize",
- "version",
- "samplingInspectionLevel",
+ "samplingSeverity",
+ "updatedAt",
"createdBy",
+ "samplingInspectionLevel",
+ "version",
"fileName",
- "drawingNumber",
- "partId",
- "updatedBy",
- "samplingAql",
"samplingPercentage",
+ "samplingAql",
+ "updatedBy",
+ "partId",
+ "drawingNumber",
"storagePath",
- "id",
- "defaultPageWidth",
"uploadedBy",
- "pageCount",
+ "defaultPageWidth",
+ "id",
"defaultPageHeight",
- "samplingPlanType",
+ "pageCount",
+ "companyId",
"createdAt",
- "companyId"
+ "samplingPlanType"
]
},
{
"name": "inspectionFeature",
"rows": 0,
"columns": [
- "inspectionDocumentId",
- "updatedBy",
- "samplingPlanType",
- "unit",
- "tolerancePlus",
- "createdBy",
- "toleranceMinus",
- "id",
- "description",
- "samplingPercentage",
+ "type",
+ "samplingSeverity",
+ "samplingSampleSize",
+ "label",
+ "samplingInspectionLevel",
+ "createdAt",
+ "nominalValue",
"samplingAql",
- "companyId",
- "updatedAt",
+ "samplingPercentage",
"pageNumber",
- "nominalValue",
- "createdAt",
- "samplingInspectionLevel",
- "label",
- "samplingSampleSize",
- "type",
- "samplingSeverity"
+ "updatedAt",
+ "companyId",
+ "description",
+ "createdBy",
+ "id",
+ "toleranceMinus",
+ "unit",
+ "tolerancePlus",
+ "updatedBy",
+ "inspectionDocumentId",
+ "samplingPlanType"
]
},
{
"name": "balloon",
"rows": 0,
"columns": [
- "regionY",
- "updatedBy",
- "companyId",
- "inspectionFeatureId",
- "updatedAt",
- "createdBy",
- "pageNumber",
- "xCoordinate",
+ "regionX",
+ "regionHeight",
+ "id",
+ "yCoordinate",
"regionWidth",
+ "xCoordinate",
"inspectionDocumentId",
"createdAt",
- "regionX",
- "yCoordinate",
- "regionHeight",
- "id"
+ "updatedAt",
+ "createdBy",
+ "pageNumber",
+ "regionY",
+ "updatedBy",
+ "companyId",
+ "inspectionFeatureId"
]
},
{
"name": "inventoryCountLine",
"rows": 0,
"columns": [
- "createdBy",
- "updatedBy",
- "locationId",
+ "id",
+ "systemQuantity",
+ "storageUnitId",
+ "createdAt",
+ "companyId",
+ "countedAt",
+ "readableId",
+ "countedQuantity",
"countedBy",
- "trackedEntityId",
+ "locationId",
+ "updatedBy",
+ "createdBy",
+ "itemId",
"inventoryCountId",
"postedItemLedgerId",
- "itemId",
- "customFields",
"updatedAt",
- "storageUnitId",
- "systemQuantity",
- "id",
- "readableId",
- "countedQuantity",
- "createdAt",
- "countedAt",
- "companyId"
+ "customFields",
+ "trackedEntityId"
]
},
{
@@ -2947,14 +2932,14 @@
"name": "itemInspectionDocumentAssignment",
"rows": 0,
"columns": [
+ "inspectionDocumentId",
+ "companyId",
+ "updatedBy",
+ "createdBy",
"usage",
"updatedAt",
"itemId",
- "createdAt",
- "companyId",
- "inspectionDocumentId",
- "updatedBy",
- "createdBy"
+ "createdAt"
]
},
{
@@ -2988,53 +2973,53 @@
"name": "itemSerialSequence",
"rows": 0,
"columns": [
- "prefix",
- "itemId",
- "size",
"updatedAt",
"suffix",
- "companyId",
- "createdAt",
- "step",
+ "size",
+ "itemId",
+ "prefix",
+ "next",
"updatedBy",
- "id",
"createdBy",
- "next"
+ "id",
+ "createdAt",
+ "step",
+ "companyId"
]
},
{
"name": "itemShelfLife",
"rows": 0,
"columns": [
- "createdAt",
- "updatedAt",
- "mode",
- "companyId",
- "itemId",
+ "triggerTiming",
+ "calculateFromBom",
+ "days",
+ "triggerProcessId",
+ "createdBy",
"updatedBy",
+ "itemId",
"customFields",
- "createdBy",
- "triggerProcessId",
- "days",
- "triggerTiming",
- "calculateFromBom"
+ "companyId",
+ "mode",
+ "createdAt",
+ "updatedAt"
]
},
{
"name": "itemSupersession",
"rows": 0,
"columns": [
- "createdBy",
- "updatedBy",
- "companyId",
"successorEffectivityDate",
- "itemId",
"createdAt",
+ "itemId",
"updatedAt",
+ "createdBy",
+ "updatedBy",
+ "companyId",
+ "discontinuationDate",
"conversionFactor",
- "successorItemId",
"supersessionMode",
- "discontinuationDate"
+ "successorItemId"
]
},
{
@@ -3079,23 +3064,23 @@
"name": "changeOrderAffectedItem",
"rows": 0,
"columns": [
- "newItemId",
- "id",
- "discontinuationDate",
- "draftMakeMethodId",
- "companyId",
+ "itemId",
+ "createdAt",
+ "sortOrder",
+ "baseMakeMethodId",
+ "changeSummary",
+ "changeType",
+ "updatedBy",
+ "createdBy",
"changeOrderId",
+ "companyId",
"updatedAt",
"successorEffectivityDate",
"supersessionMode",
- "changeType",
- "changeSummary",
- "createdBy",
- "updatedBy",
- "sortOrder",
- "itemId",
- "createdAt",
- "baseMakeMethodId"
+ "newItemId",
+ "discontinuationDate",
+ "id",
+ "draftMakeMethodId"
]
},
{
@@ -3140,24 +3125,24 @@
{
"name": "purchasingRfqLine",
"rows": 0,
- "columns": [
- "purchasingRfqId",
- "customFields",
- "updatedAt",
- "internalNotes",
- "conversionFactor",
- "externalNotes",
+ "columns": [
"order",
"id",
+ "externalNotes",
"purchaseUnitOfMeasureCode",
- "createdAt",
- "itemId",
- "description",
- "inventoryUnitOfMeasureCode",
+ "updatedAt",
+ "purchasingRfqId",
+ "customFields",
+ "conversionFactor",
+ "internalNotes",
"companyId",
"quantity",
"updatedBy",
- "createdBy"
+ "createdBy",
+ "createdAt",
+ "itemId",
+ "description",
+ "inventoryUnitOfMeasureCode"
]
},
{
@@ -3230,16 +3215,16 @@
"name": "nonConformanceItemTrackedEntity",
"rows": 0,
"columns": [
- "quantity",
- "createdAt",
- "trackedEntityId",
- "nonConformanceId",
"companyId",
- "id",
"updatedAt",
+ "id",
"updatedBy",
"createdBy",
- "nonConformanceItemId"
+ "nonConformanceItemId",
+ "quantity",
+ "createdAt",
+ "nonConformanceId",
+ "trackedEntityId"
]
},
{
@@ -3340,13 +3325,13 @@
"name": "userModulePreference",
"rows": 0,
"columns": [
- "companyId",
- "module",
- "updatedAt",
- "position",
- "userId",
"id",
- "hidden"
+ "hidden",
+ "userId",
+ "position",
+ "module",
+ "companyId",
+ "updatedAt"
]
},
{
@@ -3427,96 +3412,98 @@
"name": "enforcementRuleWorkCenterAssignment",
"rows": 0,
"columns": [
+ "createdBy",
+ "companyId",
+ "createdAt",
"ruleId",
"updatedBy",
- "workCenterId",
- "companyId",
- "createdBy",
- "createdAt"
+ "workCenterId"
]
},
{
"name": "jobOperationBatch",
"rows": 0,
"columns": [
- "workCenterId",
- "updatedBy",
- "companyId",
- "processId",
- "status",
- "createdAt",
- "customFields",
- "id",
- "locationId",
"updatedAt",
"readableId",
"createdBy",
- "notes"
+ "notes",
+ "createdAt",
+ "id",
+ "customFields",
+ "locationId",
+ "processId",
+ "mergeOutput",
+ "companyId",
+ "status",
+ "workCenterId",
+ "updatedBy",
+ "outputLotNumber"
]
},
{
"name": "maintenanceSchedule",
"rows": 0,
"columns": [
- "skipHolidays",
- "estimatedDuration",
- "workCenterId",
- "description",
"updatedBy",
- "wednesday",
+ "description",
+ "workCenterId",
"thursday",
- "takesWorkCenterOffline",
- "tuesday",
- "saturday",
- "updatedAt",
+ "wednesday",
+ "estimatedDuration",
+ "skipHolidays",
"sunday",
- "friday",
- "createdBy",
"frequency",
- "active",
- "nextDueAt",
- "locationId",
+ "createdBy",
+ "friday",
+ "saturday",
+ "updatedAt",
+ "tuesday",
+ "takesWorkCenterOffline",
"monday",
- "name",
"createdAt",
- "priority",
- "procedureId",
- "id",
+ "name",
+ "active",
+ "locationId",
+ "nextDueAt",
"lastGeneratedAt",
- "companyId"
+ "id",
+ "companyId",
+ "priority",
+ "procedureId"
]
},
{
"name": "maintenanceDispatch",
"rows": 0,
"columns": [
- "locationId",
- "updatedBy",
- "completedAt",
"assignee",
- "actualStartTime",
- "content",
+ "completedAt",
"status",
- "nonConformanceId",
- "actualEndTime",
- "createdBy",
- "plannedStartTime",
- "companyId",
+ "content",
+ "actualStartTime",
+ "updatedBy",
+ "locationId",
"priority",
+ "companyId",
+ "plannedStartTime",
"createdAt",
- "suspectedFailureModeId",
+ "actualEndTime",
+ "createdBy",
+ "nonConformanceId",
+ "plannedEndTime",
+ "maintenanceDispatchId",
"updatedAt",
- "procedureId",
- "takesWorkCenterOffline",
+ "suspectedFailureModeId",
"workCenterId",
- "maintenanceDispatchId",
- "plannedEndTime",
- "oeeImpact",
- "source",
- "actualFailureModeId",
+ "takesWorkCenterOffline",
+ "procedureId",
"severity",
+ "actualFailureModeId",
+ "id",
"maintenanceScheduleId",
- "id"
+ "oeeImpact",
+ "source"
]
},
{
@@ -3524,8 +3511,8 @@
"rows": 0,
"columns": [
"updatedBy",
- "companyId",
"comment",
+ "companyId",
"createdBy",
"updatedAt",
"maintenanceDispatchId",
@@ -3537,18 +3524,18 @@
"name": "maintenanceDispatchEvent",
"rows": 0,
"columns": [
- "startTime",
- "updatedBy",
- "notes",
- "workCenterId",
- "employeeId",
- "endTime",
- "id",
- "companyId",
- "createdAt",
"createdBy",
"updatedAt",
- "maintenanceDispatchId"
+ "maintenanceDispatchId",
+ "endTime",
+ "createdAt",
+ "companyId",
+ "id",
+ "notes",
+ "employeeId",
+ "workCenterId",
+ "startTime",
+ "updatedBy"
]
},
{
@@ -3556,81 +3543,81 @@
"rows": 0,
"columns": [
"updatedBy",
- "createdBy",
"id",
+ "createdBy",
"unitCost",
"maintenanceDispatchId",
"createdAt",
"companyId",
- "unitOfMeasureCode",
"updatedAt",
- "itemId",
- "quantity"
+ "unitOfMeasureCode",
+ "quantity",
+ "itemId"
]
},
{
"name": "maintenanceDispatchItemTrackedEntity",
"rows": 0,
"columns": [
- "createdBy",
- "id",
- "updatedAt",
- "updatedBy",
- "maintenanceDispatchItemId",
"companyId",
- "createdAt",
+ "trackedEntityId",
"quantity",
- "trackedEntityId"
+ "createdAt",
+ "updatedAt",
+ "id",
+ "createdBy",
+ "maintenanceDispatchItemId",
+ "updatedBy"
]
},
{
"name": "maintenanceDispatchWorkCenter",
"rows": 0,
"columns": [
+ "companyId",
+ "workCenterId",
+ "updatedBy",
+ "createdBy",
"maintenanceDispatchId",
"updatedAt",
"id",
- "createdAt",
- "workCenterId",
- "companyId",
- "updatedBy",
- "createdBy"
+ "createdAt"
]
},
{
"name": "maintenanceScheduleItem",
"rows": 0,
"columns": [
- "itemId",
- "quantity",
- "createdBy",
- "unitOfMeasureCode",
"maintenanceScheduleId",
"createdAt",
"updatedAt",
"updatedBy",
"id",
- "companyId"
+ "companyId",
+ "itemId",
+ "quantity",
+ "createdBy",
+ "unitOfMeasureCode"
]
},
{
"name": "peopleAssignment",
"rows": 0,
"columns": [
- "overtimeHours",
- "companyId",
+ "shiftId",
+ "workCenterId",
+ "hours",
+ "locationId",
+ "updatedAt",
+ "employeeId",
"note",
"createdAt",
- "createdBy",
- "id",
- "updatedBy",
+ "companyId",
+ "overtimeHours",
"date",
- "locationId",
- "hours",
- "workCenterId",
- "shiftId",
- "employeeId",
- "updatedAt"
+ "id",
+ "createdBy",
+ "updatedBy"
]
},
{
@@ -3739,84 +3726,30 @@
"name": "workCenterReplacementPart",
"rows": 0,
"columns": [
- "companyId",
- "updatedBy",
- "id",
- "updatedAt",
- "createdAt",
- "workCenterId",
"unitOfMeasureCode",
- "createdBy",
"itemId",
- "quantity"
- ]
- },
- {
- "name": "workCenterShift",
- "rows": 0,
- "columns": [
- "createdBy",
- "shiftId",
- "workCenterId",
- "updatedBy",
- "id",
- "createdAt",
- "companyId",
- "updatedAt"
- ]
- },
- {
- "name": "cardTransaction",
- "rows": 0,
- "columns": [
- "exchangeRate",
- "voidedBy",
- "updatedAt",
- "journalId",
- "integration",
- "voidedAt",
- "transactionDate",
- "companyId",
+ "quantity",
"createdBy",
- "offsetAccountId",
- "supplierId",
- "postedBy",
- "postedAt",
- "status",
- "type",
- "currencyCode",
"updatedBy",
- "cardAccountId",
- "customFields",
- "memo",
"id",
- "cardHolderName",
+ "companyId",
+ "workCenterId",
"createdAt",
- "cardLast4",
- "merchantName",
- "postingDate",
- "cardTransactionId",
- "amount"
+ "updatedAt"
]
},
{
- "name": "cardTransactionLine",
+ "name": "workCenterShift",
"rows": 0,
"columns": [
- "updatedAt",
- "costCenterId",
- "amount",
- "accountId",
- "companyId",
- "projectId",
- "description",
- "id",
"createdBy",
+ "shiftId",
+ "workCenterId",
"updatedBy",
- "sequence",
+ "id",
"createdAt",
- "cardTransactionId",
- "customFields"
+ "companyId",
+ "updatedAt"
]
},
{
@@ -3910,63 +3843,63 @@
"name": "customerBankAccount",
"rows": 0,
"columns": [
- "createdBy",
- "companyId",
- "isPrimary",
- "countryCode",
- "accountNumber",
+ "bankName",
+ "bankCode",
"currencyCode",
"id",
- "bankCode",
- "bankName",
- "customerId",
- "active",
- "name",
- "updatedBy",
- "updatedAt",
- "bankAddress",
+ "accountNumber",
+ "countryCode",
+ "companyId",
+ "isPrimary",
+ "createdBy",
+ "createdAt",
+ "notes",
+ "tags",
"swiftBic",
"customFields",
"accountHolderName",
- "createdAt",
- "notes",
- "tags"
+ "bankAddress",
+ "updatedBy",
+ "updatedAt",
+ "active",
+ "customerId",
+ "name"
]
},
{
"name": "customerItemPriceOverride",
"rows": 0,
"columns": [
+ "validTo",
+ "itemId",
"updatedAt",
"customerTypeId",
- "itemId",
- "validTo",
- "createdAt",
"notes",
- "customerId",
- "updatedBy",
+ "createdAt",
"companyId",
"active",
+ "updatedBy",
+ "customerId",
+ "validFrom",
"createdBy",
- "applyRulesOnTop",
"id",
- "validFrom"
+ "applyRulesOnTop"
]
},
{
"name": "customerItemPriceOverrideBreak",
"rows": 0,
"columns": [
- "active",
- "quantity",
- "overridePrice",
- "createdBy",
- "updatedBy",
- "id",
"companyId",
- "customerItemPriceOverrideId",
+ "id",
+ "updatedBy",
"createdAt",
- "updatedAt"
+ "updatedAt",
+ "customerItemPriceOverrideId",
+ "active",
+ "createdBy",
+ "overridePrice",
+ "quantity"
]
},
{
@@ -4043,17 +3976,17 @@
"name": "customerTax",
"rows": 0,
"columns": [
- "taxExemptionCertificateNumber",
- "eori",
"vatNumber",
+ "eori",
+ "taxExemptionCertificateNumber",
"taxExempt",
+ "taxId",
"taxExemptionCertificatePath",
"updatedAt",
- "taxId",
- "taxExemptionReason",
- "customerId",
"companyId",
- "updatedBy"
+ "customerId",
+ "updatedBy",
+ "taxExemptionReason"
]
},
{
@@ -4272,29 +4205,29 @@
"name": "salesReturnOrder",
"rows": 0,
"columns": [
- "customerLocationId",
- "createdAt",
- "exchangeRate",
- "updatedAt",
- "updatedBy",
- "internalNotes",
- "assignee",
- "createdBy",
- "companyId",
+ "externalNotes",
+ "salesReturnOrderId",
+ "orderDate",
+ "locationId",
+ "replacementSalesOrderId",
+ "id",
+ "salesOrderId",
+ "currencyCode",
+ "customerContactId",
"customerId",
"expirationDate",
"status",
+ "companyId",
+ "createdBy",
"customFields",
"customerReference",
- "currencyCode",
- "id",
- "salesOrderId",
- "customerContactId",
- "orderDate",
- "salesReturnOrderId",
- "externalNotes",
- "replacementSalesOrderId",
- "locationId"
+ "updatedAt",
+ "createdAt",
+ "exchangeRate",
+ "customerLocationId",
+ "assignee",
+ "internalNotes",
+ "updatedBy"
]
},
{
@@ -4578,24 +4511,24 @@
"name": "capacityReservation",
"rows": 0,
"columns": [
- "operationId",
- "updatedBy",
- "scheduleNote",
- "isPlaceholder",
+ "updatedAt",
+ "companyId",
+ "workHours",
+ "createdBy",
+ "endAt",
+ "createdAt",
+ "scenarioId",
+ "id",
+ "jobId",
"jobOperationBatchId",
"earliestStartAt",
"resourceKind",
"resourceId",
"startAt",
- "createdAt",
- "scenarioId",
- "id",
- "jobId",
- "updatedAt",
- "companyId",
- "workHours",
- "createdBy",
- "endAt"
+ "operationId",
+ "updatedBy",
+ "scheduleNote",
+ "isPlaceholder"
]
},
{
@@ -4657,104 +4590,104 @@
"name": "inspection",
"rows": 0,
"columns": [
- "createdAt",
- "supplierId",
- "sourceDocument",
- "notes",
- "status",
- "aql",
- "dispositionedAt",
- "inspectionLevel",
- "updatedBy",
- "codeLetter",
- "itemId",
- "dispositionedBy",
- "acceptanceNumber",
- "sourceDocumentReadableId",
- "companyId",
- "createdBy",
+ "updatedAt",
+ "itemReadableId",
+ "sampleSize",
+ "inspectionDocumentId",
+ "samplingStandard",
+ "id",
"samplingPlanType",
+ "createdBy",
+ "sourceDocumentId",
"lotSize",
"sourceDocumentLineId",
- "sourceDocumentId",
- "rejectionNumber",
"inspectionId",
+ "rejectionNumber",
"severity",
- "updatedAt",
- "itemReadableId",
- "inspectionDocumentId",
- "sampleSize",
- "id",
- "samplingStandard"
+ "codeLetter",
+ "updatedBy",
+ "inspectionLevel",
+ "dispositionedAt",
+ "sourceDocumentReadableId",
+ "acceptanceNumber",
+ "dispositionedBy",
+ "itemId",
+ "companyId",
+ "sourceDocument",
+ "supplierId",
+ "createdAt",
+ "status",
+ "notes",
+ "aql"
]
},
{
"name": "inspectionSample",
"rows": 0,
"columns": [
- "createdBy",
- "companyId",
- "inspectionId",
+ "notes",
+ "updatedBy",
+ "inspectedAt",
+ "status",
+ "trackedEntityId",
"inspectedBy",
"updatedAt",
- "createdAt",
"id",
- "inspectedAt",
- "trackedEntityId",
- "status",
- "notes",
- "updatedBy"
+ "createdAt",
+ "createdBy",
+ "companyId",
+ "inspectionId"
]
},
{
"name": "inspectionMeasurement",
"rows": 0,
"columns": [
- "updatedBy",
- "inspectionId",
- "companyId",
- "inspectedBy",
+ "createdAt",
+ "value",
+ "inspectionFeatureId",
+ "inspectionSampleId",
+ "updatedAt",
+ "notes",
"createdBy",
"id",
"inspectedAt",
"status",
- "inspectionFeatureId",
- "updatedAt",
- "inspectionSampleId",
- "notes",
- "value",
- "createdAt"
+ "inspectionId",
+ "updatedBy",
+ "companyId",
+ "inspectedBy"
]
},
{
"name": "inspectionSamplingPlan",
"rows": 0,
"columns": [
+ "companyId",
+ "createdAt",
+ "inspectionId",
"rejectionNumber",
- "updatedBy",
"createdBy",
"id",
- "createdAt",
- "companyId",
- "inspectionId",
- "updatedAt",
- "acceptanceNumber",
+ "updatedBy",
"codeLetter",
"inspectionFeatureId",
- "sampleSize"
+ "sampleSize",
+ "acceptanceNumber",
+ "updatedAt"
]
},
{
"name": "nonConformanceInspection",
"rows": 0,
- "columns": [
- "companyId",
- "inspectionId",
- "updatedBy",
- "createdAt",
- "nonConformanceId",
+ "columns": [
+ "createdBy",
"id",
- "createdBy"
+ "nonConformanceId",
+ "createdAt",
+ "updatedBy",
+ "companyId",
+ "inspectionId"
]
},
{
@@ -4762,8 +4695,8 @@
"rows": 0,
"columns": [
"severity",
- "lotSize",
"id",
+ "lotSize",
"defectsFound",
"aql",
"sampleSize",
@@ -4774,9 +4707,9 @@
"samplingStandard",
"outcome",
"inspectionLevel",
- "itemId",
+ "supplierId",
"createdAt",
- "supplierId"
+ "itemId"
]
},
{
@@ -4885,7 +4818,7 @@
{
"name": "jobMaterialStep",
"rows": 0,
- "columns": ["quantity", "jobOperationStepId", "jobMaterialId"]
+ "columns": ["quantity", "jobMaterialId", "jobOperationStepId"]
},
{
"name": "jobOperation",
@@ -5004,35 +4937,35 @@
"name": "pickingListLine",
"rows": 0,
"columns": [
- "customFields",
+ "jobOperationId",
+ "status",
+ "createdAt",
+ "updatedAt",
"quantityReturned",
- "createdBy",
+ "customFields",
"jobId",
+ "createdBy",
"jobMaterialId",
"quantityToPick",
- "status",
- "jobOperationId",
- "updatedAt",
- "createdAt",
- "pickingListId",
+ "toStorageUnitId",
+ "id",
+ "itemId",
"companyId",
+ "pickingListId",
"updatedBy",
"storageUnitId",
- "quantityPicked",
- "toStorageUnitId",
- "id",
- "itemId"
+ "quantityPicked"
]
},
{
"name": "pickingListLineTrackedEntity",
"rows": 0,
"columns": [
- "quantityPicked",
- "quantity",
- "companyId",
+ "pickingListLineId",
"trackedEntityId",
- "pickingListLineId"
+ "companyId",
+ "quantityPicked",
+ "quantity"
]
},
{
@@ -5099,15 +5032,15 @@
"columns": [
"targetJobOperationId",
"triggeredAtJobOperationId",
- "reason",
"updatedAt",
- "requestedById",
+ "reason",
"companyId",
+ "requestedById",
"jobId",
"quantity",
+ "createdAt",
"id",
- "completedAt",
- "createdAt"
+ "completedAt"
]
},
{
@@ -5158,19 +5091,19 @@
"name": "jobOperationStepSlide",
"rows": 0,
"columns": [
- "createdBy",
- "imagePath",
"caption",
- "annotations",
+ "imagePath",
+ "createdBy",
"sortOrder",
+ "annotations",
+ "modelUploadId",
+ "stepId",
"updatedAt",
"createdAt",
- "stepId",
- "modelUploadId",
- "companyId",
"size",
+ "id",
"updatedBy",
- "id"
+ "companyId"
]
},
{
@@ -5316,12 +5249,12 @@
"createdBy",
"imagePath",
"caption",
- "sortOrder",
"annotations",
+ "sortOrder",
"updatedAt",
"createdAt",
- "modelUploadId",
"stepId",
+ "modelUploadId",
"companyId",
"size",
"updatedBy",
@@ -5388,33 +5321,33 @@
"name": "nonConformancePurchaseReturnOrderLine",
"rows": 0,
"columns": [
- "purchaseReturnOrderReadableId",
- "companyId",
- "purchaseReturnOrderLineId",
- "purchaseReturnOrderId",
- "quantity",
- "updatedBy",
- "createdBy",
"id",
- "updatedAt",
+ "createdBy",
+ "updatedBy",
+ "quantity",
+ "nonConformanceId",
"createdAt",
- "nonConformanceId"
+ "updatedAt",
+ "purchaseReturnOrderReadableId",
+ "purchaseReturnOrderId",
+ "purchaseReturnOrderLineId",
+ "companyId"
]
},
{
"name": "nonConformanceSalesReturnOrderLine",
"rows": 0,
"columns": [
- "companyId",
"id",
"updatedAt",
+ "companyId",
+ "nonConformanceId",
"updatedBy",
"createdBy",
- "nonConformanceId",
"salesReturnOrderReadableId",
- "createdAt",
"salesReturnOrderId",
- "salesReturnOrderLineId"
+ "salesReturnOrderLineId",
+ "createdAt"
]
},
{
@@ -5453,20 +5386,6 @@
"name": "payment",
"rows": 0,
"columns": [
- "updatedBy",
- "paymentDate",
- "status",
- "paymentType",
- "memo",
- "voidedAt",
- "voidedBy",
- "postedBy",
- "journalId",
- "createdBy",
- "createdAt",
- "companyId",
- "bankAccount",
- "customerId",
"postingDate",
"exchangeRate",
"updatedAt",
@@ -5475,9 +5394,23 @@
"reference",
"supplierId",
"customFields",
- "id",
"currencyCode",
- "totalAmount"
+ "id",
+ "totalAmount",
+ "paymentDate",
+ "updatedBy",
+ "memo",
+ "paymentType",
+ "status",
+ "voidedAt",
+ "voidedBy",
+ "postedBy",
+ "journalId",
+ "createdBy",
+ "createdAt",
+ "bankAccount",
+ "companyId",
+ "customerId"
]
},
{
@@ -5627,38 +5560,38 @@
"name": "purchaseReturnOrderLineTrackedEntity",
"rows": 0,
"columns": [
- "createdBy",
- "updatedBy",
- "companyId",
- "quantity",
"createdAt",
"purchaseReturnOrderLineId",
"updatedAt",
- "trackedEntityId"
+ "trackedEntityId",
+ "createdBy",
+ "updatedBy",
+ "quantity",
+ "companyId"
]
},
{
"name": "purchasingRfqSupplier",
"rows": 0,
"columns": [
- "createdBy",
- "id",
- "purchasingRfqId",
"createdAt",
"updatedBy",
+ "companyId",
"supplierId",
- "companyId"
+ "createdBy",
+ "id",
+ "purchasingRfqId"
]
},
{
"name": "purchasingRfqToPurchaseOrder",
"rows": 0,
- "columns": ["purchaseOrderId", "purchasingRfqId", "companyId"]
+ "columns": ["purchasingRfqId", "purchaseOrderId", "companyId"]
},
{
"name": "purchasingRfqToSupplierQuote",
"rows": 0,
- "columns": ["companyId", "supplierQuoteId", "purchasingRfqId"]
+ "columns": ["purchasingRfqId", "supplierQuoteId", "companyId"]
},
{
"name": "quoteMakeMethod",
@@ -5713,7 +5646,7 @@
{
"name": "quoteMaterialStep",
"rows": 0,
- "columns": ["quoteOperationStepId", "quoteMaterialId", "quantity"]
+ "columns": ["quoteMaterialId", "quoteOperationStepId", "quantity"]
},
{
"name": "quoteOperation",
@@ -5797,19 +5730,19 @@
"name": "quoteOperationStepSlide",
"rows": 0,
"columns": [
- "modelUploadId",
- "stepId",
- "createdAt",
- "updatedAt",
- "updatedBy",
- "id",
- "size",
- "companyId",
- "imagePath",
- "caption",
"createdBy",
+ "caption",
+ "imagePath",
+ "annotations",
"sortOrder",
- "annotations"
+ "updatedAt",
+ "createdAt",
+ "stepId",
+ "modelUploadId",
+ "companyId",
+ "size",
+ "id",
+ "updatedBy"
]
},
{
@@ -5836,16 +5769,16 @@
"name": "receiptFixedAssetLine",
"rows": 0,
"columns": [
- "serialNumber",
- "createdBy",
- "purchaseOrderLineId",
- "received",
"companyId",
- "updatedAt",
"id",
+ "updatedAt",
"createdAt",
"updatedBy",
- "receiptId"
+ "receiptId",
+ "serialNumber",
+ "createdBy",
+ "received",
+ "purchaseOrderLineId"
]
},
{
@@ -5989,74 +5922,74 @@
"name": "salesReturnOrderLine",
"rows": 0,
"columns": [
- "id",
- "restockFeePercent",
- "salesOrderLineId",
- "quantityReceived",
- "companyId",
- "salesInvoiceLineId",
- "salesReturnOrderId",
- "unitPrice",
- "returnReasonId",
- "quantity",
- "updatedAt",
- "shipmentLineId",
- "customFields",
- "closedComplete",
- "createdBy",
+ "unitOfMeasureCode",
+ "createdAt",
+ "updatedBy",
"itemId",
"disposition",
"lineNumber",
- "updatedBy",
- "createdAt",
- "unitOfMeasureCode"
+ "createdBy",
+ "customFields",
+ "closedComplete",
+ "updatedAt",
+ "shipmentLineId",
+ "quantity",
+ "returnReasonId",
+ "unitPrice",
+ "salesReturnOrderId",
+ "salesInvoiceLineId",
+ "companyId",
+ "quantityReceived",
+ "salesOrderLineId",
+ "id",
+ "restockFeePercent"
]
},
{
"name": "salesReturnOrderLineTrackedEntity",
"rows": 0,
"columns": [
+ "quantity",
+ "companyId",
+ "updatedBy",
+ "createdBy",
"trackedEntityId",
"updatedAt",
"salesReturnOrderLineId",
- "createdAt",
- "companyId",
- "quantity",
- "updatedBy",
- "createdBy"
+ "createdAt"
]
},
{
"name": "salesReturnOrderCreditLine",
"rows": 0,
"columns": [
- "restockFee",
+ "unitPrice",
+ "salesReturnOrderLineId",
+ "quantity",
+ "companyId",
"updatedAt",
"createdAt",
"id",
- "updatedBy",
- "createdBy",
+ "restockFee",
"memoId",
- "unitPrice",
- "companyId",
- "salesReturnOrderLineId",
- "quantity"
+ "updatedBy",
+ "createdBy"
]
},
{
"name": "shipmentFixedAssetLine",
"rows": 0,
"columns": [
- "serialNumber",
"createdBy",
- "shipped",
"salesOrderLineId",
+ "shipped",
+ "serialNumber",
+ "updatedBy",
+ "createdAt",
+ "shipmentId",
"companyId",
- "id",
"updatedAt",
- "createdAt",
- "updatedBy",
- "shipmentId"
+ "id"
]
},
{
@@ -6139,27 +6072,27 @@
"name": "supplierBankAccount",
"rows": 0,
"columns": [
- "updatedAt",
- "updatedBy",
- "supplierId",
- "active",
- "name",
- "bankAddress",
- "accountHolderName",
- "swiftBic",
"customFields",
+ "swiftBic",
+ "accountHolderName",
+ "createdAt",
"tags",
"notes",
- "createdAt",
- "isPrimary",
- "companyId",
+ "name",
+ "active",
+ "supplierId",
+ "updatedBy",
+ "updatedAt",
+ "bankAddress",
+ "id",
+ "currencyCode",
+ "bankCode",
+ "bankName",
"createdBy",
- "accountNumber",
+ "companyId",
+ "isPrimary",
"countryCode",
- "bankCode",
- "currencyCode",
- "id",
- "bankName"
+ "accountNumber"
]
},
{
@@ -6370,7 +6303,6 @@
"companyId",
"requiredDate",
"invoiceId",
- "projectId",
"description",
"internalNotes",
"serviceId",
@@ -6420,131 +6352,131 @@
"name": "purchaseReturnOrder",
"rows": 0,
"columns": [
- "replacementPurchaseOrderId",
- "locationId",
"orderDate",
"purchaseReturnOrderId",
"externalNotes",
- "supplierContactId",
+ "replacementPurchaseOrderId",
+ "locationId",
"currencyCode",
"id",
"purchaseOrderId",
- "customFields",
- "supplierReference",
+ "supplierContactId",
"createdBy",
"companyId",
"supplierId",
"expirationDate",
"status",
- "updatedBy",
- "internalNotes",
- "assignee",
+ "customFields",
+ "supplierReference",
"supplierLocationId",
"createdAt",
"exchangeRate",
- "updatedAt"
+ "updatedAt",
+ "internalNotes",
+ "updatedBy",
+ "assignee"
]
},
{
"name": "memo",
"rows": 0,
"columns": [
- "postedAt",
- "memoId",
- "reference",
- "postingDate",
- "exchangeRate",
- "updatedAt",
- "currencyCode",
- "id",
- "amount",
- "purchaseReturnOrderId",
- "supplierId",
- "customFields",
+ "voidedBy",
+ "voidedAt",
+ "status",
"notes",
"direction",
- "status",
- "voidedAt",
- "voidedBy",
- "memoDate",
"updatedBy",
- "createdAt",
- "reasonAccount",
- "companyId",
+ "memoDate",
"customerId",
- "postedBy",
- "salesReturnOrderId",
+ "companyId",
+ "reasonAccount",
+ "createdAt",
+ "journalId",
"createdBy",
- "journalId"
+ "salesReturnOrderId",
+ "postedBy",
+ "reference",
+ "memoId",
+ "postedAt",
+ "updatedAt",
+ "exchangeRate",
+ "postingDate",
+ "purchaseReturnOrderId",
+ "amount",
+ "id",
+ "currencyCode",
+ "customFields",
+ "supplierId"
]
},
{
"name": "invoiceSettlement",
"rows": 0,
"columns": [
- "targetExchangeRate",
- "writeOffAmount",
- "id",
- "targetMemoId",
- "paymentId",
- "appliedDate",
- "createdAt",
- "sourceExchangeRate",
"discountAmount",
- "fxGainLossAmount",
- "sourceAmount",
- "targetPurchaseInvoiceId",
- "appliedViaPaymentId",
- "createdBy",
- "updatedBy",
- "sourcePaymentId",
- "memoId",
- "companyId",
+ "sourceExchangeRate",
+ "createdAt",
+ "appliedDate",
+ "paymentId",
+ "targetMemoId",
+ "id",
+ "writeOffAmount",
+ "targetExchangeRate",
+ "appliedAmount",
"targetSalesInvoiceId",
- "appliedAmount"
+ "companyId",
+ "memoId",
+ "sourcePaymentId",
+ "updatedBy",
+ "createdBy",
+ "appliedViaPaymentId",
+ "targetPurchaseInvoiceId",
+ "sourceAmount",
+ "fxGainLossAmount"
]
},
{
"name": "purchaseReturnOrderLine",
"rows": 0,
"columns": [
- "quantity",
- "receiptLineId",
- "customFields",
- "companyId",
- "createdAt",
+ "returnReasonId",
+ "unitPrice",
+ "purchaseInvoiceLineId",
+ "purchaseReturnOrderId",
+ "createdBy",
+ "quantityShipped",
+ "purchaseOrderLineId",
+ "restockFeePercent",
+ "id",
+ "unitOfMeasureCode",
+ "updatedAt",
+ "updatedBy",
"closedComplete",
"lineNumber",
"itemId",
- "updatedAt",
- "updatedBy",
- "unitOfMeasureCode",
- "restockFeePercent",
- "id",
- "purchaseOrderLineId",
- "quantityShipped",
- "createdBy",
- "purchaseInvoiceLineId",
- "purchaseReturnOrderId",
- "unitPrice",
- "returnReasonId"
+ "companyId",
+ "createdAt",
+ "quantity",
+ "receiptLineId",
+ "customFields"
]
},
{
"name": "purchaseReturnOrderCreditLine",
"rows": 0,
"columns": [
- "updatedBy",
- "createdBy",
- "memoId",
+ "unitPrice",
+ "companyId",
+ "purchaseReturnOrderLineId",
+ "quantity",
"restockFee",
"updatedAt",
"createdAt",
"id",
- "companyId",
- "purchaseReturnOrderLineId",
- "quantity",
- "unitPrice"
+ "updatedBy",
+ "createdBy",
+ "memoId"
]
},
{
@@ -6574,17 +6506,17 @@
"name": "supplierPartPrice",
"rows": 0,
"columns": [
+ "sourceDocumentId",
+ "createdBy",
+ "sourceType",
+ "unitPrice",
"companyId",
+ "leadTime",
"supplierPartId",
"updatedBy",
- "leadTime",
- "createdAt",
"updatedAt",
- "quantity",
- "sourceDocumentId",
- "createdBy",
- "sourceType",
- "unitPrice"
+ "createdAt",
+ "quantity"
]
},
{
@@ -6732,17 +6664,17 @@
"name": "supplierTax",
"rows": 0,
"columns": [
- "taxExemptionCertificateNumber",
- "eori",
- "vatNumber",
- "taxExempt",
- "updatedAt",
- "taxExemptionCertificatePath",
- "taxId",
"taxExemptionReason",
"updatedBy",
"supplierId",
- "companyId"
+ "companyId",
+ "updatedAt",
+ "taxExemptionCertificatePath",
+ "taxId",
+ "taxExempt",
+ "taxExemptionCertificateNumber",
+ "eori",
+ "vatNumber"
]
},
{
@@ -6751,11 +6683,11 @@
"columns": [
"companyId",
"updatedAt",
- "createdBy",
"nextRunAt",
- "createdAt",
+ "createdBy",
"canvasState",
"id",
+ "createdAt",
"name",
"description",
"publishedVersionId",
@@ -6767,83 +6699,83 @@
"name": "workflowVersion",
"rows": 0,
"columns": [
- "versionNumber",
- "workflowId",
- "edges",
"formatVersion",
- "companyId",
- "updatedBy",
- "createdBy",
+ "edges",
+ "workflowId",
+ "versionNumber",
+ "nodes",
"updatedAt",
- "id",
"createdAt",
- "nodes"
+ "id",
+ "updatedBy",
+ "createdBy",
+ "companyId"
]
},
{
"name": "workflowRun",
"rows": 0,
"columns": [
- "status",
- "triggerRecordId",
- "rootRunId",
- "companyId",
- "path",
- "sourceEventId",
- "statusReason",
- "id",
- "ownerId",
- "triggerTable",
- "durationMs",
- "completedAt",
"workflowVersionId",
"workflowId",
"causedByRunId",
- "depth",
- "compactedAt",
- "startedAt",
- "eventId",
+ "completedAt",
+ "durationMs",
+ "triggerTable",
+ "createdAt",
"error",
"isTest",
- "createdAt"
+ "eventId",
+ "startedAt",
+ "depth",
+ "compactedAt",
+ "path",
+ "companyId",
+ "rootRunId",
+ "triggerRecordId",
+ "status",
+ "id",
+ "ownerId",
+ "statusReason",
+ "sourceEventId"
]
},
{
"name": "workflowStepRun",
"rows": 0,
"columns": [
- "compactedAt",
- "durationMs",
- "branchTaken",
- "nodeId",
- "itemKey",
"completedAt",
"runId",
"sequence",
"createdAt",
"detail",
- "nodeType",
+ "itemKey",
+ "branchTaken",
+ "nodeId",
+ "compactedAt",
+ "durationMs",
+ "error",
+ "companyId",
+ "startedAt",
+ "status",
+ "input",
"statusReason",
"id",
"output",
- "status",
- "input",
- "error",
- "companyId",
- "startedAt"
+ "nodeType"
]
},
{
"name": "workflowTriggerEvent",
"rows": 0,
"columns": [
+ "id",
+ "origin",
+ "companyId",
"eventId",
- "createdAt",
- "workflowVersionId",
"workflowId",
- "origin",
- "id",
- "companyId"
+ "workflowVersionId",
+ "createdAt"
]
}
],
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index c25532cf3c..d592c4e1a5 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -111,6 +111,10 @@ msgstr "{0} erfolgreich gelöscht"
msgid "{0} draft journal entries"
msgstr "{0} Entwurfs-Buchungszeilen"
+#. placeholder {0}: op.description
+msgid "{0} has no supplier"
+msgstr ""
+
#. placeholder {0}: formatter.format(onHand)
#. placeholder {1}: formatter.format(assembliesInStock)
#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
@@ -141,6 +145,10 @@ msgstr "{0} von {1} Buchungskonten zugeordnet"
msgid "{0} of {maxSlots} provider slots used"
msgstr "{0} von {maxSlots} Provider-Slots verwendet"
+#. placeholder {0}: pendingJobs.length
+msgid "{0} of {memberCount} member jobs are not completed yet — their output stays out of stock until each job is completed."
+msgstr "{0} von {memberCount} Fertigungsaufträgen sind noch nicht fertiggestellt — deren Erzeugnisse verbleiben außerhalb des Bestands, bis jeder Fertigungsauftrag fertiggestellt ist."
+
#. placeholder {0}: selected.length
msgid "{0} operations · {totalQuantity} parts"
msgstr "{0} Arbeitsgänge · {totalQuantity} Teile"
@@ -1652,6 +1660,10 @@ msgstr "Alle Artikel"
msgid "All Locations"
msgstr "Alle Standorte"
+#. placeholder {0}: tracked[0]?.itemReadableId ?? ""
+msgid "all make {0}"
+msgstr "alle Eigenfertigung {0}"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "Alle Mitglieder der ausgewählten Gruppen und ausgewählten Personen können Anfragen genehmigen"
@@ -3550,6 +3562,9 @@ msgstr "Überprüfen Sie Ihre E-Mail"
msgid "Checking Stripe for this customer…"
msgstr "Überprüfung von Stripe für diesen Kunden…"
+msgid "Checking the batch's jobs..."
+msgstr "Überprüfung der Aufträge des Loses..."
+
msgid "Checkpoint ·"
msgstr "Checkpoint ·"
@@ -3574,6 +3589,10 @@ msgstr "Wählen Sie eine Zeile auf der linken Seite, um zu sehen, woher der Best
msgid "Choose a serial number"
msgstr "Wählen Sie eine Seriennummer"
+#. placeholder {0}: op.description
+msgid "choose a supplier for {0} on the job"
+msgstr ""
+
msgid "Choose another file"
msgstr "Wählen Sie eine andere Datei"
@@ -3736,6 +3755,9 @@ msgstr "Spalten"
msgid "Combine filters"
msgstr "Filter kombinieren"
+msgid "Combine output into one lot"
+msgstr "Ausgabe in einer Charge kombinieren"
+
msgid "Coming soon"
msgstr "Demnächst verfügbar"
@@ -4526,6 +4548,9 @@ msgstr "Erstelle {0} Werte"
msgid "Create & Release"
msgstr "Erstellen & Freigeben"
+msgid "Create & release batch"
+msgstr "Los erstellen und freigeben"
+
msgid "Create & Snapshot"
msgstr "Erstellen & Snapshot"
@@ -4598,6 +4623,9 @@ msgstr "Fertigungsaufträge erstellen"
msgid "Create Kanban"
msgstr "Kanban erstellen"
+msgid "Create New"
+msgstr "Neu erstellen"
+
msgid "Create new rule"
msgstr "Neue Regel erstellen"
@@ -6269,6 +6297,12 @@ msgstr "z.B. Zebra 2x1"
msgid "Each cell is the people assigned against the people the day's work needs."
msgstr "Jede Zelle zeigt die zugewiesenen Personen gegen die Personen, die die Tagesarbeit benötigt."
+msgid "Each job keeps its own lot. The shop floor can't change these."
+msgstr "Jeder Fertigungsauftrag behält seine eigene Charge. Die Werkstatt kann diese nicht ändern."
+
+msgid "Each job needs its own lot number — or combine them into one lot."
+msgstr "Jeder Fertigungsauftrag braucht seine eigene Chargennummer — oder kombinieren Sie sie in einer Charge."
+
msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."
msgstr "Jede Zeile ist ein Link aus den Daten dieses Unternehmens zu einer Zeile, die es nicht besitzt. Eine Sicherung mit diesen Zeilen könnte niemals wiederhergestellt werden."
@@ -6281,6 +6315,9 @@ msgstr "Die ungenutzten Materialien jedes Arbeitsgangs werden zurückgegeben, so
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Jede physische Einheit erhält ihre eigene verfolgte Einheit und eine eindeutige Nummer – eine verfolgte Einheit, ein Stück."
+msgid "Each supplier's outside operations from every job go on one new purchase order, or on an existing draft you choose."
+msgstr "Die Fremdarbeitsgänge jedes Lieferanten aus jedem Fertigungsauftrag werden auf einer neuen Bestellung oder auf einem bestehenden Entwurf platziert, den Sie wählen."
+
msgid "Each, lb, ft…"
msgstr "Stück, kg, m…"
@@ -7027,6 +7064,9 @@ msgstr "Alles andere"
msgid "Everything else covers people, imports, integrations and the API — anything that is not one of your workflows."
msgstr "Alles andere umfasst Personal, Importe, Integrationen und die API — alles, das nicht zu Ihren Workflows gehört."
+msgid "Everything this run makes lands in one lot. The shop floor can't change it."
+msgstr "Alles, was dieser Durchlauf herstellt, landet in einer Charge. Die Werkstatt kann das nicht ändern."
+
msgid "Exceeds {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB total — remove some attachments to send."
msgstr "Überschreitet {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB insgesamt – entfernen Sie einige Anhänge zum Senden."
@@ -7804,6 +7844,9 @@ msgstr "Ansicht anpassen"
msgid "Fix the problems with this workflow before testing it"
msgstr "Beheben Sie die Probleme mit diesem Workflow, bevor Sie ihn testen"
+msgid "Fix these jobs before releasing"
+msgstr "Beheben Sie diese Fertigungsaufträge vor der Freigabe"
+
msgid "Fixed"
msgstr "Fest"
@@ -9610,7 +9653,7 @@ msgid "Lines"
msgstr "Zeilen"
msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."
-msgstr "Positionen erscheinen hier, sobald ein Bestellungswareneingang gebucht wurde, und nur für Mengen, die nicht bereits in einer anderen Lieferantenrückgabe autorisiert wurden. Nutzen Sie „Position hinzufügen\" für eine Blindrückgabe."
+msgstr "Positionen erscheinen hier, nachdem ein Wareneingang aus einer Bestellung gebucht wurde, und nur für Mengen, die nicht bereits für eine andere Lieferantenrückgabe genehmigt wurden. Verwenden Sie Hinzufügen für eine blinde Rückgabe."
msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."
msgstr "Positionen erscheinen hier, nachdem eine Lieferung eines Kundenauftrags gebucht wurde, und nur für Mengen, die nicht bereits durch ein anderes RMA autorisiert wurden. Verwenden Sie Position hinzufügen für blinde Rückgaben."
@@ -9806,6 +9849,9 @@ msgstr "Verloren"
msgid "Lot"
msgstr "Charge"
+msgid "Lot number"
+msgstr "Chargennummer"
+
msgid "Lot size"
msgstr "Losgröße"
@@ -9986,6 +10032,9 @@ msgstr "Herstellerteilnummer"
msgid "Manufacturing"
msgstr "Fertigung"
+msgid "manufacturing is blocked"
+msgstr "Fertigung ist blockiert"
+
msgid "Map accounts"
msgstr "Konten zuordnen"
@@ -10275,6 +10324,13 @@ msgstr "Memo-ID"
msgid "Merchant"
msgstr "Händler"
+#. placeholder {0}: getItemReadableId(items, itemId) ?? itemId
+msgid "Merge {0} lots"
+msgstr ""
+
+msgid "Merge output lots"
+msgstr "Ausgangschargen zusammenführen"
+
msgid "MES"
msgstr "MES"
@@ -11264,6 +11320,10 @@ msgstr "Keine offenen Kundenauftragsposition"
msgid "No operations found."
msgstr "Keine Arbeitsgänge gefunden."
+#. placeholder {0}: job.missingAssemblies .map((m) => m.description) .join(", ")
+msgid "no operations on {0}"
+msgstr "keine Arbeitsgänge auf {0}"
+
msgid "No operations require picking at this location"
msgstr "Keine Arbeitsgänge erfordern Kommissionierung an diesem Standort"
@@ -11385,7 +11445,7 @@ msgid "No results found"
msgstr "Keine Ergebnisse gefunden"
msgid "No returnable lines for this customer"
-msgstr "Keine rückgabefähigen Positionen für diesen Kunden."
+msgstr "Keine rückgabefähigen Positionen für diesen Kunden"
msgid "No returnable lines for this supplier"
msgstr "Keine rückgabefähigen Positionen für diesen Lieferanten"
@@ -13014,6 +13074,12 @@ msgstr "Prozesse"
msgid "Procurement status — needs ordering, planned, on order, or received. The same indicator shown in the BoM tree."
msgstr "Beschaffungsstatus – Bestellung erforderlich, geplant, bestellt oder erhalten. Derselbe Indikator, der im BoM-Baum angezeigt wird."
+msgid "produced item"
+msgstr "erzeugter Artikel"
+
+msgid "Produced item"
+msgstr "Erzeugter Artikel"
+
msgid "Product issues during hypercare"
msgstr "Produktprobleme während der Hypercare"
@@ -13923,6 +13989,11 @@ msgstr "{0} Lose freigeben"
msgid "Release Batch"
msgstr "Los freigeben"
+#. placeholder {0}: batch.readableId
+#. placeholder {0}: releaseTarget.readableId
+msgid "Release batch {0}"
+msgstr "Los {0} freigeben"
+
msgid "Release change notice"
msgstr "Änderungsmitteilung freigeben"
@@ -13951,6 +14022,9 @@ msgstr "Freigegebene Revision"
msgid "Released revision is locked"
msgstr "Freigegebene Revision ist gesperrt"
+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
+msgstr "Die Freigabe des Loses gibt seine Fertigungsaufträge frei, und jeder muss für die Werkstatt bereit sein."
+
msgid "Remaining"
msgstr "Verbleibend"
@@ -15074,7 +15148,7 @@ msgid "Search by linear issue title..."
msgstr "Nach Linear-Issue-Titel suchen..."
msgid "Search by receipt, PO, or item"
-msgstr "Nach Wareneingang, Bestellung oder Artikel suchen"
+msgstr "Suchen nach Wareneingang, Bestellung oder Artikel"
msgid "Search by shipment, sales order, or item"
msgstr "Nach Lieferung, Kundenauftrag oder Artikel suchen"
@@ -15324,7 +15398,7 @@ msgid "Select operations"
msgstr "Arbeitsgänge wählen"
msgid "Select posted receipt lines from this supplier to return."
-msgstr "Wählen Sie gebuchte Wareneinganspositionen von diesem Lieferant zum Zurückgeben aus."
+msgstr "Wählen Sie gebuchte Wareneingangspositionen von diesem Lieferant aus, um sie zurückzusenden."
msgid "Select posted shipment lines to this customer to return."
msgstr "Gebuchte Lieferpositionen an diesen Kunden zur Rückgabe auswählen."
@@ -15523,7 +15597,7 @@ msgid "Session locked"
msgstr "Sitzung gesperrt"
msgid "Set a customer on this return to add from a shipment."
-msgstr "Legen Sie einen Kunden für diese Rückgabe fest, um von einer Lieferung hinzuzufügen."
+msgstr "Legen Sie einen Kunden für diese Rückgabe fest, um aus einer Lieferung hinzuzufügen."
msgid "Set a supplier on this return to add from a receipt."
msgstr "Wählen Sie einen Lieferanten für diese Rückgabe aus, um Positionen von einem Wareneingang hinzuzufügen."
@@ -15822,6 +15896,10 @@ msgstr "Tastenkombinationen"
msgid "Show"
msgstr "Anzeigen"
+#. placeholder {0}: overflow.length
+msgid "Show {0} more"
+msgstr ""
+
msgid "Show a readable Customer ID column on the customer list, customer forms, and dropdowns. Customers are still identified internally either way."
msgstr "Zeigen Sie eine lesbare Kundennummern-Spalte in der Kundenliste, Kundenformularen und Dropdowns an. Kunden werden intern in jedem Fall identifiziert."
@@ -16981,6 +17059,9 @@ msgstr "Der Sicherungsvorgang hat diesen Fehler gemeldet."
msgid "The backward-computed date an operation must finish by to keep its job on time, written to the operation's due date. A stable target for measuring progress — never a constraint on placement."
msgstr "Das rückwärts berechnete Datum, bis zu dem ein Arbeitsgang beendet sein muss, um seinen Fertigungsauftrag pünktlich zu halten, geschrieben auf das Fälligkeitsdatum des Arbeitsgangs. Ein stabiles Ziel zur Messung des Fortschritts - niemals eine Platzierungsbeschränkung."
+msgid "The batch goes to the shop floor. Its jobs are already released."
+msgstr "Das Los geht in die Werkstatt. Seine Fertigungsaufträge sind bereits freigegeben."
+
msgid "The batch runs at its most urgent member's time — the others are pulled early"
msgstr "Der Batch läuft zum Termin seines dringendsten Auftrags — die übrigen werden vorgezogen"
@@ -17266,6 +17347,9 @@ msgstr "Die Bestandskosten, die bei einer Lieferbuchung anerkannt werden, bewert
msgid "The IRS recovery-period class for this asset under MACRS (3, 5, 7, 10, 15, 20, 27.5, 39-year)."
msgstr "Die IRS-Wiederherstellungsperiode-Klasse für diesen Gegenstand nach MACRS (3, 5, 7, 10, 15, 20, 27,5, 39 Jahre)."
+msgid "The item each job produces — require it to match to merge output lots"
+msgstr "Der Artikel, den jeder Fertigungsauftrag produziert – erforderlich, um Ausgangschargen zusammenzuführen"
+
msgid "the job hours due that day (a due-date basis, not the day the work runs), with overdue work in Past due."
msgstr "die Arbeitsstunden fällig an diesem Tag (basierend auf dem Fälligkeitsdatum, nicht dem Tag der Ausführung), mit überfälligen Arbeiten unter Überfällig."
@@ -17800,6 +17884,11 @@ msgstr "Diese Zeilen sind mit Daten außerhalb dieses Unternehmens verknüpft, d
msgid "this ability"
msgstr "diese Qualifikation"
+#. placeholder {0}: jobIds.length
+#. placeholder {1}: jobIds.join(", ")
+msgid "This also releases {0} jobs ({1}). They become available to the shop floor and drive purchasing and production."
+msgstr "Dies gibt auch {0} Fertigungsaufträge ({1}) frei. Sie werden für die Werkstatt verfügbar und fördern Einkauf und Produktion."
+
msgid "This backup could not be completed."
msgstr "Diese Sicherung konnte nicht abgeschlossen werden."
diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.po
index b3160bd6f9..925f33f99f 100644
--- a/packages/locale/locales/de/mes.po
+++ b/packages/locale/locales/de/mes.po
@@ -25,14 +25,28 @@ msgstr "{0} Aktiv"
msgid "{0} ago"
msgstr "vor {0}"
+#. placeholder {0}: batchFacts.customers.length
+msgid "{0} customers"
+msgstr ""
+
+#. placeholder {0}: unplanned .map( (m) => (m.job as { jobId?: string | null } | null)?.jobId ) .filter(Boolean) .join(", ")
+msgid "{0} has no lot number. Set it on the batch or job in Carbon, then complete."
+msgstr "{0} hat keine Chargennummer. Stellen Sie sie für das Los oder den Fertigungsauftrag in Carbon ein und schließen Sie ab."
+
+#. placeholder {0}: batchFacts.items.length
+msgid "{0} items"
+msgstr ""
+
#. placeholder {0}: (batch.operations ?? []).length
msgid "{0} jobs"
msgstr "{0} Fertigungsaufträge"
+#. placeholder {0}: issuedLines.length
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
#. placeholder {1}: operation.targetQuantity
+#. placeholder {1}: trackedLines.length
msgid "{0} of {1}"
msgstr "{0} von {1}"
@@ -54,16 +68,28 @@ msgstr "{0} in Warteschlange"
msgid "{0} running"
msgstr "{0} läuft"
+#. placeholder {0}: operation.jobReadableId
+#. placeholder {1}: batch.readableId
+msgid "{0} runs in batch {1}"
+msgstr ""
+
#. placeholder {0}: item.quantityScrapped
msgid "{0} Scrapped"
msgstr "{0} Ausschuss"
+msgid "{completed} of {quantity}"
+msgstr "{completed} von {quantity}"
+
msgid "{completions} passed unit(s) will be completed."
msgstr "{completions} bestandene Einheit(en) werden abgeschlossen."
msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
msgstr "{fails} erfasste Fehler werden NICHT abgeschlossen – beheben Sie diese über das Aktionsmenü."
+#. placeholder {0}: step.perMember.length
+msgid "{recorded}/{0} jobs"
+msgstr ""
+
msgid "+{overflow} more"
msgstr "+{overflow} weitere"
@@ -88,6 +114,10 @@ msgstr "Kontoeinstellungen"
msgid "Acknowledge & finish"
msgstr "Bestätigen & beenden"
+#. placeholder {0}: members.length
+msgid "across {0} jobs"
+msgstr "über {0} Fertigungsaufträge"
+
msgid "Active"
msgstr "Aktiv"
@@ -118,6 +148,13 @@ msgstr "Alle"
msgid "All clear"
msgstr "Alles klar"
+msgid "All jobs"
+msgstr "Alle Fertigungsaufträge"
+
+#. placeholder {0}: batch.outputLotNumber
+msgid "All output goes to lot <0>{0}</0>"
+msgstr "Die gesamte Ausgabe geht an Charge <0>{0}</0>"
+
msgid "All rework"
msgstr "Alle Nacharbeit"
@@ -166,6 +203,9 @@ msgstr "verfügbar"
msgid "Available"
msgstr "Verfügbar"
+msgid "Back to batch"
+msgstr ""
+
msgid "Batch"
msgstr "Charge"
@@ -179,12 +219,21 @@ msgstr "Chargennummer {0}"
msgid "Batch number is required"
msgstr "Chargennummer ist erforderlich"
-msgid "Batched jobs"
-msgstr "Gebündelte Fertigungsaufträge"
+msgid "Batch quantity"
+msgstr "Los-Menge"
+
+msgid "batch total"
+msgstr "Los-Gesamtbetrag"
msgid "Behind target by {daysBehindTarget} day(s)"
msgstr "Hinter dem Ziel um {daysBehindTarget} Tag(e)"
+#. placeholder {0}: step.minValue
+#. placeholder {1}: step.maxValue
+#. placeholder {2}: step.unitOfMeasureCode ?? ""
+msgid "Between {0} and {1} {2}"
+msgstr ""
+
#. placeholder {0}: column.blockingDispatchReadableId
msgid "Blocked by {0}"
msgstr "Blockiert durch {0}"
@@ -222,6 +271,9 @@ msgstr "Chat"
msgid "Check your email"
msgstr "Prüfen Sie Ihre E-Mail"
+msgid "Choose a job"
+msgstr ""
+
msgid "Clear"
msgstr "Löschen"
@@ -249,6 +301,9 @@ msgstr "Schließen"
msgid "Collapse features table"
msgstr "Merkmalstabelle ausblenden"
+msgid "Collapse panel"
+msgstr "Bereich reduzieren"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -278,6 +333,9 @@ msgstr "Abschließen"
msgid "Complete All"
msgstr "Alles abschließen"
+msgid "Complete batch"
+msgstr ""
+
msgid "Complete Batch"
msgstr "Charge abschließen"
@@ -377,6 +435,9 @@ msgstr "Anzeige"
msgid "Displays"
msgstr "Anzeigetafeln"
+msgid "Done"
+msgstr ""
+
msgid "Down"
msgstr "Stillstand"
@@ -409,9 +470,12 @@ msgstr "Zeichnung und Funktionen durch Ziehen vergrößern/verkleinern"
msgid "Dragging {0} cancelled."
msgstr "Ziehen von {0} storniert."
+msgid "Due"
+msgstr ""
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
msgid "Due {0}"
msgstr "Fällig {0}"
@@ -434,6 +498,9 @@ msgstr "Doppelte Seriennummer"
msgid "Duration"
msgstr "Dauer"
+msgid "Each job's output is its own lot — keep each job's parts apart."
+msgstr ""
+
msgid "Edit"
msgstr "Bearbeiten"
@@ -449,6 +516,9 @@ msgstr "Leere Arbeitsplätze"
msgid "End Operations"
msgstr "Arbeitsgänge beenden"
+msgid "Enter each job's value, or fill every job at once from the first row. Empty rows are skipped."
+msgstr ""
+
#. placeholder {0}: selectedPerson.name
msgid "Enter PIN for {0}"
msgstr "PIN für {0} eingeben"
@@ -465,12 +535,18 @@ msgstr "Fehler"
msgid "Estimated"
msgstr "Soll"
+msgid "Every job in the batch follows these steps. Record a step for all of them at once."
+msgstr ""
+
msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
msgstr "Jede Einheit hat ein Urteil: {passes} bestanden und {fails} fehlgeschlagen. Das Los wird geschlossen, wobei jede Einheit zu ihrem eigenen Ergebnis weitergeleitet wird."
msgid "Expand features table"
msgstr "Funktionstabelle erweitern"
+msgid "Expand panel"
+msgstr "Bereich erweitern"
+
msgid "Expired"
msgstr "Abgelaufen"
@@ -511,6 +587,10 @@ msgstr "Messung konnte nicht gespeichert werden"
msgid "Failed to save result"
msgstr "Ergebnis konnte nicht gespeichert werden"
+#. placeholder {0}: file.name
+msgid "Failed to upload {0}"
+msgstr ""
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Fehler beim Hochladen der Datei: {0}"
@@ -555,6 +635,10 @@ msgstr "Beenden Sie die Einrichtung Ihres Kontos"
msgid "Finish with material unpicked?"
msgstr "Mit nicht gepicktem Material abschließen?"
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(batchFacts.dueDate) )
+msgid "First due {0}"
+msgstr ""
+
msgid "Forgot to Clock Out?"
msgstr "Ausstempeln vergessen?"
@@ -567,6 +651,9 @@ msgstr "Zurück zur Operation"
msgid "Go to onboarding"
msgstr "Gehen Sie zum Onboarding"
+msgid "Hide description"
+msgstr ""
+
msgid "How many were actually picked?"
msgstr "Wie viele wurden tatsächlich gepickt?"
@@ -631,6 +718,9 @@ msgstr "Material ausgeben"
msgid "Issue Type"
msgstr "Problemtyp"
+msgid "Issued"
+msgstr "Ausgegeben"
+
msgid "Issued {issuedQuantity} of {lotLabel}"
msgstr "Freigegeben {issuedQuantity} von {lotLabel}"
@@ -688,6 +778,9 @@ msgstr "Zeilen"
msgid "List view"
msgstr "Listenansicht"
+msgid "Load list"
+msgstr ""
+
msgid "Loading item details..."
msgstr "Artikeldetails werden geladen..."
@@ -700,6 +793,9 @@ msgstr "Lokal"
msgid "Location"
msgstr "Standort"
+msgid "Log completed"
+msgstr ""
+
msgid "Log Completed"
msgstr "Fertigmeldung"
@@ -727,6 +823,12 @@ msgstr "Anmelden"
msgid "Lot"
msgstr "Charge"
+msgid "Lot numbers missing"
+msgstr "Chargennummern fehlen"
+
+msgid "Lot tracked"
+msgstr ""
+
msgid "Machine"
msgstr "Maschine"
@@ -763,6 +865,9 @@ msgstr "entspricht"
msgid "Materials"
msgstr "Materialien"
+msgid "Materials issued"
+msgstr "Werkstoffe ausgegeben"
+
msgid "Maximum number of records reached"
msgstr "Maximale Anzahl an Datensätzen erreicht"
@@ -866,6 +971,9 @@ msgstr "Keine Übereinstimmungen. Geben Sie etwas ein, um einen zu erstellen."
msgid "No materials"
msgstr "Keine Materialien"
+msgid "No materials on this batch."
+msgstr "Keine Werkstoffe in diesem Los."
+
msgid "No open jobs"
msgstr "Keine offenen Fertigungsaufträge"
@@ -959,9 +1067,22 @@ msgstr "OEE-Auswirkung"
msgid "OEM Required"
msgstr "OEM erforderlich"
+#. placeholder {0}: m.operationQuantity ?? 0
+msgid "of {0}"
+msgstr ""
+
msgid "Oldest first"
msgstr "Älteste zuerst"
+msgid "one combined lot · planned"
+msgstr "eine kombinierte Charge · geplant"
+
+msgid "one per job · planned"
+msgstr "eine pro Fertigungsauftrag · geplant"
+
+msgid "One pick covers the whole batch — it is shared out to the jobs automatically."
+msgstr ""
+
#. placeholder {0}: batch.quantity
msgid "Only {0} available"
msgstr "Nur {0} verfügbar"
@@ -975,6 +1096,9 @@ msgstr "Offen"
msgid "Open a display on the screen mounted at the work center and leave it running. Each board refreshes on its own."
msgstr "Öffnen Sie eine Anzeige auf dem am Arbeitsplatz montierten Bildschirm und lassen Sie sie laufen. Jede Tafel aktualisiert sich von selbst."
+msgid "Open a job in this batch"
+msgstr ""
+
msgid "Open an NCR for MRB disposition"
msgstr "Öffnen Sie einen NCR für MRB-Verwendungsentscheid"
@@ -999,6 +1123,9 @@ msgstr "Optional"
msgid "or"
msgstr "oder"
+msgid "Output lot"
+msgstr "Ausgabe-Charge"
+
msgid "Overall result"
msgstr "Gesamtergebnis"
@@ -1017,6 +1144,9 @@ msgstr "Teilweise"
msgid "Partial Disposition"
msgstr "Teilweise Verwendungsentscheid"
+msgid "Passed inspection"
+msgstr ""
+
msgid "Passed Inspection"
msgstr "Prüfung bestanden"
@@ -1029,6 +1159,10 @@ msgstr "Unterbrechen"
msgid "Pick"
msgstr "Kommissionieren"
+#. placeholder {0}: m.required - m.issued
+msgid "Pick {0}"
+msgstr "Kommissionieren {0}"
+
msgid "Pick tracked item"
msgstr "Verfolgtes Element auswählen"
@@ -1098,6 +1232,9 @@ msgstr "Verfahrensanweisung"
msgid "Process"
msgstr "Prozess"
+msgid "Process parameters"
+msgstr "Verfahrensparameter"
+
msgid "Process Parameters"
msgstr "Prozessparameter"
@@ -1140,18 +1277,28 @@ msgstr "Erfassen"
msgid "Record {0}"
msgstr "Datensatz {0}"
+#. placeholder {0}: changed.length
+msgid "Record {0} jobs"
+msgstr ""
+
msgid "Record only"
msgstr "Nur aufzeichnen"
msgid "Record Partial"
msgstr "Teilweise aufzeichnen"
+msgid "Recorded"
+msgstr ""
+
msgid "Reject"
msgstr "Ablehnen"
msgid "Reject Lot"
msgstr "Charge ablehnen"
+msgid "Released"
+msgstr ""
+
msgid "Remove"
msgstr "Entfernen"
@@ -1167,6 +1314,9 @@ msgstr "Teil entfernen"
msgid "Reopen the subassembly and create a replacement unit"
msgstr "Baugruppe wieder öffnen und Ersatzeinheit erstellen"
+msgid "Required"
+msgstr "Erforderlich"
+
msgid "Result"
msgstr "Ergebnis"
@@ -1188,6 +1338,9 @@ msgstr "Läuft"
msgid "Sales Order"
msgstr "Kundenauftrag"
+msgid "Same for every job"
+msgstr ""
+
msgid "Save"
msgstr "Speichern"
@@ -1307,6 +1460,9 @@ msgstr "Senden"
msgid "Send to Carbon"
msgstr "An Carbon senden"
+msgid "Separate lots"
+msgstr "Separate Chargen"
+
msgid "Serial"
msgstr "Serie"
@@ -1326,6 +1482,9 @@ msgstr "Seriennummern"
msgid "Serial Numbers"
msgstr "Seriennummern"
+msgid "Serialized"
+msgstr ""
+
msgid "Session locked"
msgstr "Sitzung gesperrt"
@@ -1338,6 +1497,9 @@ msgstr "Ausstempelzeit festlegen"
msgid "Set up in Carbon"
msgstr "In Carbon einrichten"
+msgid "Set when the batch was planned."
+msgstr "Eingestellt, wenn das Los geplant wurde."
+
msgid "Setup"
msgstr "Rüsten"
@@ -1350,6 +1512,9 @@ msgstr "Fehlbestand"
msgid "Short pick {itemName}"
msgstr "Kurzkommissionierung {itemName}"
+msgid "Show description"
+msgstr ""
+
msgid "Show this overlay"
msgstr "Dieses Overlay anzeigen"
@@ -1389,6 +1554,10 @@ msgstr "Verwendete Ersatzteile"
msgid "Start"
msgstr "Start"
+#. placeholder {0}: workTypeLabels[ eventType.toLowerCase() as keyof typeof workTypeLabels ].toLowerCase()
+msgid "Start {0}"
+msgstr ""
+
msgid "Start or pause the operation"
msgstr "Arbeitsgang starten oder unterbrechen"
@@ -1438,12 +1607,22 @@ msgstr "Tag"
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "Die abgeschlossene Menge für diesen Arbeitsgang ist geringer als die erforderliche Menge von {targetQuantity}."
+msgid "The jobs and parts that make up this run."
+msgstr ""
+
+msgid "The jobs make different items — keep each job's parts apart."
+msgstr ""
+
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "Das Los wird als Bestanden markiert und {remaining} verbleibende Einheit(en) werden bei diesem Arbeitsgang abgeschlossen."
msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "Das Los wird weiterhin dispositioniert, aber ein NCR kann nicht erstellt werden, bis mindestens ein Problemtyp konfiguriert ist."
+#. placeholder {0}: (batch.operations ?? []).length
+msgid "The timer and completion are shared by all {0} jobs. Steps, materials and files here are this job's own."
+msgstr ""
+
msgid "There are no available or consumed tracked parts for this material."
msgstr "Es gibt keine verfügbaren oder verbrauchten verfolgten Teile für dieses Material."
@@ -1453,6 +1632,9 @@ msgstr "Es gibt serien- oder chargenverfolgte Materialien in der Stückliste, di
msgid "These items still have material to pick. Finishing now marks the list Partial."
msgstr "Diese Artikel haben noch Material zum Picken. Ein Abschluss jetzt markiert die Liste als Teilweise."
+msgid "This batch has no work instructions."
+msgstr ""
+
msgid "This lot is expired and can't be picked."
msgstr "Dieses Los ist abgelaufen und kann nicht entnommen werden."
@@ -1468,6 +1650,9 @@ msgstr "Diese Einheit wird endgültig verschrottet und es wird eine neue Serienn
msgid "Thumbnail"
msgstr "Vorschaubild"
+msgid "Tick the jobs this was done for."
+msgstr ""
+
msgid "Time and cost split across jobs proportionally to quantity."
msgstr "Zeit und Kosten werden proportional zur Menge auf die Fertigungsaufträge verteilt."
@@ -1478,6 +1663,12 @@ msgstr "Zeiteinträge"
msgid "Time Worked: {0}"
msgstr "Arbeitszeit: {0}"
+msgid "To pick"
+msgstr ""
+
+msgid "To run"
+msgstr ""
+
msgid "Today"
msgstr "Heute"
@@ -1487,6 +1678,9 @@ msgstr "Seitenleiste ein-/ausblenden"
msgid "Tools"
msgstr "Werkzeuge"
+msgid "Total"
+msgstr ""
+
msgid "Total Quantity"
msgstr "Gesamtmenge"
@@ -1501,6 +1695,9 @@ msgstr "Gesamt: {0}"
msgid "Tracked Entity"
msgstr "Verfolgte Einheit"
+msgid "tracked lines"
+msgstr "nachverfolgten Positionen"
+
msgid "Tracking"
msgstr "Verfolgung"
@@ -1572,6 +1769,12 @@ msgstr "{0} wird hochgeladen"
msgid "Use a different account"
msgstr "Verwenden Sie ein anderes Konto"
+msgid "Used automatically at completion"
+msgstr ""
+
+msgid "Value"
+msgstr ""
+
msgid "Verify"
msgstr "Bestätigen"
@@ -1584,6 +1787,9 @@ msgstr "Wir haben Ihnen einen Magic Link zur Anmeldung an Ihrem Konto gesendet."
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm} ist was?"
+msgid "Whole batch"
+msgstr "Ganzes Los"
+
msgid "WIP"
msgstr "WIP"
@@ -1593,6 +1799,9 @@ msgstr "Arbeitsplatz"
msgid "Work Center Displays"
msgstr "Arbeitsplatzanzeigen"
+msgid "Work instructions"
+msgstr "Arbeitsanweisungen"
+
msgid "Yes"
msgstr "Ja"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index f2a709e6b2..4a6e493e85 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -111,6 +111,10 @@ msgstr "{0} deleted successfully"
msgid "{0} draft journal entries"
msgstr "{0} draft journal entries"
+#. placeholder {0}: op.description
+msgid "{0} has no supplier"
+msgstr "{0} has no supplier"
+
#. placeholder {0}: formatter.format(onHand)
#. placeholder {1}: formatter.format(assembliesInStock)
#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
@@ -141,6 +145,10 @@ msgstr "{0} of {1} posting accounts mapped"
msgid "{0} of {maxSlots} provider slots used"
msgstr "{0} of {maxSlots} provider slots used"
+#. placeholder {0}: pendingJobs.length
+msgid "{0} of {memberCount} member jobs are not completed yet — their output stays out of stock until each job is completed."
+msgstr "{0} of {memberCount} member jobs are not completed yet — their output stays out of stock until each job is completed."
+
#. placeholder {0}: selected.length
msgid "{0} operations · {totalQuantity} parts"
msgstr "{0} operations · {totalQuantity} parts"
@@ -1652,6 +1660,10 @@ msgstr "All Items"
msgid "All Locations"
msgstr "All Locations"
+#. placeholder {0}: tracked[0]?.itemReadableId ?? ""
+msgid "all make {0}"
+msgstr "all make {0}"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "All members of selected groups and selected individuals will be able to approve requests"
@@ -3550,6 +3562,9 @@ msgstr "Check your email"
msgid "Checking Stripe for this customer…"
msgstr "Checking Stripe for this customer…"
+msgid "Checking the batch's jobs..."
+msgstr "Checking the batch's jobs..."
+
msgid "Checkpoint ·"
msgstr "Checkpoint ·"
@@ -3574,6 +3589,10 @@ msgstr "Choose a row on the left to see where its stock can come from."
msgid "Choose a serial number"
msgstr "Choose a serial number"
+#. placeholder {0}: op.description
+msgid "choose a supplier for {0} on the job"
+msgstr "choose a supplier for {0} on the job"
+
msgid "Choose another file"
msgstr "Choose another file"
@@ -3736,6 +3755,9 @@ msgstr "Columns"
msgid "Combine filters"
msgstr "Combine filters"
+msgid "Combine output into one lot"
+msgstr "Combine output into one lot"
+
msgid "Coming soon"
msgstr "Coming soon"
@@ -4526,6 +4548,9 @@ msgstr "Create {0} values"
msgid "Create & Release"
msgstr "Create & Release"
+msgid "Create & release batch"
+msgstr "Create & release batch"
+
msgid "Create & Snapshot"
msgstr "Create & Snapshot"
@@ -4598,6 +4623,9 @@ msgstr "Create Jobs"
msgid "Create Kanban"
msgstr "Create Kanban"
+msgid "Create New"
+msgstr "Create New"
+
msgid "Create new rule"
msgstr "Create new rule"
@@ -6269,6 +6297,12 @@ msgstr "e.g. Zebra 2x1"
msgid "Each cell is the people assigned against the people the day's work needs."
msgstr "Each cell is the people assigned against the people the day's work needs."
+msgid "Each job keeps its own lot. The shop floor can't change these."
+msgstr "Each job keeps its own lot. The shop floor can't change these."
+
+msgid "Each job needs its own lot number — or combine them into one lot."
+msgstr "Each job needs its own lot number — or combine them into one lot."
+
msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."
msgstr "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."
@@ -6281,6 +6315,9 @@ msgstr "Each operation's unused material returns as soon as the operation is don
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
+msgid "Each supplier's outside operations from every job go on one new purchase order, or on an existing draft you choose."
+msgstr "Each supplier's outside operations from every job go on one new purchase order, or on an existing draft you choose."
+
msgid "Each, lb, ft…"
msgstr "Each, lb, ft…"
@@ -7027,6 +7064,9 @@ msgstr "Everything else"
msgid "Everything else covers people, imports, integrations and the API — anything that is not one of your workflows."
msgstr "Everything else covers people, imports, integrations and the API — anything that is not one of your workflows."
+msgid "Everything this run makes lands in one lot. The shop floor can't change it."
+msgstr "Everything this run makes lands in one lot. The shop floor can't change it."
+
msgid "Exceeds {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB total — remove some attachments to send."
msgstr "Exceeds {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB total — remove some attachments to send."
@@ -7804,6 +7844,9 @@ msgstr "Fit view"
msgid "Fix the problems with this workflow before testing it"
msgstr "Fix the problems with this workflow before testing it"
+msgid "Fix these jobs before releasing"
+msgstr "Fix these jobs before releasing"
+
msgid "Fixed"
msgstr "Fixed"
@@ -9806,6 +9849,9 @@ msgstr "Lost"
msgid "Lot"
msgstr "Lot"
+msgid "Lot number"
+msgstr "Lot number"
+
msgid "Lot size"
msgstr "Lot size"
@@ -9986,6 +10032,9 @@ msgstr "Manufacturer Part Number"
msgid "Manufacturing"
msgstr "Manufacturing"
+msgid "manufacturing is blocked"
+msgstr "manufacturing is blocked"
+
msgid "Map accounts"
msgstr "Map accounts"
@@ -10275,6 +10324,13 @@ msgstr "Memo ID"
msgid "Merchant"
msgstr "Merchant"
+#. placeholder {0}: getItemReadableId(items, itemId) ?? itemId
+msgid "Merge {0} lots"
+msgstr "Merge {0} lots"
+
+msgid "Merge output lots"
+msgstr "Merge output lots"
+
msgid "MES"
msgstr "MES"
@@ -11264,6 +11320,10 @@ msgstr "No open sales order lines"
msgid "No operations found."
msgstr "No operations found."
+#. placeholder {0}: job.missingAssemblies .map((m) => m.description) .join(", ")
+msgid "no operations on {0}"
+msgstr "no operations on {0}"
+
msgid "No operations require picking at this location"
msgstr "No operations require picking at this location"
@@ -13014,6 +13074,12 @@ msgstr "Processes"
msgid "Procurement status — needs ordering, planned, on order, or received. The same indicator shown in the BoM tree."
msgstr "Procurement status — needs ordering, planned, on order, or received. The same indicator shown in the BoM tree."
+msgid "produced item"
+msgstr "produced item"
+
+msgid "Produced item"
+msgstr "Produced item"
+
msgid "Product issues during hypercare"
msgstr "Product issues during hypercare"
@@ -13923,6 +13989,11 @@ msgstr "Release {0} batches"
msgid "Release Batch"
msgstr "Release Batch"
+#. placeholder {0}: batch.readableId
+#. placeholder {0}: releaseTarget.readableId
+msgid "Release batch {0}"
+msgstr "Release batch {0}"
+
msgid "Release change notice"
msgstr "Release change notice"
@@ -13951,6 +14022,9 @@ msgstr "Released revision"
msgid "Released revision is locked"
msgstr "Released revision is locked"
+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
+msgstr "Releasing the batch releases its jobs, and each one must be ready for the floor."
+
msgid "Remaining"
msgstr "Remaining"
@@ -15822,6 +15896,10 @@ msgstr "Shortcuts"
msgid "Show"
msgstr "Show"
+#. placeholder {0}: overflow.length
+msgid "Show {0} more"
+msgstr "Show {0} more"
+
msgid "Show a readable Customer ID column on the customer list, customer forms, and dropdowns. Customers are still identified internally either way."
msgstr "Show a readable Customer ID column on the customer list, customer forms, and dropdowns. Customers are still identified internally either way."
@@ -16981,6 +17059,9 @@ msgstr "The backup job reported this error."
msgid "The backward-computed date an operation must finish by to keep its job on time, written to the operation's due date. A stable target for measuring progress — never a constraint on placement."
msgstr "The backward-computed date an operation must finish by to keep its job on time, written to the operation's due date. A stable target for measuring progress — never a constraint on placement."
+msgid "The batch goes to the shop floor. Its jobs are already released."
+msgstr "The batch goes to the shop floor. Its jobs are already released."
+
msgid "The batch runs at its most urgent member's time — the others are pulled early"
msgstr "The batch runs at its most urgent member's time — the others are pulled early"
@@ -17266,6 +17347,9 @@ msgstr "The inventory cost recognized when a shipment posts, valued by the item'
msgid "The IRS recovery-period class for this asset under MACRS (3, 5, 7, 10, 15, 20, 27.5, 39-year)."
msgstr "The IRS recovery-period class for this asset under MACRS (3, 5, 7, 10, 15, 20, 27.5, 39-year)."
+msgid "The item each job produces — require it to match to merge output lots"
+msgstr "The item each job produces — require it to match to merge output lots"
+
msgid "the job hours due that day (a due-date basis, not the day the work runs), with overdue work in Past due."
msgstr "the job hours due that day (a due-date basis, not the day the work runs), with overdue work in Past due."
@@ -17800,6 +17884,11 @@ msgstr "These rows link to data outside this company, so they could never be res
msgid "this ability"
msgstr "this ability"
+#. placeholder {0}: jobIds.length
+#. placeholder {1}: jobIds.join(", ")
+msgid "This also releases {0} jobs ({1}). They become available to the shop floor and drive purchasing and production."
+msgstr "This also releases {0} jobs ({1}). They become available to the shop floor and drive purchasing and production."
+
msgid "This backup could not be completed."
msgstr "This backup could not be completed."
diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.po
index f2c8dd28fb..2909bbd062 100644
--- a/packages/locale/locales/en/mes.po
+++ b/packages/locale/locales/en/mes.po
@@ -25,14 +25,28 @@ msgstr "{0} Active"
msgid "{0} ago"
msgstr "{0} ago"
+#. placeholder {0}: batchFacts.customers.length
+msgid "{0} customers"
+msgstr "{0} customers"
+
+#. placeholder {0}: unplanned .map( (m) => (m.job as { jobId?: string | null } | null)?.jobId ) .filter(Boolean) .join(", ")
+msgid "{0} has no lot number. Set it on the batch or job in Carbon, then complete."
+msgstr "{0} has no lot number. Set it on the batch or job in Carbon, then complete."
+
+#. placeholder {0}: batchFacts.items.length
+msgid "{0} items"
+msgstr "{0} items"
+
#. placeholder {0}: (batch.operations ?? []).length
msgid "{0} jobs"
msgstr "{0} jobs"
+#. placeholder {0}: issuedLines.length
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
#. placeholder {1}: operation.targetQuantity
+#. placeholder {1}: trackedLines.length
msgid "{0} of {1}"
msgstr "{0} of {1}"
@@ -54,16 +68,28 @@ msgstr "{0} queued"
msgid "{0} running"
msgstr "{0} running"
+#. placeholder {0}: operation.jobReadableId
+#. placeholder {1}: batch.readableId
+msgid "{0} runs in batch {1}"
+msgstr "{0} runs in batch {1}"
+
#. placeholder {0}: item.quantityScrapped
msgid "{0} Scrapped"
msgstr "{0} Scrapped"
+msgid "{completed} of {quantity}"
+msgstr "{completed} of {quantity}"
+
msgid "{completions} passed unit(s) will be completed."
msgstr "{completions} passed unit(s) will be completed."
msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
msgstr "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
+#. placeholder {0}: step.perMember.length
+msgid "{recorded}/{0} jobs"
+msgstr "{recorded}/{0} jobs"
+
msgid "+{overflow} more"
msgstr "+{overflow} more"
@@ -88,6 +114,10 @@ msgstr "Account Settings"
msgid "Acknowledge & finish"
msgstr "Acknowledge & finish"
+#. placeholder {0}: members.length
+msgid "across {0} jobs"
+msgstr "across {0} jobs"
+
msgid "Active"
msgstr "Active"
@@ -118,6 +148,13 @@ msgstr "All"
msgid "All clear"
msgstr "All clear"
+msgid "All jobs"
+msgstr "All jobs"
+
+#. placeholder {0}: batch.outputLotNumber
+msgid "All output goes to lot <0>{0}</0>"
+msgstr "All output goes to lot <0>{0}</0>"
+
msgid "All rework"
msgstr "All rework"
@@ -166,6 +203,9 @@ msgstr "available"
msgid "Available"
msgstr "Available"
+msgid "Back to batch"
+msgstr "Back to batch"
+
msgid "Batch"
msgstr "Batch"
@@ -179,12 +219,21 @@ msgstr "Batch Number {0}"
msgid "Batch number is required"
msgstr "Batch number is required"
-msgid "Batched jobs"
-msgstr "Batched jobs"
+msgid "Batch quantity"
+msgstr "Batch quantity"
+
+msgid "batch total"
+msgstr "batch total"
msgid "Behind target by {daysBehindTarget} day(s)"
msgstr "Behind target by {daysBehindTarget} day(s)"
+#. placeholder {0}: step.minValue
+#. placeholder {1}: step.maxValue
+#. placeholder {2}: step.unitOfMeasureCode ?? ""
+msgid "Between {0} and {1} {2}"
+msgstr "Between {0} and {1} {2}"
+
#. placeholder {0}: column.blockingDispatchReadableId
msgid "Blocked by {0}"
msgstr "Blocked by {0}"
@@ -222,6 +271,9 @@ msgstr "Chat"
msgid "Check your email"
msgstr "Check your email"
+msgid "Choose a job"
+msgstr "Choose a job"
+
msgid "Clear"
msgstr "Clear"
@@ -249,6 +301,9 @@ msgstr "Close"
msgid "Collapse features table"
msgstr "Collapse features table"
+msgid "Collapse panel"
+msgstr "Collapse panel"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -278,6 +333,9 @@ msgstr "Complete"
msgid "Complete All"
msgstr "Complete All"
+msgid "Complete batch"
+msgstr "Complete batch"
+
msgid "Complete Batch"
msgstr "Complete Batch"
@@ -377,6 +435,9 @@ msgstr "Display"
msgid "Displays"
msgstr "Displays"
+msgid "Done"
+msgstr "Done"
+
msgid "Down"
msgstr "Down"
@@ -409,9 +470,12 @@ msgstr "Drag to resize drawing and features"
msgid "Dragging {0} cancelled."
msgstr "Dragging {0} cancelled."
+msgid "Due"
+msgstr "Due"
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
msgid "Due {0}"
msgstr "Due {0}"
@@ -434,6 +498,9 @@ msgstr "Duplicate serial number"
msgid "Duration"
msgstr "Duration"
+msgid "Each job's output is its own lot — keep each job's parts apart."
+msgstr "Each job's output is its own lot — keep each job's parts apart."
+
msgid "Edit"
msgstr "Edit"
@@ -449,6 +516,9 @@ msgstr "Empty work centers"
msgid "End Operations"
msgstr "End Operations"
+msgid "Enter each job's value, or fill every job at once from the first row. Empty rows are skipped."
+msgstr "Enter each job's value, or fill every job at once from the first row. Empty rows are skipped."
+
#. placeholder {0}: selectedPerson.name
msgid "Enter PIN for {0}"
msgstr "Enter PIN for {0}"
@@ -465,12 +535,18 @@ msgstr "Error"
msgid "Estimated"
msgstr "Estimated"
+msgid "Every job in the batch follows these steps. Record a step for all of them at once."
+msgstr "Every job in the batch follows these steps. Record a step for all of them at once."
+
msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
msgstr "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
msgid "Expand features table"
msgstr "Expand features table"
+msgid "Expand panel"
+msgstr "Expand panel"
+
msgid "Expired"
msgstr "Expired"
@@ -511,6 +587,10 @@ msgstr "Failed to save measurement"
msgid "Failed to save result"
msgstr "Failed to save result"
+#. placeholder {0}: file.name
+msgid "Failed to upload {0}"
+msgstr "Failed to upload {0}"
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Failed to upload file: {0}"
@@ -555,6 +635,10 @@ msgstr "Finish setting up your account"
msgid "Finish with material unpicked?"
msgstr "Finish with material unpicked?"
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(batchFacts.dueDate) )
+msgid "First due {0}"
+msgstr "First due {0}"
+
msgid "Forgot to Clock Out?"
msgstr "Forgot to Clock Out?"
@@ -567,6 +651,9 @@ msgstr "Go back to operation"
msgid "Go to onboarding"
msgstr "Go to onboarding"
+msgid "Hide description"
+msgstr "Hide description"
+
msgid "How many were actually picked?"
msgstr "How many were actually picked?"
@@ -631,6 +718,9 @@ msgstr "Issue Material"
msgid "Issue Type"
msgstr "Issue Type"
+msgid "Issued"
+msgstr "Issued"
+
msgid "Issued {issuedQuantity} of {lotLabel}"
msgstr "Issued {issuedQuantity} of {lotLabel}"
@@ -688,6 +778,9 @@ msgstr "lines"
msgid "List view"
msgstr "List view"
+msgid "Load list"
+msgstr "Load list"
+
msgid "Loading item details..."
msgstr "Loading item details..."
@@ -700,6 +793,9 @@ msgstr "Local"
msgid "Location"
msgstr "Location"
+msgid "Log completed"
+msgstr "Log completed"
+
msgid "Log Completed"
msgstr "Log Completed"
@@ -727,6 +823,12 @@ msgstr "Login"
msgid "Lot"
msgstr "Lot"
+msgid "Lot numbers missing"
+msgstr "Lot numbers missing"
+
+msgid "Lot tracked"
+msgstr "Lot tracked"
+
msgid "Machine"
msgstr "Machine"
@@ -763,6 +865,9 @@ msgstr "matches"
msgid "Materials"
msgstr "Materials"
+msgid "Materials issued"
+msgstr "Materials issued"
+
msgid "Maximum number of records reached"
msgstr "Maximum number of records reached"
@@ -866,6 +971,9 @@ msgstr "No matches. Type to create one."
msgid "No materials"
msgstr "No materials"
+msgid "No materials on this batch."
+msgstr "No materials on this batch."
+
msgid "No open jobs"
msgstr "No open jobs"
@@ -959,9 +1067,22 @@ msgstr "OEE Impact"
msgid "OEM Required"
msgstr "OEM Required"
+#. placeholder {0}: m.operationQuantity ?? 0
+msgid "of {0}"
+msgstr "of {0}"
+
msgid "Oldest first"
msgstr "Oldest first"
+msgid "one combined lot · planned"
+msgstr "one combined lot · planned"
+
+msgid "one per job · planned"
+msgstr "one per job · planned"
+
+msgid "One pick covers the whole batch — it is shared out to the jobs automatically."
+msgstr "One pick covers the whole batch — it is shared out to the jobs automatically."
+
#. placeholder {0}: batch.quantity
msgid "Only {0} available"
msgstr "Only {0} available"
@@ -975,6 +1096,9 @@ msgstr "Open"
msgid "Open a display on the screen mounted at the work center and leave it running. Each board refreshes on its own."
msgstr "Open a display on the screen mounted at the work center and leave it running. Each board refreshes on its own."
+msgid "Open a job in this batch"
+msgstr "Open a job in this batch"
+
msgid "Open an NCR for MRB disposition"
msgstr "Open an NCR for MRB disposition"
@@ -999,6 +1123,9 @@ msgstr "Optional"
msgid "or"
msgstr "or"
+msgid "Output lot"
+msgstr "Output lot"
+
msgid "Overall result"
msgstr "Overall result"
@@ -1017,6 +1144,9 @@ msgstr "Partial"
msgid "Partial Disposition"
msgstr "Partial Disposition"
+msgid "Passed inspection"
+msgstr "Passed inspection"
+
msgid "Passed Inspection"
msgstr "Passed Inspection"
@@ -1029,6 +1159,10 @@ msgstr "Pause"
msgid "Pick"
msgstr "Pick"
+#. placeholder {0}: m.required - m.issued
+msgid "Pick {0}"
+msgstr "Pick {0}"
+
msgid "Pick tracked item"
msgstr "Pick tracked item"
@@ -1098,6 +1232,9 @@ msgstr "Procedure"
msgid "Process"
msgstr "Process"
+msgid "Process parameters"
+msgstr "Process parameters"
+
msgid "Process Parameters"
msgstr "Process Parameters"
@@ -1140,18 +1277,28 @@ msgstr "Record"
msgid "Record {0}"
msgstr "Record {0}"
+#. placeholder {0}: changed.length
+msgid "Record {0} jobs"
+msgstr "Record {0} jobs"
+
msgid "Record only"
msgstr "Record only"
msgid "Record Partial"
msgstr "Record Partial"
+msgid "Recorded"
+msgstr "Recorded"
+
msgid "Reject"
msgstr "Reject"
msgid "Reject Lot"
msgstr "Reject Lot"
+msgid "Released"
+msgstr "Released"
+
msgid "Remove"
msgstr "Remove"
@@ -1167,6 +1314,9 @@ msgstr "Remove part"
msgid "Reopen the subassembly and create a replacement unit"
msgstr "Reopen the subassembly and create a replacement unit"
+msgid "Required"
+msgstr "Required"
+
msgid "Result"
msgstr "Result"
@@ -1188,6 +1338,9 @@ msgstr "Running"
msgid "Sales Order"
msgstr "Sales Order"
+msgid "Same for every job"
+msgstr "Same for every job"
+
msgid "Save"
msgstr "Save"
@@ -1307,6 +1460,9 @@ msgstr "Send"
msgid "Send to Carbon"
msgstr "Send to Carbon"
+msgid "Separate lots"
+msgstr "Separate lots"
+
msgid "Serial"
msgstr "Serial"
@@ -1326,6 +1482,9 @@ msgstr "Serial numbers"
msgid "Serial Numbers"
msgstr "Serial Numbers"
+msgid "Serialized"
+msgstr "Serialized"
+
msgid "Session locked"
msgstr "Session locked"
@@ -1338,6 +1497,9 @@ msgstr "Set clock-out time"
msgid "Set up in Carbon"
msgstr "Set up in Carbon"
+msgid "Set when the batch was planned."
+msgstr "Set when the batch was planned."
+
msgid "Setup"
msgstr "Setup"
@@ -1350,6 +1512,9 @@ msgstr "Short"
msgid "Short pick {itemName}"
msgstr "Short pick {itemName}"
+msgid "Show description"
+msgstr "Show description"
+
msgid "Show this overlay"
msgstr "Show this overlay"
@@ -1389,6 +1554,10 @@ msgstr "Spare Parts Used"
msgid "Start"
msgstr "Start"
+#. placeholder {0}: workTypeLabels[ eventType.toLowerCase() as keyof typeof workTypeLabels ].toLowerCase()
+msgid "Start {0}"
+msgstr "Start {0}"
+
msgid "Start or pause the operation"
msgstr "Start or pause the operation"
@@ -1438,12 +1607,22 @@ msgstr "Tag"
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
+msgid "The jobs and parts that make up this run."
+msgstr "The jobs and parts that make up this run."
+
+msgid "The jobs make different items — keep each job's parts apart."
+msgstr "The jobs make different items — keep each job's parts apart."
+
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
+#. placeholder {0}: (batch.operations ?? []).length
+msgid "The timer and completion are shared by all {0} jobs. Steps, materials and files here are this job's own."
+msgstr "The timer and completion are shared by all {0} jobs. Steps, materials and files here are this job's own."
+
msgid "There are no available or consumed tracked parts for this material."
msgstr "There are no available or consumed tracked parts for this material."
@@ -1453,6 +1632,9 @@ msgstr "There are serial or batch tracked materials on the bill of material that
msgid "These items still have material to pick. Finishing now marks the list Partial."
msgstr "These items still have material to pick. Finishing now marks the list Partial."
+msgid "This batch has no work instructions."
+msgstr "This batch has no work instructions."
+
msgid "This lot is expired and can't be picked."
msgstr "This lot is expired and can't be picked."
@@ -1468,6 +1650,9 @@ msgstr "This unit will be permanently scrapped and a replacement serial number w
msgid "Thumbnail"
msgstr "Thumbnail"
+msgid "Tick the jobs this was done for."
+msgstr "Tick the jobs this was done for."
+
msgid "Time and cost split across jobs proportionally to quantity."
msgstr "Time and cost split across jobs proportionally to quantity."
@@ -1478,6 +1663,12 @@ msgstr "Time Entries"
msgid "Time Worked: {0}"
msgstr "Time Worked: {0}"
+msgid "To pick"
+msgstr "To pick"
+
+msgid "To run"
+msgstr "To run"
+
msgid "Today"
msgstr "Today"
@@ -1487,6 +1678,9 @@ msgstr "Toggle the sidebar"
msgid "Tools"
msgstr "Tools"
+msgid "Total"
+msgstr "Total"
+
msgid "Total Quantity"
msgstr "Total Quantity"
@@ -1501,6 +1695,9 @@ msgstr "Total: {0}"
msgid "Tracked Entity"
msgstr "Tracked Entity"
+msgid "tracked lines"
+msgstr "tracked lines"
+
msgid "Tracking"
msgstr "Tracking"
@@ -1572,6 +1769,12 @@ msgstr "Uploading {0}"
msgid "Use a different account"
msgstr "Use a different account"
+msgid "Used automatically at completion"
+msgstr "Used automatically at completion"
+
+msgid "Value"
+msgstr "Value"
+
msgid "Verify"
msgstr "Verify"
@@ -1584,6 +1787,9 @@ msgstr "We've sent you a magic link to sign in to your account."
msgid "What is {translatedTerm}?"
msgstr "What is {translatedTerm}?"
+msgid "Whole batch"
+msgstr "Whole batch"
+
msgid "WIP"
msgstr "WIP"
@@ -1593,6 +1799,9 @@ msgstr "Work Center"
msgid "Work Center Displays"
msgstr "Work Center Displays"
+msgid "Work instructions"
+msgstr "Work instructions"
+
msgid "Yes"
msgstr "Yes"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index aae0b07f8f..c3fe27a3be 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -111,6 +111,10 @@ msgstr "{0} eliminado correctamente"
msgid "{0} draft journal entries"
msgstr "{0} asientos de diario en borrador"
+#. placeholder {0}: op.description
+msgid "{0} has no supplier"
+msgstr ""
+
#. placeholder {0}: formatter.format(onHand)
#. placeholder {1}: formatter.format(assembliesInStock)
#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
@@ -141,6 +145,10 @@ msgstr "{0} de {1} cuentas de contabilización asignadas"
msgid "{0} of {maxSlots} provider slots used"
msgstr "{0} de {maxSlots} espacios de proveedor utilizados"
+#. placeholder {0}: pendingJobs.length
+msgid "{0} of {memberCount} member jobs are not completed yet — their output stays out of stock until each job is completed."
+msgstr "{0} de {memberCount} órdenes de trabajo aún no están completadas — su producción permanece sin existencias hasta que cada orden de trabajo esté completada."
+
#. placeholder {0}: selected.length
msgid "{0} operations · {totalQuantity} parts"
msgstr "{0} operaciones · {totalQuantity} piezas"
@@ -1652,6 +1660,10 @@ msgstr "Todos los artículos"
msgid "All Locations"
msgstr "Todas las Ubicaciones"
+#. placeholder {0}: tracked[0]?.itemReadableId ?? ""
+msgid "all make {0}"
+msgstr "todos fabricados {0}"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "Todos los miembros de los grupos seleccionados e individuos seleccionados podrán aprobar solicitudes"
@@ -3550,6 +3562,9 @@ msgstr "Revisa tu correo electrónico"
msgid "Checking Stripe for this customer…"
msgstr "Verificando Stripe para este cliente…"
+msgid "Checking the batch's jobs..."
+msgstr "Comprobando las órdenes de trabajo del lote de producción..."
+
msgid "Checkpoint ·"
msgstr "Punto de control ·"
@@ -3574,6 +3589,10 @@ msgstr "Elija una fila a la izquierda para ver de dónde puede provenir su stock
msgid "Choose a serial number"
msgstr "Elige un número de serie"
+#. placeholder {0}: op.description
+msgid "choose a supplier for {0} on the job"
+msgstr ""
+
msgid "Choose another file"
msgstr "Elegir otro archivo"
@@ -3736,6 +3755,9 @@ msgstr "Columnas"
msgid "Combine filters"
msgstr "Combinar filtros"
+msgid "Combine output into one lot"
+msgstr "Combinar la salida en un lote"
+
msgid "Coming soon"
msgstr "Próximamente"
@@ -4526,6 +4548,9 @@ msgstr "Crear {0} valores"
msgid "Create & Release"
msgstr "Crear y Liberar"
+msgid "Create & release batch"
+msgstr "Crear y liberar lote de producción"
+
msgid "Create & Snapshot"
msgstr "Crear y Capturar"
@@ -4598,6 +4623,9 @@ msgstr "Crear órdenes de trabajo"
msgid "Create Kanban"
msgstr "Crear Kanban"
+msgid "Create New"
+msgstr "Crear nuevo"
+
msgid "Create new rule"
msgstr "Crear nueva regla"
@@ -6269,6 +6297,12 @@ msgstr "p. ej. Zebra 2x1"
msgid "Each cell is the people assigned against the people the day's work needs."
msgstr "Cada celda muestra las personas asignadas frente a las personas que el trabajo del día necesita."
+msgid "Each job keeps its own lot. The shop floor can't change these."
+msgstr "Cada orden de trabajo mantiene su propio lote. La planta no puede cambiar estos."
+
+msgid "Each job needs its own lot number — or combine them into one lot."
+msgstr "Cada orden de trabajo necesita su propio número de lote — o combinarlos en un lote."
+
msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."
msgstr "Cada línea es un vínculo de los datos de esta empresa a una fila que no posee. Una copia de seguridad con estas filas nunca podría restaurarse."
@@ -6281,6 +6315,9 @@ msgstr "El material no utilizado de cada operación se devuelve tan pronto como
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Cada unidad física obtiene su propia entidad rastreada y número único — una entidad, una unidad."
+msgid "Each supplier's outside operations from every job go on one new purchase order, or on an existing draft you choose."
+msgstr "Las operaciones externas de cada proveedor de cada orden de trabajo se colocan en una nueva orden de compra o en un borrador existente que elija."
+
msgid "Each, lb, ft…"
msgstr "Cada, lb, ft…"
@@ -7027,6 +7064,9 @@ msgstr "Todo lo demás"
msgid "Everything else covers people, imports, integrations and the API — anything that is not one of your workflows."
msgstr "Todo lo demás cubre personas, importaciones, integraciones y la API — cualquier cosa que no sea uno de tus flujos de trabajo."
+msgid "Everything this run makes lands in one lot. The shop floor can't change it."
+msgstr "Todo lo que esta ejecución fabrica cae en un lote. La planta no puede cambiarlo."
+
msgid "Exceeds {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB total — remove some attachments to send."
msgstr "Excede {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB en total — elimine algunos archivos adjuntos para enviar."
@@ -7804,6 +7844,9 @@ msgstr "Ajustar vista"
msgid "Fix the problems with this workflow before testing it"
msgstr "Corrige los problemas con este flujo de trabajo antes de probarlo"
+msgid "Fix these jobs before releasing"
+msgstr "Arregle estas órdenes de trabajo antes de liberar"
+
msgid "Fixed"
msgstr "Fijo"
@@ -9610,7 +9653,7 @@ msgid "Lines"
msgstr "Líneas"
msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."
-msgstr "Las líneas aparecen aquí una vez que se ha contabilizado una recepción de orden de compra, y solo para cantidades aún no autorizadas en otra devolución a proveedor. Usa Agregar Línea para una devolución ciega."
+msgstr "Las líneas aparecen aquí una vez que se ha contabilizado una recepción de orden de compra, y solo para cantidades que no estén ya autorizadas en otra devolución de proveedor. Usa Agregar artículo de línea para una devolución ciega."
msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."
msgstr "Las líneas aparecen aquí una vez que se ha contabilizado un envío de pedido de venta, y solo para cantidades no autorizadas en otro RMA. Use Agregar artículo de línea para una devolución a ciegas."
@@ -9806,6 +9849,9 @@ msgstr "Perdido"
msgid "Lot"
msgstr "Lote"
+msgid "Lot number"
+msgstr "Número de lote"
+
msgid "Lot size"
msgstr "Tamaño de lote"
@@ -9986,6 +10032,9 @@ msgstr "Número de Parte del Fabricante"
msgid "Manufacturing"
msgstr "Manufactura"
+msgid "manufacturing is blocked"
+msgstr "la manufactura está bloqueada"
+
msgid "Map accounts"
msgstr "Asignar cuentas"
@@ -10275,6 +10324,13 @@ msgstr "ID de Memorándum"
msgid "Merchant"
msgstr "Comerciante"
+#. placeholder {0}: getItemReadableId(items, itemId) ?? itemId
+msgid "Merge {0} lots"
+msgstr ""
+
+msgid "Merge output lots"
+msgstr "Fusionar lotes de salida"
+
msgid "MES"
msgstr "MES"
@@ -11264,6 +11320,10 @@ msgstr "Sin líneas de pedido de venta abiertas"
msgid "No operations found."
msgstr "No se encontraron operaciones."
+#. placeholder {0}: job.missingAssemblies .map((m) => m.description) .join(", ")
+msgid "no operations on {0}"
+msgstr "sin operaciones en {0}"
+
msgid "No operations require picking at this location"
msgstr "No se requieren operaciones de picking en esta ubicación"
@@ -13014,6 +13074,12 @@ msgstr "Procesos"
msgid "Procurement status — needs ordering, planned, on order, or received. The same indicator shown in the BoM tree."
msgstr "Estado de aprovisionamiento: requiere pedido, planificado, en pedido o recibido. El mismo indicador que se muestra en el árbol de la BoM."
+msgid "produced item"
+msgstr "artículo producido"
+
+msgid "Produced item"
+msgstr "Artículo producido"
+
msgid "Product issues during hypercare"
msgstr "Problemas de producto durante hipercare"
@@ -13923,6 +13989,11 @@ msgstr "Liberar {0} lotes de producción"
msgid "Release Batch"
msgstr "Liberar lote de producción"
+#. placeholder {0}: batch.readableId
+#. placeholder {0}: releaseTarget.readableId
+msgid "Release batch {0}"
+msgstr "Liberar lote de producción {0}"
+
msgid "Release change notice"
msgstr "Liberar aviso de cambio"
@@ -13951,6 +14022,9 @@ msgstr "Revisión lanzada"
msgid "Released revision is locked"
msgstr "La revisión lanzada está bloqueada"
+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
+msgstr "Liberar el lote de producción libera sus órdenes de trabajo, y cada una debe estar lista para la planta."
+
msgid "Remaining"
msgstr "Restante"
@@ -15822,6 +15896,10 @@ msgstr "Atajos"
msgid "Show"
msgstr "Mostrar"
+#. placeholder {0}: overflow.length
+msgid "Show {0} more"
+msgstr ""
+
msgid "Show a readable Customer ID column on the customer list, customer forms, and dropdowns. Customers are still identified internally either way."
msgstr "Mostrar una columna de ID de cliente legible en la lista de clientes, formularios de clientes y listas desplegables. Los clientes se identifican internamente de cualquier forma."
@@ -16981,6 +17059,9 @@ msgstr "El trabajo de copia de seguridad reportó este error."
msgid "The backward-computed date an operation must finish by to keep its job on time, written to the operation's due date. A stable target for measuring progress — never a constraint on placement."
msgstr "La fecha calculada hacia atrás que una operación debe finalizar para mantener su orden de trabajo a tiempo, escrita en la fecha de vencimiento de la operación. Un objetivo estable para medir el progreso — nunca una restricción en la colocación."
+msgid "The batch goes to the shop floor. Its jobs are already released."
+msgstr "El lote de producción va a la planta. Sus órdenes de trabajo ya están liberadas."
+
msgid "The batch runs at its most urgent member's time — the others are pulled early"
msgstr "El lote se ejecuta según su miembro más urgente — los demás se adelantan"
@@ -17266,6 +17347,9 @@ msgstr "El costo de inventario reconocido cuando se registra un envío, valorado
msgid "The IRS recovery-period class for this asset under MACRS (3, 5, 7, 10, 15, 20, 27.5, 39-year)."
msgstr "La clase de período de recuperación del IRS para este activo bajo MACRS (3, 5, 7, 10, 15, 20, 27.5, 39 años)."
+msgid "The item each job produces — require it to match to merge output lots"
+msgstr "El artículo que cada orden de trabajo produce — requiere que coincida para fusionar lotes de salida"
+
msgid "the job hours due that day (a due-date basis, not the day the work runs), with overdue work in Past due."
msgstr "las horas de Orden de trabajo vencidas ese día (una base de fecha de vencimiento, no el día que se ejecuta el trabajo), con trabajo Atrasado en Pasado vencido."
@@ -17800,6 +17884,11 @@ msgstr "Estas filas se vinculan a datos fuera de esta empresa, por lo que nunca
msgid "this ability"
msgstr "esta habilidad"
+#. placeholder {0}: jobIds.length
+#. placeholder {1}: jobIds.join(", ")
+msgid "This also releases {0} jobs ({1}). They become available to the shop floor and drive purchasing and production."
+msgstr "Esto también libera {0} órdenes de trabajo ({1}). Se vuelven disponibles para la planta e impulsan las compras y la producción."
+
msgid "This backup could not be completed."
msgstr "Esta copia de seguridad no se pudo completar."
diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.po
index 03f185db37..ac2081a40d 100644
--- a/packages/locale/locales/es/mes.po
+++ b/packages/locale/locales/es/mes.po
@@ -25,14 +25,28 @@ msgstr "{0} Activos"
msgid "{0} ago"
msgstr "hace {0}"
+#. placeholder {0}: batchFacts.customers.length
+msgid "{0} customers"
+msgstr ""
+
+#. placeholder {0}: unplanned .map( (m) => (m.job as { jobId?: string | null } | null)?.jobId ) .filter(Boolean) .join(", ")
+msgid "{0} has no lot number. Set it on the batch or job in Carbon, then complete."
+msgstr "{0} no tiene número de lote. Configúralo en el lote de producción u orden de trabajo en Carbon, luego completa."
+
+#. placeholder {0}: batchFacts.items.length
+msgid "{0} items"
+msgstr ""
+
#. placeholder {0}: (batch.operations ?? []).length
msgid "{0} jobs"
msgstr "{0} órdenes de trabajo"
+#. placeholder {0}: issuedLines.length
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
#. placeholder {1}: operation.targetQuantity
+#. placeholder {1}: trackedLines.length
msgid "{0} of {1}"
msgstr "{0} de {1}"
@@ -54,16 +68,28 @@ msgstr "{0} en cola"
msgid "{0} running"
msgstr "{0} en ejecución"
+#. placeholder {0}: operation.jobReadableId
+#. placeholder {1}: batch.readableId
+msgid "{0} runs in batch {1}"
+msgstr ""
+
#. placeholder {0}: item.quantityScrapped
msgid "{0} Scrapped"
msgstr "{0} Descartados"
+msgid "{completed} of {quantity}"
+msgstr "{completed} de {quantity}"
+
msgid "{completions} passed unit(s) will be completed."
msgstr "{completions} unidades superadas se completarán."
msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
msgstr "{fails} fallo(s) muestreado(s) registrado(s) y NO serán completado(s) — resuélvalo(s) desde el menú de acciones."
+#. placeholder {0}: step.perMember.length
+msgid "{recorded}/{0} jobs"
+msgstr ""
+
msgid "+{overflow} more"
msgstr "+{overflow} más"
@@ -88,6 +114,10 @@ msgstr "Configuración de cuenta"
msgid "Acknowledge & finish"
msgstr "Reconocer y finalizar"
+#. placeholder {0}: members.length
+msgid "across {0} jobs"
+msgstr "en {0} órdenes de trabajo"
+
msgid "Active"
msgstr "Activo"
@@ -118,6 +148,13 @@ msgstr "Todos"
msgid "All clear"
msgstr "Todo despejado"
+msgid "All jobs"
+msgstr "Todas las órdenes de trabajo"
+
+#. placeholder {0}: batch.outputLotNumber
+msgid "All output goes to lot <0>{0}</0>"
+msgstr "Toda la salida va al lote <0>{0}</0>"
+
msgid "All rework"
msgstr "Todo retrabajo"
@@ -166,6 +203,9 @@ msgstr "disponible"
msgid "Available"
msgstr "Disponible"
+msgid "Back to batch"
+msgstr ""
+
msgid "Batch"
msgstr "Lote"
@@ -179,12 +219,21 @@ msgstr "Número de lote {0}"
msgid "Batch number is required"
msgstr "El número de lote es obligatorio"
-msgid "Batched jobs"
-msgstr "Órdenes de trabajo agrupadas"
+msgid "Batch quantity"
+msgstr "Cantidad del lote de producción"
+
+msgid "batch total"
+msgstr "total del lote de producción"
msgid "Behind target by {daysBehindTarget} day(s)"
msgstr "Retrasado por {daysBehindTarget} día(s)"
+#. placeholder {0}: step.minValue
+#. placeholder {1}: step.maxValue
+#. placeholder {2}: step.unitOfMeasureCode ?? ""
+msgid "Between {0} and {1} {2}"
+msgstr ""
+
#. placeholder {0}: column.blockingDispatchReadableId
msgid "Blocked by {0}"
msgstr "Bloqueado por {0}"
@@ -222,6 +271,9 @@ msgstr "Chat"
msgid "Check your email"
msgstr "Revise su correo electrónico"
+msgid "Choose a job"
+msgstr ""
+
msgid "Clear"
msgstr "Limpiar"
@@ -249,6 +301,9 @@ msgstr "Cerrar"
msgid "Collapse features table"
msgstr "Contraer tabla de características"
+msgid "Collapse panel"
+msgstr "Contraer panel"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -278,6 +333,9 @@ msgstr "Completar"
msgid "Complete All"
msgstr "Completar todo"
+msgid "Complete batch"
+msgstr ""
+
msgid "Complete Batch"
msgstr "Completar Lote"
@@ -377,6 +435,9 @@ msgstr "Visualización"
msgid "Displays"
msgstr "Pantallas"
+msgid "Done"
+msgstr ""
+
msgid "Down"
msgstr "Fuera de servicio"
@@ -409,9 +470,12 @@ msgstr "Arrastra para redimensionar el dibujo y las características"
msgid "Dragging {0} cancelled."
msgstr "Se canceló el arrastre de {0}."
+msgid "Due"
+msgstr ""
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
msgid "Due {0}"
msgstr "Vence {0}"
@@ -434,6 +498,9 @@ msgstr "Número de serie duplicado"
msgid "Duration"
msgstr "Duración"
+msgid "Each job's output is its own lot — keep each job's parts apart."
+msgstr ""
+
msgid "Edit"
msgstr "Editar"
@@ -449,6 +516,9 @@ msgstr "Centros de trabajo vacíos"
msgid "End Operations"
msgstr "Finalizar operaciones"
+msgid "Enter each job's value, or fill every job at once from the first row. Empty rows are skipped."
+msgstr ""
+
#. placeholder {0}: selectedPerson.name
msgid "Enter PIN for {0}"
msgstr "Ingrese el PIN para {0}"
@@ -465,12 +535,18 @@ msgstr "Error"
msgid "Estimated"
msgstr "Estimado"
+msgid "Every job in the batch follows these steps. Record a step for all of them at once."
+msgstr ""
+
msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
msgstr "Cada unidad tiene un veredicto: {passes} superadas y {fails} rechazadas. El lote se cierra con cada unidad dirigida a su propio resultado."
msgid "Expand features table"
msgstr "Expandir tabla de características"
+msgid "Expand panel"
+msgstr "Expandir panel"
+
msgid "Expired"
msgstr "Vencido"
@@ -511,6 +587,10 @@ msgstr "Error al guardar la medición"
msgid "Failed to save result"
msgstr "Error al guardar el resultado"
+#. placeholder {0}: file.name
+msgid "Failed to upload {0}"
+msgstr ""
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Error al subir el archivo: {0}"
@@ -555,6 +635,10 @@ msgstr "Finalizar la configuración de su cuenta"
msgid "Finish with material unpicked?"
msgstr "¿Finalizar con material sin recoger?"
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(batchFacts.dueDate) )
+msgid "First due {0}"
+msgstr ""
+
msgid "Forgot to Clock Out?"
msgstr "¿Olvidó fichar salida?"
@@ -567,6 +651,9 @@ msgstr "Volver a la operación"
msgid "Go to onboarding"
msgstr "Ir a la incorporación"
+msgid "Hide description"
+msgstr ""
+
msgid "How many were actually picked?"
msgstr "¿Cuántos se recogieron realmente?"
@@ -631,6 +718,9 @@ msgstr "Emitir material"
msgid "Issue Type"
msgstr "Tipo de Problema"
+msgid "Issued"
+msgstr "Emitido"
+
msgid "Issued {issuedQuantity} of {lotLabel}"
msgstr "Emitido {issuedQuantity} de {lotLabel}"
@@ -688,6 +778,9 @@ msgstr "líneas"
msgid "List view"
msgstr "Vista de lista"
+msgid "Load list"
+msgstr ""
+
msgid "Loading item details..."
msgstr "Cargando detalles del artículo..."
@@ -700,6 +793,9 @@ msgstr "Local"
msgid "Location"
msgstr "Ubicación"
+msgid "Log completed"
+msgstr ""
+
msgid "Log Completed"
msgstr "Registrar completados"
@@ -727,6 +823,12 @@ msgstr "Iniciar sesión"
msgid "Lot"
msgstr "Lote"
+msgid "Lot numbers missing"
+msgstr "Números de lote faltantes"
+
+msgid "Lot tracked"
+msgstr ""
+
msgid "Machine"
msgstr "Máquina"
@@ -763,6 +865,9 @@ msgstr "coincide con"
msgid "Materials"
msgstr "Materiales"
+msgid "Materials issued"
+msgstr "Materiales emitidos"
+
msgid "Maximum number of records reached"
msgstr "Se alcanzó el número máximo de registros"
@@ -866,6 +971,9 @@ msgstr "Sin coincidencias. Escribe para crear una."
msgid "No materials"
msgstr "Sin materiales"
+msgid "No materials on this batch."
+msgstr "Sin materiales en este lote de producción."
+
msgid "No open jobs"
msgstr "Sin órdenes de trabajo abiertas"
@@ -959,9 +1067,22 @@ msgstr "Impacto OEE"
msgid "OEM Required"
msgstr "Requiere OEM"
+#. placeholder {0}: m.operationQuantity ?? 0
+msgid "of {0}"
+msgstr ""
+
msgid "Oldest first"
msgstr "Más antiguo primero"
+msgid "one combined lot · planned"
+msgstr "un lote combinado · planificado"
+
+msgid "one per job · planned"
+msgstr "uno por orden de trabajo · planificado"
+
+msgid "One pick covers the whole batch — it is shared out to the jobs automatically."
+msgstr ""
+
#. placeholder {0}: batch.quantity
msgid "Only {0} available"
msgstr "Solo {0} disponibles"
@@ -975,6 +1096,9 @@ msgstr "Abierto"
msgid "Open a display on the screen mounted at the work center and leave it running. Each board refreshes on its own."
msgstr "Abra una pantalla en la pantalla instalada en el centro de trabajo y déjela en ejecución. Cada tablero se actualiza automáticamente."
+msgid "Open a job in this batch"
+msgstr ""
+
msgid "Open an NCR for MRB disposition"
msgstr "Abrir un NCR para la disposición de MRB"
@@ -999,6 +1123,9 @@ msgstr "Opcional"
msgid "or"
msgstr "o"
+msgid "Output lot"
+msgstr "Lote de salida"
+
msgid "Overall result"
msgstr "Resultado general"
@@ -1017,6 +1144,9 @@ msgstr "Parcial"
msgid "Partial Disposition"
msgstr "Disposición Parcial"
+msgid "Passed inspection"
+msgstr ""
+
msgid "Passed Inspection"
msgstr "Inspección superada"
@@ -1029,6 +1159,10 @@ msgstr "Pausar"
msgid "Pick"
msgstr "Recoger"
+#. placeholder {0}: m.required - m.issued
+msgid "Pick {0}"
+msgstr "Picking {0}"
+
msgid "Pick tracked item"
msgstr "Seleccionar artículo rastreado"
@@ -1098,6 +1232,9 @@ msgstr "Procedimiento"
msgid "Process"
msgstr "Proceso"
+msgid "Process parameters"
+msgstr "Parámetros del proceso"
+
msgid "Process Parameters"
msgstr "Parámetros del proceso"
@@ -1140,18 +1277,28 @@ msgstr "Registrar"
msgid "Record {0}"
msgstr "Registro {0}"
+#. placeholder {0}: changed.length
+msgid "Record {0} jobs"
+msgstr ""
+
msgid "Record only"
msgstr "Solo registrar"
msgid "Record Partial"
msgstr "Registrar Parcial"
+msgid "Recorded"
+msgstr ""
+
msgid "Reject"
msgstr "Rechazar"
msgid "Reject Lot"
msgstr "Rechazar lote"
+msgid "Released"
+msgstr ""
+
msgid "Remove"
msgstr "Quitar"
@@ -1167,6 +1314,9 @@ msgstr "Quitar pieza"
msgid "Reopen the subassembly and create a replacement unit"
msgstr "Reabrir el subensamble y crear una unidad de reemplazo"
+msgid "Required"
+msgstr "Requerido"
+
msgid "Result"
msgstr "Resultado"
@@ -1188,6 +1338,9 @@ msgstr "En ejecución"
msgid "Sales Order"
msgstr "Pedido de venta"
+msgid "Same for every job"
+msgstr ""
+
msgid "Save"
msgstr "Guardar"
@@ -1307,6 +1460,9 @@ msgstr "Enviar"
msgid "Send to Carbon"
msgstr "Enviar a Carbon"
+msgid "Separate lots"
+msgstr "Lotes separados"
+
msgid "Serial"
msgstr "Serie"
@@ -1326,6 +1482,9 @@ msgstr "Números de serie"
msgid "Serial Numbers"
msgstr "Números de serie"
+msgid "Serialized"
+msgstr ""
+
msgid "Session locked"
msgstr "Sesión bloqueada"
@@ -1338,6 +1497,9 @@ msgstr "Establecer hora de salida"
msgid "Set up in Carbon"
msgstr "Configurar en Carbon"
+msgid "Set when the batch was planned."
+msgstr "Se establece cuando el lote de producción fue planificado."
+
msgid "Setup"
msgstr "Preparación"
@@ -1350,6 +1512,9 @@ msgstr "Faltante"
msgid "Short pick {itemName}"
msgstr "Picking corto {itemName}"
+msgid "Show description"
+msgstr ""
+
msgid "Show this overlay"
msgstr "Mostrar esta superposición"
@@ -1389,6 +1554,10 @@ msgstr "Repuestos utilizados"
msgid "Start"
msgstr "Iniciar"
+#. placeholder {0}: workTypeLabels[ eventType.toLowerCase() as keyof typeof workTypeLabels ].toLowerCase()
+msgid "Start {0}"
+msgstr ""
+
msgid "Start or pause the operation"
msgstr "Iniciar o pausar la operación"
@@ -1438,12 +1607,22 @@ msgstr "Etiqueta"
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "La cantidad completada para esta operación es menor que la cantidad requerida de {targetQuantity}."
+msgid "The jobs and parts that make up this run."
+msgstr ""
+
+msgid "The jobs make different items — keep each job's parts apart."
+msgstr ""
+
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "El lote será marcado como Superado y {remaining} unidades restantes se completarán en esta operación."
msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "El lote seguirá siendo disposicionado, pero no se puede crear un NCR hasta que se configure al menos un tipo de problema."
+#. placeholder {0}: (batch.operations ?? []).length
+msgid "The timer and completion are shared by all {0} jobs. Steps, materials and files here are this job's own."
+msgstr ""
+
msgid "There are no available or consumed tracked parts for this material."
msgstr "No hay piezas rastreadas disponibles o consumidas para este material."
@@ -1453,6 +1632,9 @@ msgstr "Hay materiales con seguimiento de serie o lote en la lista de materiales
msgid "These items still have material to pick. Finishing now marks the list Partial."
msgstr "Estos elementos aún tienen material para recoger. Finalizar ahora marca la lista como Parcial."
+msgid "This batch has no work instructions."
+msgstr ""
+
msgid "This lot is expired and can't be picked."
msgstr "Este lote está vencido y no puede ser preparado."
@@ -1468,6 +1650,9 @@ msgstr "Esta unidad será descartada permanentemente y se creará un nuevo núme
msgid "Thumbnail"
msgstr "Miniatura"
+msgid "Tick the jobs this was done for."
+msgstr ""
+
msgid "Time and cost split across jobs proportionally to quantity."
msgstr "El tiempo y el costo se distribuyen entre las órdenes de trabajo proporcionalmente a la cantidad."
@@ -1478,6 +1663,12 @@ msgstr "Registros de tiempo"
msgid "Time Worked: {0}"
msgstr "Tiempo trabajado: {0}"
+msgid "To pick"
+msgstr ""
+
+msgid "To run"
+msgstr ""
+
msgid "Today"
msgstr "Hoy"
@@ -1487,6 +1678,9 @@ msgstr "Alternar la barra lateral"
msgid "Tools"
msgstr "Herramientas"
+msgid "Total"
+msgstr ""
+
msgid "Total Quantity"
msgstr "Cantidad total"
@@ -1501,6 +1695,9 @@ msgstr "Total: {0}"
msgid "Tracked Entity"
msgstr "Entidad rastreada"
+msgid "tracked lines"
+msgstr "líneas rastreadas"
+
msgid "Tracking"
msgstr "Seguimiento"
@@ -1572,6 +1769,12 @@ msgstr "Subiendo {0}"
msgid "Use a different account"
msgstr "Usar una cuenta diferente"
+msgid "Used automatically at completion"
+msgstr ""
+
+msgid "Value"
+msgstr ""
+
msgid "Verify"
msgstr "Verificar"
@@ -1584,6 +1787,9 @@ msgstr "Le hemos enviado un enlace mágico para iniciar sesión en su cuenta."
msgid "What is {translatedTerm}?"
msgstr "¿Qué es {translatedTerm}?"
+msgid "Whole batch"
+msgstr "Todo el lote de producción"
+
msgid "WIP"
msgstr "Producto en proceso"
@@ -1593,6 +1799,9 @@ msgstr "Centro de trabajo"
msgid "Work Center Displays"
msgstr "Pantallas del Centro de Trabajo"
+msgid "Work instructions"
+msgstr "Instrucciones de trabajo"
+
msgid "Yes"
msgstr "Sí"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 6c6d6a747a..b170b0759b 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -111,6 +111,10 @@ msgstr "{0} supprimé avec succès"
msgid "{0} draft journal entries"
msgstr "{0} écritures de journal brouillon"
+#. placeholder {0}: op.description
+msgid "{0} has no supplier"
+msgstr ""
+
#. placeholder {0}: formatter.format(onHand)
#. placeholder {1}: formatter.format(assembliesInStock)
#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
@@ -141,6 +145,10 @@ msgstr "{0} sur {1} comptes de comptabilisation mappés"
msgid "{0} of {maxSlots} provider slots used"
msgstr "{0} sur {maxSlots} emplacements de fournisseur utilisés"
+#. placeholder {0}: pendingJobs.length
+msgid "{0} of {memberCount} member jobs are not completed yet — their output stays out of stock until each job is completed."
+msgstr "{0} de {memberCount} ordres de fabrication ne sont pas encore terminés — leur production reste hors du stock jusqu'à ce que chaque ordre soit terminé."
+
#. placeholder {0}: selected.length
msgid "{0} operations · {totalQuantity} parts"
msgstr "{0} opérations · {totalQuantity} pièces"
@@ -1652,6 +1660,10 @@ msgstr "Tous les articles"
msgid "All Locations"
msgstr "Tous les Emplacements"
+#. placeholder {0}: tracked[0]?.itemReadableId ?? ""
+msgid "all make {0}"
+msgstr "Tous font {0}"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "Tous les membres des groupes sélectionnés et les individus sélectionnés pourront approuver les demandes"
@@ -3550,6 +3562,9 @@ msgstr "Vérifiez votre email"
msgid "Checking Stripe for this customer…"
msgstr "Vérification de Stripe pour ce client…"
+msgid "Checking the batch's jobs..."
+msgstr "Vérification des ordres de fabrication du lot de production..."
+
msgid "Checkpoint ·"
msgstr "Point de contrôle ·"
@@ -3574,6 +3589,10 @@ msgstr "Choisissez une ligne à gauche pour voir d'où son stock peut provenir."
msgid "Choose a serial number"
msgstr "Choisir un numéro de série"
+#. placeholder {0}: op.description
+msgid "choose a supplier for {0} on the job"
+msgstr ""
+
msgid "Choose another file"
msgstr "Choisir un autre fichier"
@@ -3736,6 +3755,9 @@ msgstr "Colonnes"
msgid "Combine filters"
msgstr "Combiner les filtres"
+msgid "Combine output into one lot"
+msgstr "Combiner la sortie en un lot unique"
+
msgid "Coming soon"
msgstr "Bientôt disponible"
@@ -4526,6 +4548,9 @@ msgstr "Créer {0} valeurs"
msgid "Create & Release"
msgstr "Créer et Lancer"
+msgid "Create & release batch"
+msgstr "Créer et lancer le lot de production"
+
msgid "Create & Snapshot"
msgstr "Créer et capturer"
@@ -4598,6 +4623,9 @@ msgstr "Créer des ordres de fabrication"
msgid "Create Kanban"
msgstr "Créer Kanban"
+msgid "Create New"
+msgstr "Créer nouveau"
+
msgid "Create new rule"
msgstr "Créer une nouvelle règle"
@@ -6269,6 +6297,12 @@ msgstr "p. ex. Zebra 2x1"
msgid "Each cell is the people assigned against the people the day's work needs."
msgstr "Chaque cellule affiche les personnes assignées par rapport aux personnes que le travail du jour nécessite."
+msgid "Each job keeps its own lot. The shop floor can't change these."
+msgstr "Chaque ordre de fabrication garde son propre lot. L'atelier ne peut pas modifier ceux-ci."
+
+msgid "Each job needs its own lot number — or combine them into one lot."
+msgstr "Chaque ordre de fabrication a besoin de son propre numéro de lot — ou les combiner en un lot unique."
+
msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."
msgstr "Chaque ligne est un lien entre les données de cette Société et une ligne qu'elle ne possède pas. Une sauvegarde avec ces lignes ne pourrait jamais être restaurée."
@@ -6281,6 +6315,9 @@ msgstr "La matière inutilisée de chaque opération est restituée dès que l'o
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Chaque unité physique obtient sa propre entité suivie et un numéro unique — une entité, une unité."
+msgid "Each supplier's outside operations from every job go on one new purchase order, or on an existing draft you choose."
+msgstr "Les opérations externalisées de chaque fournisseur de chaque ordre de fabrication vont sur un nouveau bon de commande, ou sur un brouillon existant que vous choisissez."
+
msgid "Each, lb, ft…"
msgstr "Chacun, lb, ft…"
@@ -7027,6 +7064,9 @@ msgstr "Tout le reste"
msgid "Everything else covers people, imports, integrations and the API — anything that is not one of your workflows."
msgstr "Tout le reste couvre les personnes, les importations, les intégrations et l'API — tout ce qui n'est pas l'un de vos flux de travail."
+msgid "Everything this run makes lands in one lot. The shop floor can't change it."
+msgstr "Tout ce que cette exécution fabrique se retrouve dans un lot. L'atelier ne peut pas le modifier."
+
msgid "Exceeds {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB total — remove some attachments to send."
msgstr "Dépasse {PO_EMAIL_ATTACHMENT_LIMIT_MB} Mo au total — supprimez certaines pièces jointes pour envoyer."
@@ -7804,6 +7844,9 @@ msgstr "Ajuster la vue"
msgid "Fix the problems with this workflow before testing it"
msgstr "Résolvez les problèmes avec ce flux de travail avant de le tester"
+msgid "Fix these jobs before releasing"
+msgstr "Corrigez ces ordres de fabrication avant de lancer"
+
msgid "Fixed"
msgstr "Fixe"
@@ -9610,7 +9653,7 @@ msgid "Lines"
msgstr "Lignes"
msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."
-msgstr "Les lignes apparaissent ici une fois qu'une réception de bon de commande a été comptabilisée, et uniquement pour les quantités non déjà autorisées sur un autre retour fournisseur. Utilisez Ajouter une ligne pour un retour aveugle."
+msgstr "Les lignes apparaissent ici une fois qu'une réception de bon de commande a été comptabilisée, et uniquement pour les quantités non déjà autorisées sur un autre retour fournisseur. Utilisez Ajouter un article de ligne pour un retour en aveugle."
msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."
msgstr "Les lignes apparaissent ici une fois qu'une expédition de commande client a été comptabilisée, et uniquement pour les quantités non déjà autorisées sur un autre RMA. Utilisez Ajouter article de ligne pour un retour en aveugle."
@@ -9806,6 +9849,9 @@ msgstr "Perdu"
msgid "Lot"
msgstr "Lot"
+msgid "Lot number"
+msgstr "Numéro de lot"
+
msgid "Lot size"
msgstr "Taille de lot"
@@ -9986,6 +10032,9 @@ msgstr "Numéro de pièce du fabricant"
msgid "Manufacturing"
msgstr "Production"
+msgid "manufacturing is blocked"
+msgstr "la production est bloquée"
+
msgid "Map accounts"
msgstr "Mapper les comptes"
@@ -10275,6 +10324,13 @@ msgstr "ID du mémo"
msgid "Merchant"
msgstr "Commerçant"
+#. placeholder {0}: getItemReadableId(items, itemId) ?? itemId
+msgid "Merge {0} lots"
+msgstr ""
+
+msgid "Merge output lots"
+msgstr "Fusionner les lots de sortie"
+
msgid "MES"
msgstr "MES"
@@ -11264,6 +11320,10 @@ msgstr "Aucune ligne de commande client ouverte"
msgid "No operations found."
msgstr "Aucune opération trouvée."
+#. placeholder {0}: job.missingAssemblies .map((m) => m.description) .join(", ")
+msgid "no operations on {0}"
+msgstr "pas d'opérations sur {0}"
+
msgid "No operations require picking at this location"
msgstr "Aucune opération ne nécessite de prélèvement à cet endroit"
@@ -13014,6 +13074,12 @@ msgstr "Processus"
msgid "Procurement status — needs ordering, planned, on order, or received. The same indicator shown in the BoM tree."
msgstr "Statut d'approvisionnement — à commander, planifié, commandé ou reçu. Le même indicateur que celui affiché dans l'arborescence de la BoM."
+msgid "produced item"
+msgstr "article produit"
+
+msgid "Produced item"
+msgstr "Article produit"
+
msgid "Product issues during hypercare"
msgstr "Problèmes de produit pendant l'hypercare"
@@ -13923,6 +13989,11 @@ msgstr "Lancer {0} lots de production"
msgid "Release Batch"
msgstr "Lancer le lot de production"
+#. placeholder {0}: batch.readableId
+#. placeholder {0}: releaseTarget.readableId
+msgid "Release batch {0}"
+msgstr "Lancer le lot de production {0}"
+
msgid "Release change notice"
msgstr "Lancer l'avis de modification"
@@ -13951,6 +14022,9 @@ msgstr "Révision publiée"
msgid "Released revision is locked"
msgstr "La révision publiée est verrouillée"
+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
+msgstr "Lancer le lot de production lance ses ordres de fabrication, et chacun doit être prêt pour l'atelier."
+
msgid "Remaining"
msgstr "Restant"
@@ -15074,7 +15148,7 @@ msgid "Search by linear issue title..."
msgstr "Rechercher par titre de problème linear..."
msgid "Search by receipt, PO, or item"
-msgstr "Rechercher par réception, bon de commande ou article"
+msgstr "Rechercher par réception, bon de commande, ou article"
msgid "Search by shipment, sales order, or item"
msgstr "Rechercher par expédition, commande client ou article"
@@ -15523,7 +15597,7 @@ msgid "Session locked"
msgstr "Session verrouillée"
msgid "Set a customer on this return to add from a shipment."
-msgstr "Définissez un client pour ce retour afin d'ajouter depuis une expédition."
+msgstr "Définissez un client sur ce retour pour ajouter depuis une expédition."
msgid "Set a supplier on this return to add from a receipt."
msgstr "Définir un fournisseur sur ce retour pour ajouter à partir d'une réception."
@@ -15822,6 +15896,10 @@ msgstr "Raccourcis"
msgid "Show"
msgstr "Afficher"
+#. placeholder {0}: overflow.length
+msgid "Show {0} more"
+msgstr ""
+
msgid "Show a readable Customer ID column on the customer list, customer forms, and dropdowns. Customers are still identified internally either way."
msgstr "Afficher une colonne ID client lisible sur la liste des clients, les formulaires clients et les listes déroulantes. Les clients sont toujours identifiés en interne de toute façon."
@@ -16981,6 +17059,9 @@ msgstr "Le travail de sauvegarde a signalé cette erreur."
msgid "The backward-computed date an operation must finish by to keep its job on time, written to the operation's due date. A stable target for measuring progress — never a constraint on placement."
msgstr "La date calculée rétroactivement à laquelle une opération doit être terminée pour que son ordre de fabrication soit à l'heure, écrite à la date d'échéance de l'opération. Une cible stable pour mesurer la progression — jamais une contrainte de placement."
+msgid "The batch goes to the shop floor. Its jobs are already released."
+msgstr "Le lot de production va à l'atelier. Ses ordres de fabrication sont déjà lancés."
+
msgid "The batch runs at its most urgent member's time — the others are pulled early"
msgstr "Le lot s'exécute au rythme de son membre le plus urgent — les autres sont avancés"
@@ -17266,6 +17347,9 @@ msgstr "Le coût reconnu lors de la comptabilisation d'une expédition, évalué
msgid "The IRS recovery-period class for this asset under MACRS (3, 5, 7, 10, 15, 20, 27.5, 39-year)."
msgstr "La classe de période de récupération IRS pour cet actif selon MACRS (3, 5, 7, 10, 15, 20, 27,5, 39 ans)."
+msgid "The item each job produces — require it to match to merge output lots"
+msgstr "L'article que chaque ordre de fabrication produit — exiger qu'il corresponde pour fusionner les lots de sortie"
+
msgid "the job hours due that day (a due-date basis, not the day the work runs), with overdue work in Past due."
msgstr "les heures de travail dues ce jour-là (selon la date d'échéance, pas le jour où le travail s'exécute), avec le travail en retard en Retard."
@@ -17800,6 +17884,11 @@ msgstr "Ces lignes sont liées à des données en dehors de cette société, don
msgid "this ability"
msgstr "cette compétence"
+#. placeholder {0}: jobIds.length
+#. placeholder {1}: jobIds.join(", ")
+msgid "This also releases {0} jobs ({1}). They become available to the shop floor and drive purchasing and production."
+msgstr "Cela lance aussi {0} ordres de fabrication ({1}). Ils deviennent disponibles pour l'atelier et pilotent les achats et la production."
+
msgid "This backup could not be completed."
msgstr "Cette sauvegarde n'a pas pu être complétée."
diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.po
index 4a3c3a4f7e..5c4e0088d1 100644
--- a/packages/locale/locales/fr/mes.po
+++ b/packages/locale/locales/fr/mes.po
@@ -25,14 +25,28 @@ msgstr "{0} Actif(s)"
msgid "{0} ago"
msgstr "il y a {0}"
+#. placeholder {0}: batchFacts.customers.length
+msgid "{0} customers"
+msgstr ""
+
+#. placeholder {0}: unplanned .map( (m) => (m.job as { jobId?: string | null } | null)?.jobId ) .filter(Boolean) .join(", ")
+msgid "{0} has no lot number. Set it on the batch or job in Carbon, then complete."
+msgstr "{0} n'a pas de numéro de lot. Définissez-le sur le lot de production ou l'ordre de fabrication dans Carbon, puis terminez."
+
+#. placeholder {0}: batchFacts.items.length
+msgid "{0} items"
+msgstr ""
+
#. placeholder {0}: (batch.operations ?? []).length
msgid "{0} jobs"
msgstr "{0} ordres de fabrication"
+#. placeholder {0}: issuedLines.length
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
#. placeholder {1}: operation.targetQuantity
+#. placeholder {1}: trackedLines.length
msgid "{0} of {1}"
msgstr "{0} sur {1}"
@@ -54,16 +68,28 @@ msgstr "{0} en file d'attente"
msgid "{0} running"
msgstr "{0} en cours"
+#. placeholder {0}: operation.jobReadableId
+#. placeholder {1}: batch.readableId
+msgid "{0} runs in batch {1}"
+msgstr ""
+
#. placeholder {0}: item.quantityScrapped
msgid "{0} Scrapped"
msgstr "{0} Rebuté(s)"
+msgid "{completed} of {quantity}"
+msgstr "{completed} sur {quantity}"
+
msgid "{completions} passed unit(s) will be completed."
msgstr "{completions} unité(s) réussie(s) seront terminées."
msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
msgstr "{fails} défaut(s) échantillonné(s) enregistré(s) et ne seront PAS complété(s) — résolvez-les à partir du menu des actions."
+#. placeholder {0}: step.perMember.length
+msgid "{recorded}/{0} jobs"
+msgstr ""
+
msgid "+{overflow} more"
msgstr "+{overflow} autres"
@@ -88,6 +114,10 @@ msgstr "Paramètres du compte"
msgid "Acknowledge & finish"
msgstr "Reconnaître et terminer"
+#. placeholder {0}: members.length
+msgid "across {0} jobs"
+msgstr "sur {0} ordres de fabrication"
+
msgid "Active"
msgstr "Actif"
@@ -118,6 +148,13 @@ msgstr "Tout"
msgid "All clear"
msgstr "Tout est correct"
+msgid "All jobs"
+msgstr "Tous les ordres de fabrication"
+
+#. placeholder {0}: batch.outputLotNumber
+msgid "All output goes to lot <0>{0}</0>"
+msgstr "Toute la sortie va au lot <0>{0}</0>"
+
msgid "All rework"
msgstr "Tous les retouches"
@@ -166,6 +203,9 @@ msgstr "disponible"
msgid "Available"
msgstr "Disponible"
+msgid "Back to batch"
+msgstr ""
+
msgid "Batch"
msgstr "Lot"
@@ -179,12 +219,21 @@ msgstr "Numéro de lot {0}"
msgid "Batch number is required"
msgstr "Le numéro de lot est requis"
-msgid "Batched jobs"
-msgstr "Ordres de fabrication regroupés"
+msgid "Batch quantity"
+msgstr "Quantité du lot de production"
+
+msgid "batch total"
+msgstr "total du lot de production"
msgid "Behind target by {daysBehindTarget} day(s)"
msgstr "En retard de {daysBehindTarget} jour(s)"
+#. placeholder {0}: step.minValue
+#. placeholder {1}: step.maxValue
+#. placeholder {2}: step.unitOfMeasureCode ?? ""
+msgid "Between {0} and {1} {2}"
+msgstr ""
+
#. placeholder {0}: column.blockingDispatchReadableId
msgid "Blocked by {0}"
msgstr "Bloqué par {0}"
@@ -222,6 +271,9 @@ msgstr "Discussion"
msgid "Check your email"
msgstr "Vérifiez votre e-mail"
+msgid "Choose a job"
+msgstr ""
+
msgid "Clear"
msgstr "Effacer"
@@ -249,6 +301,9 @@ msgstr "Fermer"
msgid "Collapse features table"
msgstr "Réduire le tableau des caractéristiques"
+msgid "Collapse panel"
+msgstr "Réduire le panneau"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -278,6 +333,9 @@ msgstr "Terminé"
msgid "Complete All"
msgstr "Tout compléter"
+msgid "Complete batch"
+msgstr ""
+
msgid "Complete Batch"
msgstr "Terminer le lot"
@@ -377,6 +435,9 @@ msgstr "Affichage"
msgid "Displays"
msgstr "Affichages"
+msgid "Done"
+msgstr ""
+
msgid "Down"
msgstr "En panne"
@@ -409,9 +470,12 @@ msgstr "Faites glisser pour redimensionner le dessin et les caractéristiques"
msgid "Dragging {0} cancelled."
msgstr "Déplacement de {0} annulé."
+msgid "Due"
+msgstr ""
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
msgid "Due {0}"
msgstr "Échéance {0}"
@@ -434,6 +498,9 @@ msgstr "Numéro de série en doublon"
msgid "Duration"
msgstr "Durée"
+msgid "Each job's output is its own lot — keep each job's parts apart."
+msgstr ""
+
msgid "Edit"
msgstr "Modifier"
@@ -449,6 +516,9 @@ msgstr "Postes de travail vides"
msgid "End Operations"
msgstr "Arrêter les opérations"
+msgid "Enter each job's value, or fill every job at once from the first row. Empty rows are skipped."
+msgstr ""
+
#. placeholder {0}: selectedPerson.name
msgid "Enter PIN for {0}"
msgstr "Saisir le NIP pour {0}"
@@ -465,12 +535,18 @@ msgstr "Erreur"
msgid "Estimated"
msgstr "Estimé"
+msgid "Every job in the batch follows these steps. Record a step for all of them at once."
+msgstr ""
+
msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
msgstr "Chaque unité a un verdict : {passes} réussie(s) et {fails} échouée(s). Le lot se ferme avec chaque unité acheminée vers son propre résultat."
msgid "Expand features table"
msgstr "Développer le tableau des caractéristiques"
+msgid "Expand panel"
+msgstr "Agrandir le panneau"
+
msgid "Expired"
msgstr "Expiré"
@@ -511,6 +587,10 @@ msgstr "Échec de l'enregistrement de la mesure"
msgid "Failed to save result"
msgstr "Échec de l'enregistrement du résultat"
+#. placeholder {0}: file.name
+msgid "Failed to upload {0}"
+msgstr ""
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Échec du téléversement du fichier : {0}"
@@ -555,6 +635,10 @@ msgstr "Terminez la configuration de votre compte"
msgid "Finish with material unpicked?"
msgstr "Terminer avec du matériel non prélevé?"
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(batchFacts.dueDate) )
+msgid "First due {0}"
+msgstr ""
+
msgid "Forgot to Clock Out?"
msgstr "Avez-vous oublié le pointage fin ?"
@@ -567,6 +651,9 @@ msgstr "Revenir à l'opération"
msgid "Go to onboarding"
msgstr "Aller à l'onboarding"
+msgid "Hide description"
+msgstr ""
+
msgid "How many were actually picked?"
msgstr "Combien ont réellement été prélevés ?"
@@ -631,6 +718,9 @@ msgstr "Distribuer le matériau"
msgid "Issue Type"
msgstr "Type de problème"
+msgid "Issued"
+msgstr "Émis"
+
msgid "Issued {issuedQuantity} of {lotLabel}"
msgstr "Émis {issuedQuantity} sur {lotLabel}"
@@ -688,6 +778,9 @@ msgstr "lignes"
msgid "List view"
msgstr "Vue liste"
+msgid "Load list"
+msgstr ""
+
msgid "Loading item details..."
msgstr "Chargement des détails de l'article..."
@@ -700,6 +793,9 @@ msgstr "Local"
msgid "Location"
msgstr "Emplacement"
+msgid "Log completed"
+msgstr ""
+
msgid "Log Completed"
msgstr "Enregistrer la production"
@@ -727,6 +823,12 @@ msgstr "Connexion"
msgid "Lot"
msgstr "Lot"
+msgid "Lot numbers missing"
+msgstr "Numéros de lot manquants"
+
+msgid "Lot tracked"
+msgstr ""
+
msgid "Machine"
msgstr "Machine"
@@ -763,6 +865,9 @@ msgstr "correspond à"
msgid "Materials"
msgstr "Matériaux"
+msgid "Materials issued"
+msgstr "Matières émises"
+
msgid "Maximum number of records reached"
msgstr "Nombre maximum d'enregistrements atteint"
@@ -866,6 +971,9 @@ msgstr "Aucune correspondance. Tapez pour en créer une."
msgid "No materials"
msgstr "Aucun matériau"
+msgid "No materials on this batch."
+msgstr "Aucune matière sur ce lot de production."
+
msgid "No open jobs"
msgstr "Aucun ordre de fabrication ouvert"
@@ -959,9 +1067,22 @@ msgstr "Impact TRS"
msgid "OEM Required"
msgstr "Intervention OEM requise"
+#. placeholder {0}: m.operationQuantity ?? 0
+msgid "of {0}"
+msgstr ""
+
msgid "Oldest first"
msgstr "Le plus ancien en premier"
+msgid "one combined lot · planned"
+msgstr "un lot combiné · planifié"
+
+msgid "one per job · planned"
+msgstr "un par ordre de fabrication · planifié"
+
+msgid "One pick covers the whole batch — it is shared out to the jobs automatically."
+msgstr ""
+
#. placeholder {0}: batch.quantity
msgid "Only {0} available"
msgstr "Seulement {0} disponible(s)"
@@ -975,6 +1096,9 @@ msgstr "Ouvert"
msgid "Open a display on the screen mounted at the work center and leave it running. Each board refreshes on its own."
msgstr "Ouvrez un affichage sur l'écran installé au poste de travail et laissez-le fonctionner. Chaque tableau s'actualise automatiquement."
+msgid "Open a job in this batch"
+msgstr ""
+
msgid "Open an NCR for MRB disposition"
msgstr "Ouvrir une NCR pour le traitement du MRB"
@@ -999,6 +1123,9 @@ msgstr "Optionnel"
msgid "or"
msgstr "ou"
+msgid "Output lot"
+msgstr "Lot de sortie"
+
msgid "Overall result"
msgstr "Résultat global"
@@ -1017,6 +1144,9 @@ msgstr "Partiel"
msgid "Partial Disposition"
msgstr "Traitement partiel"
+msgid "Passed inspection"
+msgstr ""
+
msgid "Passed Inspection"
msgstr "Contrôle réussi"
@@ -1029,6 +1159,10 @@ msgstr "Mettre en pause"
msgid "Pick"
msgstr "Prélever"
+#. placeholder {0}: m.required - m.issued
+msgid "Pick {0}"
+msgstr "Prélever {0}"
+
msgid "Pick tracked item"
msgstr "Sélectionner un article suivi"
@@ -1098,6 +1232,9 @@ msgstr "Procédure"
msgid "Process"
msgstr "Processus"
+msgid "Process parameters"
+msgstr "Paramètres du procédé"
+
msgid "Process Parameters"
msgstr "Paramètres de processus"
@@ -1140,18 +1277,28 @@ msgstr "Enregistrer"
msgid "Record {0}"
msgstr "Enregistrement {0}"
+#. placeholder {0}: changed.length
+msgid "Record {0} jobs"
+msgstr ""
+
msgid "Record only"
msgstr "Enregistrer uniquement"
msgid "Record Partial"
msgstr "Enregistrer partiellement"
+msgid "Recorded"
+msgstr ""
+
msgid "Reject"
msgstr "Rejeter"
msgid "Reject Lot"
msgstr "Rejeter lot"
+msgid "Released"
+msgstr ""
+
msgid "Remove"
msgstr "Retirer"
@@ -1167,6 +1314,9 @@ msgstr "Retirer la pièce"
msgid "Reopen the subassembly and create a replacement unit"
msgstr "Rouvrir le sous-ensemble et créer une unité de remplacement"
+msgid "Required"
+msgstr "Obligatoire"
+
msgid "Result"
msgstr "Résultat"
@@ -1188,6 +1338,9 @@ msgstr "En cours"
msgid "Sales Order"
msgstr "Commande client"
+msgid "Same for every job"
+msgstr ""
+
msgid "Save"
msgstr "Enregistrer"
@@ -1307,6 +1460,9 @@ msgstr "Envoyer"
msgid "Send to Carbon"
msgstr "Envoyer à Carbon"
+msgid "Separate lots"
+msgstr "Lots distincts"
+
msgid "Serial"
msgstr "Série"
@@ -1326,6 +1482,9 @@ msgstr "Numéros de série"
msgid "Serial Numbers"
msgstr "Numéros de série"
+msgid "Serialized"
+msgstr ""
+
msgid "Session locked"
msgstr "Session verrouillée"
@@ -1338,6 +1497,9 @@ msgstr "Définir l'heure de sortie"
msgid "Set up in Carbon"
msgstr "Configurer dans Carbon"
+msgid "Set when the batch was planned."
+msgstr "Défini lors de la planification du lot de production."
+
msgid "Setup"
msgstr "Réglage"
@@ -1350,6 +1512,9 @@ msgstr "Manquant"
msgid "Short pick {itemName}"
msgstr "Prélèvement court {itemName}"
+msgid "Show description"
+msgstr ""
+
msgid "Show this overlay"
msgstr "Afficher cette superposition"
@@ -1389,6 +1554,10 @@ msgstr "Pièces de rechange utilisées"
msgid "Start"
msgstr "Démarrer"
+#. placeholder {0}: workTypeLabels[ eventType.toLowerCase() as keyof typeof workTypeLabels ].toLowerCase()
+msgid "Start {0}"
+msgstr ""
+
msgid "Start or pause the operation"
msgstr "Démarrer ou mettre en pause l'opération"
@@ -1438,12 +1607,22 @@ msgstr "Étiquette"
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "La quantité produite pour cette opération est inférieure à la quantité requise de {targetQuantity}."
+msgid "The jobs and parts that make up this run."
+msgstr ""
+
+msgid "The jobs make different items — keep each job's parts apart."
+msgstr ""
+
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "Le lot sera marqué comme Réussi et {remaining} unité(s) restante(s) seront complétées à cette opération."
msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "Le lot sera toujours dispositionné, mais un NCR ne peut pas être créé tant qu'au moins un type de problème n'est pas configuré."
+#. placeholder {0}: (batch.operations ?? []).length
+msgid "The timer and completion are shared by all {0} jobs. Steps, materials and files here are this job's own."
+msgstr ""
+
msgid "There are no available or consumed tracked parts for this material."
msgstr "Il n'y a aucune pièce traçable disponible ou consommée pour cette matière."
@@ -1453,6 +1632,9 @@ msgstr "Il existe des matériaux suivis par numéro de série ou par lot dans la
msgid "These items still have material to pick. Finishing now marks the list Partial."
msgstr "Ces articles ont encore du matériel à prélever. L'arrêt maintenant marque la liste comme Partielle."
+msgid "This batch has no work instructions."
+msgstr ""
+
msgid "This lot is expired and can't be picked."
msgstr "Ce lot est expiré et ne peut pas être prélevé."
@@ -1468,6 +1650,9 @@ msgstr "Cette unité sera définitivement mise au rebut et un nouveau numéro de
msgid "Thumbnail"
msgstr "Miniature"
+msgid "Tick the jobs this was done for."
+msgstr ""
+
msgid "Time and cost split across jobs proportionally to quantity."
msgstr "Le temps et le coût sont répartis entre les ordres de fabrication proportionnellement à la quantité."
@@ -1478,6 +1663,12 @@ msgstr "Saisies de temps"
msgid "Time Worked: {0}"
msgstr "Temps travaillé : {0}"
+msgid "To pick"
+msgstr ""
+
+msgid "To run"
+msgstr ""
+
msgid "Today"
msgstr "Aujourd'hui"
@@ -1487,6 +1678,9 @@ msgstr "Afficher/masquer la barre latérale"
msgid "Tools"
msgstr "Outils"
+msgid "Total"
+msgstr ""
+
msgid "Total Quantity"
msgstr "Quantité totale"
@@ -1501,6 +1695,9 @@ msgstr "Total : {0}"
msgid "Tracked Entity"
msgstr "Entité suivie"
+msgid "tracked lines"
+msgstr "lignes suivies"
+
msgid "Tracking"
msgstr "Suivi"
@@ -1572,6 +1769,12 @@ msgstr "Téléversement de {0}"
msgid "Use a different account"
msgstr "Utiliser un compte différent"
+msgid "Used automatically at completion"
+msgstr ""
+
+msgid "Value"
+msgstr ""
+
msgid "Verify"
msgstr "Vérifier"
@@ -1584,6 +1787,9 @@ msgstr "Nous vous avons envoyé un lien magique pour vous connecter à votre com
msgid "What is {translatedTerm}?"
msgstr "Qu'est-ce que {translatedTerm} ?"
+msgid "Whole batch"
+msgstr "Tout le lot de production"
+
msgid "WIP"
msgstr "En-cours"
@@ -1593,6 +1799,9 @@ msgstr "Poste de travail"
msgid "Work Center Displays"
msgstr "Affichages des postes de travail"
+msgid "Work instructions"
+msgstr "Modes opératoires"
+
msgid "Yes"
msgstr "Oui"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 7cf07f55d7..3147f698fb 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -111,6 +111,10 @@ msgstr "{0} सफलतापूर्वक हटाया गया"
msgid "{0} draft journal entries"
msgstr "{0} ड्राफ्ट जर्नल प्रविष्टियाँ"
+#. placeholder {0}: op.description
+msgid "{0} has no supplier"
+msgstr ""
+
#. placeholder {0}: formatter.format(onHand)
#. placeholder {1}: formatter.format(assembliesInStock)
#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
@@ -141,6 +145,10 @@ msgstr "{0} में से {1} पोस्टिंग खातों को
msgid "{0} of {maxSlots} provider slots used"
msgstr "{0} में से {maxSlots} प्रदाता स्लॉट उपयोग किए गए"
+#. placeholder {0}: pendingJobs.length
+msgid "{0} of {memberCount} member jobs are not completed yet — their output stays out of stock until each job is completed."
+msgstr "{0} का {memberCount} सदस्य जॉब अभी तक पूर्ण नहीं हैं — उनका आउटपुट तब तक स्टॉक से बाहर रहेगा जब तक प्रत्येक जॉब पूर्ण न हो जाए।"
+
#. placeholder {0}: selected.length
msgid "{0} operations · {totalQuantity} parts"
msgstr "{0} ऑपरेशन · {totalQuantity} पार्ट्स"
@@ -1652,6 +1660,10 @@ msgstr "सभी आइटम"
msgid "All Locations"
msgstr "सभी स्थान"
+#. placeholder {0}: tracked[0]?.itemReadableId ?? ""
+msgid "all make {0}"
+msgstr "सभी निर्माण {0}"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "चयनित समूहों के सभी सदस्य और चयनित व्यक्ति अनुरोधों को अनुमोदित करने में सक्षम होंगे"
@@ -3550,6 +3562,9 @@ msgstr "अपना ईमेल जांचें"
msgid "Checking Stripe for this customer…"
msgstr "इस ग्राहक के लिए Stripe की जांच की जा रही है…"
+msgid "Checking the batch's jobs..."
+msgstr "बैच की जॉब्स को जाँच रहे हैं..."
+
msgid "Checkpoint ·"
msgstr "चेकपॉइंट ·"
@@ -3574,6 +3589,10 @@ msgstr "यह देखने के लिए बाईं ओर की प
msgid "Choose a serial number"
msgstr "एक सीरियल नंबर चुनें"
+#. placeholder {0}: op.description
+msgid "choose a supplier for {0} on the job"
+msgstr ""
+
msgid "Choose another file"
msgstr "दूसरी फ़ाइल चुनें"
@@ -3736,6 +3755,9 @@ msgstr "कॉलम"
msgid "Combine filters"
msgstr "फ़िल्टर को संयोजित करें"
+msgid "Combine output into one lot"
+msgstr "एक लॉट में आउटपुट को मिलाएं"
+
msgid "Coming soon"
msgstr "जल्द ही आ रहा है"
@@ -4526,6 +4548,9 @@ msgstr "{0} मान बनाएं"
msgid "Create & Release"
msgstr "बनाएँ और जारी करें"
+msgid "Create & release batch"
+msgstr "बैच बनाएँ और जारी करें"
+
msgid "Create & Snapshot"
msgstr "बनाएं और स्नैपशॉट लें"
@@ -4598,6 +4623,9 @@ msgstr "जॉब बनाएँ"
msgid "Create Kanban"
msgstr "कानबान बनाएँ"
+msgid "Create New"
+msgstr "नया बनाएँ"
+
msgid "Create new rule"
msgstr "नया नियम बनाएं"
@@ -6269,6 +6297,12 @@ msgstr "उदाहरण के लिए Zebra 2x1"
msgid "Each cell is the people assigned against the people the day's work needs."
msgstr "प्रत्येक सेल उन लोगों को दर्शाता है जो दिन के काम के लिए आवश्यक लोगों के खिलाफ असाइन किए गए हैं।"
+msgid "Each job keeps its own lot. The shop floor can't change these."
+msgstr "प्रत्येक जॉब अपना स्वयं का लॉट रखता है। शॉप फ्लोर इन्हें नहीं बदल सकता।"
+
+msgid "Each job needs its own lot number — or combine them into one lot."
+msgstr "प्रत्येक जॉब को अपनी स्वयं की लॉट संख्या की आवश्यकता है — या उन्हें एक लॉट में मिलाएं।"
+
msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."
msgstr "प्रत्येक पंक्ति इस कंपनी के डेटा से एक ऐसी पंक्ति के लिए एक लिंक है जिसका यह मालिक नहीं है। इन पंक्तियों के साथ एक बैकअप को कभी भी पुनः स्थापित नहीं किया जा सकता।"
@@ -6281,6 +6315,9 @@ msgstr "प्रत्येक ऑपरेशन की अप्रयुक
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "प्रत्येक भौतिक इकाई को अपनी खुद की ट्रैक की गई इकाई और अद्वितीय संख्या मिलती है — एक इकाई, एक इकाई।"
+msgid "Each supplier's outside operations from every job go on one new purchase order, or on an existing draft you choose."
+msgstr "प्रत्येक आपूर्तिकर्ता की बाहरी ऑपरेशन हर जॉब से एक नया क्रय आदेश पर जाती है, या आप जो मौजूदा ड्राफ्ट चुनते हैं उस पर।"
+
msgid "Each, lb, ft…"
msgstr "प्रत्येक, lb, ft…"
@@ -7027,6 +7064,9 @@ msgstr "बाकी सब कुछ"
msgid "Everything else covers people, imports, integrations and the API — anything that is not one of your workflows."
msgstr "बाकी सब कुछ लोग, आयात, एकीकरण और API को कवर करता है — कुछ भी जो आपके वर्कफ़्लो में से एक नहीं है।"
+msgid "Everything this run makes lands in one lot. The shop floor can't change it."
+msgstr "इस रन में निर्माण होने वाली सभी चीजें एक लॉट में जाती हैं। शॉप फ्लोर इसे नहीं बदल सकता।"
+
msgid "Exceeds {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB total — remove some attachments to send."
msgstr "{PO_EMAIL_ATTACHMENT_LIMIT_MB} MB कुल से अधिक है — भेजने के लिए कुछ अनुलग्नक निकालें।"
@@ -7804,6 +7844,9 @@ msgstr "व्यू फिट करें"
msgid "Fix the problems with this workflow before testing it"
msgstr "इसे परीक्षण करने से पहले इस वर्कफ़्लो की समस्याओं को ठीक करें"
+msgid "Fix these jobs before releasing"
+msgstr "जारी करने से पहले इन जॉब्स को ठीक करें"
+
msgid "Fixed"
msgstr "निश्चित"
@@ -9610,7 +9653,7 @@ msgid "Lines"
msgstr "पंक्तियाँ"
msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."
-msgstr "एक बार क्रय आदेश प्राप्ति पोस्ट किए जाने के बाद यहां पंक्तियां दिखाई देती हैं, और केवल उन मात्राओं के लिए जो पहले से ही किसी अन्य आपूर्तिकर्ता रिटर्न पर अधिकृत नहीं हैं। एक अंधे रिटर्न के लिए पंक्ति आइटम जोड़ें का उपयोग करें।"
+msgstr "एक बार क्रय आदेश की प्राप्ति पोस्ट किए जाने के बाद यहां पंक्तियां दिखाई देंगी, और केवल उन मात्राओं के लिए जो पहले से किसी अन्य आपूर्तिकर्ता रिटर्न पर अधिकृत नहीं हैं। एक अंधी रिटर्न के लिए पंक्ति आइटम जोड़ें का उपयोग करें।"
msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."
msgstr "पंक्तियाँ यहाँ दिखाई देती हैं जब विक्रय आदेश की शिपमेंट पोस्ट की जाती है, और केवल उन मात्राओं के लिए जो पहले से किसी अन्य RMA पर अधिकृत नहीं हैं। एक अंधी रिटर्न के लिए पंक्ति मद जोड़ें का उपयोग करें।"
@@ -9806,6 +9849,9 @@ msgstr "खोया"
msgid "Lot"
msgstr "लॉट"
+msgid "Lot number"
+msgstr "लॉट संख्या"
+
msgid "Lot size"
msgstr "लॉट आकार"
@@ -9986,6 +10032,9 @@ msgstr "निर्माता भाग संख्या"
msgid "Manufacturing"
msgstr "विनिर्माण"
+msgid "manufacturing is blocked"
+msgstr "विनिर्माण अवरुद्ध है"
+
msgid "Map accounts"
msgstr "खातों को मैप करें"
@@ -10275,6 +10324,13 @@ msgstr "मेमो आईडी"
msgid "Merchant"
msgstr "व्यापारी"
+#. placeholder {0}: getItemReadableId(items, itemId) ?? itemId
+msgid "Merge {0} lots"
+msgstr ""
+
+msgid "Merge output lots"
+msgstr "आउटपुट लॉट्स को मर्ज करें"
+
msgid "MES"
msgstr "MES"
@@ -11264,6 +11320,10 @@ msgstr "कोई खुली विक्रय आदेश पंक्त
msgid "No operations found."
msgstr "कोई ऑपरेशन नहीं मिला।"
+#. placeholder {0}: job.missingAssemblies .map((m) => m.description) .join(", ")
+msgid "no operations on {0}"
+msgstr "{0} में कोई ऑपरेशन नहीं"
+
msgid "No operations require picking at this location"
msgstr "इस स्थान पर कोई भी ऑपरेशन पिकिंग की आवश्यकता नहीं है"
@@ -11385,7 +11445,7 @@ msgid "No results found"
msgstr "कोई परिणाम नहीं मिला"
msgid "No returnable lines for this customer"
-msgstr "इस ग्राहक के लिए कोई लौटाने योग्य पंक्तियां नहीं"
+msgstr "इस ग्राहक के लिए कोई लौटाई जा सकने वाली पंक्तियां नहीं"
msgid "No returnable lines for this supplier"
msgstr "इस आपूर्तिकर्ता के लिए कोई रिटर्न योग्य पंक्तियाँ नहीं"
@@ -13014,6 +13074,12 @@ msgstr "प्रक्रियाएं"
msgid "Procurement status — needs ordering, planned, on order, or received. The same indicator shown in the BoM tree."
msgstr "खरीद स्थिति — ऑर्डर करने की आवश्यकता, नियोजित, ऑर्डर पर, या प्राप्त। वही संकेतक जो BoM ट्री में दिखाया जाता है।"
+msgid "produced item"
+msgstr "उत्पादित आइटम"
+
+msgid "Produced item"
+msgstr "उत्पादित आइटम"
+
msgid "Product issues during hypercare"
msgstr "हाइपरकेयर के दौरान उत्पाद समस्याएं"
@@ -13923,6 +13989,11 @@ msgstr "{0} बैच जारी करें"
msgid "Release Batch"
msgstr "बैच जारी करें"
+#. placeholder {0}: batch.readableId
+#. placeholder {0}: releaseTarget.readableId
+msgid "Release batch {0}"
+msgstr "बैच {0} जारी करें"
+
msgid "Release change notice"
msgstr "परिवर्तन सूचना जारी करें"
@@ -13951,6 +14022,9 @@ msgstr "जारी रिवीजन"
msgid "Released revision is locked"
msgstr "जारी रिवीजन लॉक है"
+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
+msgstr "बैच जारी करने से इसकी जॉब्स जारी हो जाती हैं, और प्रत्येक को शॉप फ्लोर के लिए तैयार होना चाहिए।"
+
msgid "Remaining"
msgstr "शेष"
@@ -15074,7 +15148,7 @@ msgid "Search by linear issue title..."
msgstr "Linear समस्या शीर्षक द्वारा खोजें..."
msgid "Search by receipt, PO, or item"
-msgstr "प्राप्ति, क्रय आदेश, या आइटम द्वारा खोजें"
+msgstr "प्राप्ति, PO, या आइटम द्वारा खोजें"
msgid "Search by shipment, sales order, or item"
msgstr "शिपमेंट, विक्रय आदेश, या आइटम के अनुसार खोजें"
@@ -15324,7 +15398,7 @@ msgid "Select operations"
msgstr "ऑपरेशन चुनें"
msgid "Select posted receipt lines from this supplier to return."
-msgstr "इस आपूर्तिकर्ता से लौटाने के लिए पोस्ट किए गए प्राप्ति पंक्तियों का चयन करें।"
+msgstr "इस आपूर्तिकर्ता से रिटर्न करने के लिए पोस्ट की गई प्राप्ति पंक्तियां चुनें।"
msgid "Select posted shipment lines to this customer to return."
msgstr "इस ग्राहक को भेजी गई शिपमेंट पंक्तियों को रिटर्न के लिए चुनें।"
@@ -15822,6 +15896,10 @@ msgstr "शॉर्टकट"
msgid "Show"
msgstr "दिखाएँ"
+#. placeholder {0}: overflow.length
+msgid "Show {0} more"
+msgstr ""
+
msgid "Show a readable Customer ID column on the customer list, customer forms, and dropdowns. Customers are still identified internally either way."
msgstr "ग्राहक सूची, ग्राहक फॉर्म और ड्रॉपडाउन पर एक पठनीय ग्राहक आईडी कॉलम दिखाएं। ग्राहकों की पहचान आंतरिक रूप से किसी भी तरह से की जाती है।"
@@ -16981,6 +17059,9 @@ msgstr "बैकअप जॉब ने इस त्रुटि की रि
msgid "The backward-computed date an operation must finish by to keep its job on time, written to the operation's due date. A stable target for measuring progress — never a constraint on placement."
msgstr "वह पिछड़ी हुई गणना की गई तारीख जिस तक एक ऑपरेशन को अपने जॉब को समय पर रखने के लिए समाप्त करना चाहिए, ऑपरेशन की नियत तिथि में लिखा गया है। प्रगति को मापने के लिए एक स्थिर लक्ष्य — कभी भी प्लेसमेंट पर बाधा नहीं।"
+msgid "The batch goes to the shop floor. Its jobs are already released."
+msgstr "बैच शॉप फ्लोर पर जाता है। इसकी जॉब्स पहले से ही जारी हैं।"
+
msgid "The batch runs at its most urgent member's time — the others are pulled early"
msgstr "बैच अपने सबसे जरूरी सदस्य के समय चलता है — बाकी पहले खींचे जाते हैं"
@@ -17266,6 +17347,9 @@ msgstr "शिपमेंट पोस्ट होने पर मान्
msgid "The IRS recovery-period class for this asset under MACRS (3, 5, 7, 10, 15, 20, 27.5, 39-year)."
msgstr "MACRS के तहत इस संपत्ति के लिए IRS पुनर्प्राप्ति-अवधि वर्ग (3, 5, 7, 10, 15, 20, 27.5, 39-वर्ष)।"
+msgid "The item each job produces — require it to match to merge output lots"
+msgstr "प्रत्येक जॉब द्वारा उत्पादित आइटम — आउटपुट लॉट्स को मर्ज करने के लिए इसे मेल खाना आवश्यक है"
+
msgid "the job hours due that day (a due-date basis, not the day the work runs), with overdue work in Past due."
msgstr "उस दिन देय नौकरी के घंटे (देय तारीख आधार पर, वह दिन नहीं जब काम चलता है), अतिदेय कार्य पिछली देय में।"
@@ -17800,6 +17884,11 @@ msgstr "ये पंक्तियां इस कंपनी के बा
msgid "this ability"
msgstr "यह कौशल"
+#. placeholder {0}: jobIds.length
+#. placeholder {1}: jobIds.join(", ")
+msgid "This also releases {0} jobs ({1}). They become available to the shop floor and drive purchasing and production."
+msgstr "यह {0} जॉब्स ({1}) भी जारी करता है। वे शॉप फ्लोर के लिए उपलब्ध हो जाती हैं और क्रय और उत्पादन को चलाती हैं।"
+
msgid "This backup could not be completed."
msgstr "यह बैकअप पूर्ण नहीं किया जा सका।"
diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.po
index cd9b59b9fc..fde2b5154f 100644
--- a/packages/locale/locales/hi/mes.po
+++ b/packages/locale/locales/hi/mes.po
@@ -25,14 +25,28 @@ msgstr "{0} सक्रिय"
msgid "{0} ago"
msgstr "{0} पहले"
+#. placeholder {0}: batchFacts.customers.length
+msgid "{0} customers"
+msgstr ""
+
+#. placeholder {0}: unplanned .map( (m) => (m.job as { jobId?: string | null } | null)?.jobId ) .filter(Boolean) .join(", ")
+msgid "{0} has no lot number. Set it on the batch or job in Carbon, then complete."
+msgstr "{0} के पास लॉट संख्या नहीं है। इसे Carbon में बैच या जॉब पर सेट करें, फिर पूर्ण करें।"
+
+#. placeholder {0}: batchFacts.items.length
+msgid "{0} items"
+msgstr ""
+
#. placeholder {0}: (batch.operations ?? []).length
msgid "{0} jobs"
msgstr "{0} जॉब"
+#. placeholder {0}: issuedLines.length
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
#. placeholder {1}: operation.targetQuantity
+#. placeholder {1}: trackedLines.length
msgid "{0} of {1}"
msgstr "{0} में से {1}"
@@ -54,16 +68,28 @@ msgstr "{0} कतार में"
msgid "{0} running"
msgstr "{0} चल रहा है"
+#. placeholder {0}: operation.jobReadableId
+#. placeholder {1}: batch.readableId
+msgid "{0} runs in batch {1}"
+msgstr ""
+
#. placeholder {0}: item.quantityScrapped
msgid "{0} Scrapped"
msgstr "{0} स्क्रैप किया गया"
+msgid "{completed} of {quantity}"
+msgstr "{quantity} में से {completed}"
+
msgid "{completions} passed unit(s) will be completed."
msgstr "{completions} उत्तीर्ण इकाई(यों) को पूर्ण किया जाएगा।"
msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
msgstr "{fails} नमूना विफलता(एं) दर्ज की गई है और पूर्ण नहीं की जाएगी — उन्हें क्रियाएं मेनू से हल करें।"
+#. placeholder {0}: step.perMember.length
+msgid "{recorded}/{0} jobs"
+msgstr ""
+
msgid "+{overflow} more"
msgstr "+{overflow} अधिक"
@@ -88,6 +114,10 @@ msgstr "खाता सेटिंग्स"
msgid "Acknowledge & finish"
msgstr "स्वीकार करें और समाप्त करें"
+#. placeholder {0}: members.length
+msgid "across {0} jobs"
+msgstr "{0} जॉब में"
+
msgid "Active"
msgstr "सक्रिय"
@@ -118,6 +148,13 @@ msgstr "सभी"
msgid "All clear"
msgstr "सब कुछ स्पष्ट"
+msgid "All jobs"
+msgstr "सभी जॉब"
+
+#. placeholder {0}: batch.outputLotNumber
+msgid "All output goes to lot <0>{0}</0>"
+msgstr "सभी आउटपुट लॉट <0>{0}</0> में जाता है"
+
msgid "All rework"
msgstr "सभी पुनः कार्य"
@@ -166,6 +203,9 @@ msgstr "उपलब्ध"
msgid "Available"
msgstr "उपलब्ध"
+msgid "Back to batch"
+msgstr ""
+
msgid "Batch"
msgstr "बैच"
@@ -179,12 +219,21 @@ msgstr "बैच नंबर {0}"
msgid "Batch number is required"
msgstr "बैच नंबर आवश्यक है"
-msgid "Batched jobs"
-msgstr "बैच जॉब"
+msgid "Batch quantity"
+msgstr "बैच की मात्रा"
+
+msgid "batch total"
+msgstr "बैच कुल"
msgid "Behind target by {daysBehindTarget} day(s)"
msgstr "लक्ष्य से {daysBehindTarget} दिन(दिन) पीछे"
+#. placeholder {0}: step.minValue
+#. placeholder {1}: step.maxValue
+#. placeholder {2}: step.unitOfMeasureCode ?? ""
+msgid "Between {0} and {1} {2}"
+msgstr ""
+
#. placeholder {0}: column.blockingDispatchReadableId
msgid "Blocked by {0}"
msgstr "{0} द्वारा अवरुद्ध"
@@ -222,6 +271,9 @@ msgstr "चैट"
msgid "Check your email"
msgstr "अपना ईमेल जांचें"
+msgid "Choose a job"
+msgstr ""
+
msgid "Clear"
msgstr "साफ़ करें"
@@ -249,6 +301,9 @@ msgstr "बंद करें"
msgid "Collapse features table"
msgstr "फीचर्स टेबल को संक्षिप्त करें"
+msgid "Collapse panel"
+msgstr "पैनल संक्षिप्त करें"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -278,6 +333,9 @@ msgstr "पूर्ण करें"
msgid "Complete All"
msgstr "सभी को पूर्ण करें"
+msgid "Complete batch"
+msgstr ""
+
msgid "Complete Batch"
msgstr "बैच पूरा करें"
@@ -377,6 +435,9 @@ msgstr "प्रदर्शन"
msgid "Displays"
msgstr "डिस्प्ले"
+msgid "Done"
+msgstr ""
+
msgid "Down"
msgstr "डाउन"
@@ -409,9 +470,12 @@ msgstr "ड्राइंग और फीचर्स को रिसाइ
msgid "Dragging {0} cancelled."
msgstr "\"{0}\" को ड्रैग करना रद्द किया गया।"
+msgid "Due"
+msgstr ""
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
msgid "Due {0}"
msgstr "Due {0} के लिए"
@@ -434,6 +498,9 @@ msgstr "डुप्लिकेट सीरियल नंबर"
msgid "Duration"
msgstr "अवधि"
+msgid "Each job's output is its own lot — keep each job's parts apart."
+msgstr ""
+
msgid "Edit"
msgstr "संपादित करें"
@@ -449,6 +516,9 @@ msgstr "खाली वर्क सेंटर"
msgid "End Operations"
msgstr "ऑपरेशन समाप्त करें"
+msgid "Enter each job's value, or fill every job at once from the first row. Empty rows are skipped."
+msgstr ""
+
#. placeholder {0}: selectedPerson.name
msgid "Enter PIN for {0}"
msgstr "{0} के लिए PIN दर्ज करें"
@@ -465,12 +535,18 @@ msgstr "त्रुटि"
msgid "Estimated"
msgstr "अनुमानित"
+msgid "Every job in the batch follows these steps. Record a step for all of them at once."
+msgstr ""
+
msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
msgstr "प्रत्येक इकाई का निर्णय है: {passes} उत्तीर्ण और {fails} असफल। लॉट बंद हो जाता है जब प्रत्येक इकाई को अपने परिणाम के अनुसार भेजा जाता है।"
msgid "Expand features table"
msgstr "फीचर्स टेबल को विस्तृत करें"
+msgid "Expand panel"
+msgstr "पैनल विस्तार करें"
+
msgid "Expired"
msgstr "समाप्त"
@@ -511,6 +587,10 @@ msgstr "माप को सहेजने में विफल"
msgid "Failed to save result"
msgstr "परिणाम को सहेजने में विफल"
+#. placeholder {0}: file.name
+msgid "Failed to upload {0}"
+msgstr ""
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "फाइल अपलोड करने में विफल: {0}"
@@ -555,6 +635,10 @@ msgstr "अपना खाता सेट अप करना पूर्ण
msgid "Finish with material unpicked?"
msgstr "सामग्री बिना चुने समाप्त करें?"
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(batchFacts.dueDate) )
+msgid "First due {0}"
+msgstr ""
+
msgid "Forgot to Clock Out?"
msgstr "कार्य समाप्त करना भूल गए?"
@@ -567,6 +651,9 @@ msgstr "ऑपरेशन पर वापस जाएं"
msgid "Go to onboarding"
msgstr "ऑनबोर्डिंग पर जाएं"
+msgid "Hide description"
+msgstr ""
+
msgid "How many were actually picked?"
msgstr "वास्तव में कितने चुने गए?"
@@ -631,6 +718,9 @@ msgstr "सामग्री जारी करें"
msgid "Issue Type"
msgstr "समस्या प्रकार"
+msgid "Issued"
+msgstr "जारी किया गया"
+
msgid "Issued {issuedQuantity} of {lotLabel}"
msgstr "{issuedQuantity} का {lotLabel} जारी किया"
@@ -688,6 +778,9 @@ msgstr "लाइनें"
msgid "List view"
msgstr "सूची दृश्य"
+msgid "Load list"
+msgstr ""
+
msgid "Loading item details..."
msgstr "आइटम विवरण लोड हो रहे हैं..."
@@ -700,6 +793,9 @@ msgstr "स्थानीय"
msgid "Location"
msgstr "स्थान"
+msgid "Log completed"
+msgstr ""
+
msgid "Log Completed"
msgstr "पूर्ण लॉग करें"
@@ -727,6 +823,12 @@ msgstr "लॉगिन"
msgid "Lot"
msgstr "लॉट"
+msgid "Lot numbers missing"
+msgstr "लॉट संख्या गायब है"
+
+msgid "Lot tracked"
+msgstr ""
+
msgid "Machine"
msgstr "मशीन"
@@ -763,6 +865,9 @@ msgstr "मेल खाता है"
msgid "Materials"
msgstr "सामग्री"
+msgid "Materials issued"
+msgstr "सामग्री जारी की गई"
+
msgid "Maximum number of records reached"
msgstr "रिकॉर्ड की अधिकतम संख्या तक पहुंच गई"
@@ -866,6 +971,9 @@ msgstr "कोई मेल नहीं। एक बनाने के लि
msgid "No materials"
msgstr "कोई सामग्री नहीं"
+msgid "No materials on this batch."
+msgstr "इस बैच पर कोई सामग्री नहीं है।"
+
msgid "No open jobs"
msgstr "कोई खुली जॉब नहीं"
@@ -959,9 +1067,22 @@ msgstr "OEE प्रभाव"
msgid "OEM Required"
msgstr "OEM आवश्यक"
+#. placeholder {0}: m.operationQuantity ?? 0
+msgid "of {0}"
+msgstr ""
+
msgid "Oldest first"
msgstr "सबसे पुराना पहले"
+msgid "one combined lot · planned"
+msgstr "एक संयुक्त लॉट · योजनाबद्ध"
+
+msgid "one per job · planned"
+msgstr "प्रति जॉब एक · योजनाबद्ध"
+
+msgid "One pick covers the whole batch — it is shared out to the jobs automatically."
+msgstr ""
+
#. placeholder {0}: batch.quantity
msgid "Only {0} available"
msgstr "केवल {0} उपलब्ध"
@@ -975,6 +1096,9 @@ msgstr "खुला"
msgid "Open a display on the screen mounted at the work center and leave it running. Each board refreshes on its own."
msgstr "वर्क सेंटर पर लगी स्क्रीन पर एक डिस्प्ले खोलें और इसे चलाते रहें। प्रत्येक बोर्ड स्वयं रीफ्रेश होता है।"
+msgid "Open a job in this batch"
+msgstr ""
+
msgid "Open an NCR for MRB disposition"
msgstr "MRB निपटान के लिए एक NCR खोलें"
@@ -999,6 +1123,9 @@ msgstr "वैकल्पिक"
msgid "or"
msgstr "या"
+msgid "Output lot"
+msgstr "आउटपुट लॉट"
+
msgid "Overall result"
msgstr "समग्र परिणाम"
@@ -1017,6 +1144,9 @@ msgstr "आंशिक"
msgid "Partial Disposition"
msgstr "आंशिक निपटान"
+msgid "Passed inspection"
+msgstr ""
+
msgid "Passed Inspection"
msgstr "निरीक्षण उत्तीर्ण"
@@ -1029,6 +1159,10 @@ msgstr "रोकें"
msgid "Pick"
msgstr "चुनें"
+#. placeholder {0}: m.required - m.issued
+msgid "Pick {0}"
+msgstr "पिकिंग {0}"
+
msgid "Pick tracked item"
msgstr "ट्रैक किए गए आइटम को चुनें"
@@ -1098,6 +1232,9 @@ msgstr "कार्यविधि"
msgid "Process"
msgstr "प्रक्रिया"
+msgid "Process parameters"
+msgstr "प्रक्रिया पैरामीटर"
+
msgid "Process Parameters"
msgstr "प्रक्रिया पैरामीटर"
@@ -1140,18 +1277,28 @@ msgstr "रिकॉर्ड"
msgid "Record {0}"
msgstr "रिकॉर्ड {0}"
+#. placeholder {0}: changed.length
+msgid "Record {0} jobs"
+msgstr ""
+
msgid "Record only"
msgstr "केवल रिकॉर्ड करें"
msgid "Record Partial"
msgstr "आंशिक रिकॉर्ड करें"
+msgid "Recorded"
+msgstr ""
+
msgid "Reject"
msgstr "अस्वीकार करें"
msgid "Reject Lot"
msgstr "लॉट अस्वीकार करें"
+msgid "Released"
+msgstr ""
+
msgid "Remove"
msgstr "निकालें"
@@ -1167,6 +1314,9 @@ msgstr "पार्ट निकालें"
msgid "Reopen the subassembly and create a replacement unit"
msgstr "सब-असेंबली को फिर से खोलें और एक रिप्लेसमेंट इकाई बनाएँ"
+msgid "Required"
+msgstr "आवश्यक"
+
msgid "Result"
msgstr "परिणाम"
@@ -1188,6 +1338,9 @@ msgstr "चल रहा है"
msgid "Sales Order"
msgstr "विक्रय आदेश"
+msgid "Same for every job"
+msgstr ""
+
msgid "Save"
msgstr "सहेजें"
@@ -1307,6 +1460,9 @@ msgstr "भेजें"
msgid "Send to Carbon"
msgstr "Carbon को भेजें"
+msgid "Separate lots"
+msgstr "अलग-अलग लॉट"
+
msgid "Serial"
msgstr "सीरीज़"
@@ -1326,6 +1482,9 @@ msgstr "सीरियल नंबर"
msgid "Serial Numbers"
msgstr "सीरियल नंबर"
+msgid "Serialized"
+msgstr ""
+
msgid "Session locked"
msgstr "सत्र लॉक किया गया"
@@ -1338,6 +1497,9 @@ msgstr "घड़ी बंद करने का समय सेट करे
msgid "Set up in Carbon"
msgstr "Carbon में सेट अप करें"
+msgid "Set when the batch was planned."
+msgstr "जब बैच की योजना बनाई गई थी तब सेट करें।"
+
msgid "Setup"
msgstr "सेटअप"
@@ -1350,6 +1512,9 @@ msgstr "कम"
msgid "Short pick {itemName}"
msgstr "Short pick {itemName}"
+msgid "Show description"
+msgstr ""
+
msgid "Show this overlay"
msgstr "यह ओवरले दिखाएं"
@@ -1389,6 +1554,10 @@ msgstr "उपयोग किए गए स्पेयर पार्ट्
msgid "Start"
msgstr "शुरू करें"
+#. placeholder {0}: workTypeLabels[ eventType.toLowerCase() as keyof typeof workTypeLabels ].toLowerCase()
+msgid "Start {0}"
+msgstr ""
+
msgid "Start or pause the operation"
msgstr "ऑपरेशन को शुरू करें या रोकें"
@@ -1438,12 +1607,22 @@ msgstr "टैग"
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "इस ऑपरेशन के लिए पूर्ण मात्रा आवश्यक मात्रा {targetQuantity} से कम है।"
+msgid "The jobs and parts that make up this run."
+msgstr ""
+
+msgid "The jobs make different items — keep each job's parts apart."
+msgstr ""
+
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "लॉट को उत्तीर्ण के रूप में चिह्नित किया जाएगा और {remaining} शेष इकाई(यों) को इस ऑपरेशन पर पूर्ण किया जाएगा।"
msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "लॉट को अभी भी डिस्पोज़ किया जाएगा, लेकिन कम से कम एक Issue Type कॉन्फ़िगर होने तक NCR नहीं बनाया जा सकता।"
+#. placeholder {0}: (batch.operations ?? []).length
+msgid "The timer and completion are shared by all {0} jobs. Steps, materials and files here are this job's own."
+msgstr ""
+
msgid "There are no available or consumed tracked parts for this material."
msgstr "इस सामग्री के लिए कोई उपलब्ध या उपयोग की गई ट्रैक की गई पार्ट नहीं है।"
@@ -1453,6 +1632,9 @@ msgstr "बिल ऑफ मेटेरियल पर सीरियल य
msgid "These items still have material to pick. Finishing now marks the list Partial."
msgstr "इन आइटम के पास अभी भी चुनने के लिए सामग्री है। अभी समाप्त करने से सूची को आंशिक के रूप में चिह्नित किया जाता है।"
+msgid "This batch has no work instructions."
+msgstr ""
+
msgid "This lot is expired and can't be picked."
msgstr "यह लॉट समाप्त हो गया है और इसे चुना नहीं जा सकता।"
@@ -1468,6 +1650,9 @@ msgstr "इस इकाई को स्थायी रूप से स्क
msgid "Thumbnail"
msgstr "थंबनेल"
+msgid "Tick the jobs this was done for."
+msgstr ""
+
msgid "Time and cost split across jobs proportionally to quantity."
msgstr "समय और लागत मात्रा के अनुपात में जॉब में विभाजित है।"
@@ -1478,6 +1663,12 @@ msgstr "समय प्रविष्टियाँ"
msgid "Time Worked: {0}"
msgstr "समय काम किया: {0}"
+msgid "To pick"
+msgstr ""
+
+msgid "To run"
+msgstr ""
+
msgid "Today"
msgstr "आज"
@@ -1487,6 +1678,9 @@ msgstr "साइडबार को टॉगल करें"
msgid "Tools"
msgstr "उपकरण"
+msgid "Total"
+msgstr ""
+
msgid "Total Quantity"
msgstr "कुल मात्रा"
@@ -1501,6 +1695,9 @@ msgstr "कुल: {0}"
msgid "Tracked Entity"
msgstr "ट्रैक की गई इकाई"
+msgid "tracked lines"
+msgstr "ट्रैक की गई पंक्तियां"
+
msgid "Tracking"
msgstr "ट्रैकिंग"
@@ -1572,6 +1769,12 @@ msgstr "अपलोड किया जा रहा है {0}"
msgid "Use a different account"
msgstr "एक अलग खाता उपयोग करें"
+msgid "Used automatically at completion"
+msgstr ""
+
+msgid "Value"
+msgstr ""
+
msgid "Verify"
msgstr "सत्यापित करें"
@@ -1584,6 +1787,9 @@ msgstr "हमने आपके खाते में साइन इन क
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm} क्या है?"
+msgid "Whole batch"
+msgstr "पूरा बैच"
+
msgid "WIP"
msgstr "WIP"
@@ -1593,6 +1799,9 @@ msgstr "वर्क सेंटर"
msgid "Work Center Displays"
msgstr "वर्क सेंटर डिस्प्ले"
+msgid "Work instructions"
+msgstr "कार्य निर्देश"
+
msgid "Yes"
msgstr "हां"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 09ee510a6f..c73ca0a3a8 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -111,6 +111,10 @@ msgstr "{0} eliminato con successo"
msgid "{0} draft journal entries"
msgstr "{0} bozze di prima nota"
+#. placeholder {0}: op.description
+msgid "{0} has no supplier"
+msgstr ""
+
#. placeholder {0}: formatter.format(onHand)
#. placeholder {1}: formatter.format(assembliesInStock)
#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
@@ -141,6 +145,10 @@ msgstr "{0} di {1} conti di registrazione mappati"
msgid "{0} of {maxSlots} provider slots used"
msgstr "{0} di {maxSlots} slot provider utilizzati"
+#. placeholder {0}: pendingJobs.length
+msgid "{0} of {memberCount} member jobs are not completed yet — their output stays out of stock until each job is completed."
+msgstr "{0} dei {memberCount} ordini di produzione non sono ancora completati — il loro output rimane fuori dalla giacenza fino a quando ogni ordine di produzione non sia completato."
+
#. placeholder {0}: selected.length
msgid "{0} operations · {totalQuantity} parts"
msgstr "{0} operazioni · {totalQuantity} componenti"
@@ -1652,6 +1660,10 @@ msgstr "Tutti gli articoli"
msgid "All Locations"
msgstr "Tutte le Ubicazioni"
+#. placeholder {0}: tracked[0]?.itemReadableId ?? ""
+msgid "all make {0}"
+msgstr "Produzione di {0}"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "Tutti i membri dei gruppi selezionati e gli individui selezionati potranno approvare le richieste"
@@ -3550,6 +3562,9 @@ msgstr "Controlla la tua email"
msgid "Checking Stripe for this customer…"
msgstr "Verifica di Stripe per questo cliente…"
+msgid "Checking the batch's jobs..."
+msgstr "Controllo degli ordini di produzione nel lotto..."
+
msgid "Checkpoint ·"
msgstr "Checkpoint ·"
@@ -3574,6 +3589,10 @@ msgstr "Scegli una riga a sinistra per vedere da dove può provenire il suo stoc
msgid "Choose a serial number"
msgstr "Scegli un numero di serie"
+#. placeholder {0}: op.description
+msgid "choose a supplier for {0} on the job"
+msgstr ""
+
msgid "Choose another file"
msgstr "Scegli un altro file"
@@ -3736,6 +3755,9 @@ msgstr "Colonne"
msgid "Combine filters"
msgstr "Combina filtri"
+msgid "Combine output into one lot"
+msgstr "Combina in un unico Lotto"
+
msgid "Coming soon"
msgstr "Disponibile presto"
@@ -4526,6 +4548,9 @@ msgstr "Crea {0} valori"
msgid "Create & Release"
msgstr "Crea e rilascia"
+msgid "Create & release batch"
+msgstr "Crea & rilascia lotto di produzione"
+
msgid "Create & Snapshot"
msgstr "Crea e Snapshot"
@@ -4598,6 +4623,9 @@ msgstr "Crea ordini di produzione"
msgid "Create Kanban"
msgstr "Crea Kanban"
+msgid "Create New"
+msgstr "Crea nuovo"
+
msgid "Create new rule"
msgstr "Crea nuova regola"
@@ -6269,6 +6297,12 @@ msgstr "ad es. Zebra 2x1"
msgid "Each cell is the people assigned against the people the day's work needs."
msgstr "Ogni cella mostra le persone assegnate rispetto alle persone di cui il lavoro del giorno ha bisogno."
+msgid "Each job keeps its own lot. The shop floor can't change these."
+msgstr "Ogni Ordine di produzione mantiene il suo Lotto. L'Officina non può cambiarli."
+
+msgid "Each job needs its own lot number — or combine them into one lot."
+msgstr "Ogni Ordine di produzione richiede il suo numero di Lotto — oppure combinarli in un unico Lotto."
+
msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."
msgstr "Ogni riga è un collegamento dai dati di questa Azienda a una riga che non possiede. Un backup con queste righe non potrebbe mai essere ripristinato."
@@ -6281,6 +6315,9 @@ msgstr "Ogni Materiale non utilizzato dell'Operazione ritorna non appena l'Opera
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Ogni unità fisica ottiene la propria entità tracciata e numero univoco — un'entità, un'unità."
+msgid "Each supplier's outside operations from every job go on one new purchase order, or on an existing draft you choose."
+msgstr "Le operazioni esterne di ogni fornitore da ogni ordine di produzione vengono inserite in un nuovo ordine di acquisto o in una bozza esistente che scegli."
+
msgid "Each, lb, ft…"
msgstr "Ogni, lb, ft…"
@@ -7027,6 +7064,9 @@ msgstr "Tutto il resto"
msgid "Everything else covers people, imports, integrations and the API — anything that is not one of your workflows."
msgstr "Tutto il resto copre persone, importazioni, integrazioni e l'API — qualsiasi cosa che non sia uno dei tuoi flussi di lavoro."
+msgid "Everything this run makes lands in one lot. The shop floor can't change it."
+msgstr "Tutta la Produzione di questo ciclo finisce in un unico Lotto. L'Officina non può cambiarlo."
+
msgid "Exceeds {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB total — remove some attachments to send."
msgstr "Supera {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB totali — rimuovi alcuni allegati per inviare."
@@ -7804,6 +7844,9 @@ msgstr "Adatta alla vista"
msgid "Fix the problems with this workflow before testing it"
msgstr "Correggere i problemi di questo flusso di lavoro prima di testarlo"
+msgid "Fix these jobs before releasing"
+msgstr "Correggi questi ordini di produzione prima di rilasciarli"
+
msgid "Fixed"
msgstr "Fisso"
@@ -9610,7 +9653,7 @@ msgid "Lines"
msgstr "Righe"
msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."
-msgstr "Le righe appaiono qui dopo che un'entrata merci su ordine di acquisto è stata registrata, e solo per quantità non già autorizzate in un altro reso al fornitore. Usa Aggiungi riga per un reso cieco."
+msgstr "Le righe appariranno qui una volta che un'entrata merci di un ordine di acquisto è stata registrata, e solo per le quantità non già autorizzate su un altro reso del fornitore. Utilizza Aggiungi riga per un reso cieco."
msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."
msgstr "Le righe appariranno qui una volta che la spedizione dell'ordine di vendita è stata registrata, e solo per le quantità non già autorizzate su un altro RMA. Utilizza Aggiungi riga articolo per un reso cieco."
@@ -9806,6 +9849,9 @@ msgstr "Perso"
msgid "Lot"
msgstr "Lotto"
+msgid "Lot number"
+msgstr "Numero di Lotto"
+
msgid "Lot size"
msgstr "Dimensione del lotto"
@@ -9986,6 +10032,9 @@ msgstr "Numero di parte del produttore"
msgid "Manufacturing"
msgstr "Produzione"
+msgid "manufacturing is blocked"
+msgstr "La produzione è bloccata"
+
msgid "Map accounts"
msgstr "Mappa conti"
@@ -10275,6 +10324,13 @@ msgstr "ID Memo"
msgid "Merchant"
msgstr "Esercente"
+#. placeholder {0}: getItemReadableId(items, itemId) ?? itemId
+msgid "Merge {0} lots"
+msgstr ""
+
+msgid "Merge output lots"
+msgstr "Unisci i lotti"
+
msgid "MES"
msgstr "MES"
@@ -11264,6 +11320,10 @@ msgstr "Nessuna riga di ordine di vendita aperta"
msgid "No operations found."
msgstr "Nessuna operazione trovata."
+#. placeholder {0}: job.missingAssemblies .map((m) => m.description) .join(", ")
+msgid "no operations on {0}"
+msgstr "Nessuna operazione su {0}"
+
msgid "No operations require picking at this location"
msgstr "Nessuna operazione richiede il prelievo in questa posizione"
@@ -13014,6 +13074,12 @@ msgstr "Processi"
msgid "Procurement status — needs ordering, planned, on order, or received. The same indicator shown in the BoM tree."
msgstr "Stato di approvvigionamento: da ordinare, pianificato, in ordine o ricevuto. Lo stesso indicatore mostrato nell'albero della BoM."
+msgid "produced item"
+msgstr "articolo prodotto"
+
+msgid "Produced item"
+msgstr "Articolo prodotto"
+
msgid "Product issues during hypercare"
msgstr "Problemi di prodotto durante l'hypercare"
@@ -13923,6 +13989,11 @@ msgstr "Rilascia {0} lotti di produzione"
msgid "Release Batch"
msgstr "Rilascia lotto"
+#. placeholder {0}: batch.readableId
+#. placeholder {0}: releaseTarget.readableId
+msgid "Release batch {0}"
+msgstr "Rilascia lotto di produzione {0}"
+
msgid "Release change notice"
msgstr "Rilascia avviso di modifica"
@@ -13951,6 +14022,9 @@ msgstr "Revisione rilasciata"
msgid "Released revision is locked"
msgstr "La revisione rilasciata è bloccata"
+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
+msgstr "Rilasciare il lotto di produzione rilascia i suoi ordini di produzione, e ognuno deve essere pronto per l'officina."
+
msgid "Remaining"
msgstr "Rimanente"
@@ -15822,6 +15896,10 @@ msgstr "Scorciatoie"
msgid "Show"
msgstr "Mostra"
+#. placeholder {0}: overflow.length
+msgid "Show {0} more"
+msgstr ""
+
msgid "Show a readable Customer ID column on the customer list, customer forms, and dropdowns. Customers are still identified internally either way."
msgstr "Mostra una colonna ID Cliente leggibile nell'elenco clienti, nei moduli cliente e nei menu a discesa. I clienti sono comunque identificati internamente in entrambi i casi."
@@ -16981,6 +17059,9 @@ msgstr "Il lavoro di backup ha segnalato questo errore."
msgid "The backward-computed date an operation must finish by to keep its job on time, written to the operation's due date. A stable target for measuring progress — never a constraint on placement."
msgstr "La data calcolata a ritroso che un'operazione deve terminare entro per mantenere il suo ordine di produzione in orario, scritta nella data di scadenza dell'operazione. Un obiettivo stabile per misurare i progressi — mai un vincolo sul posizionamento."
+msgid "The batch goes to the shop floor. Its jobs are already released."
+msgstr "Il lotto di produzione va all'officina. I suoi ordini di produzione sono già rilasciati."
+
msgid "The batch runs at its most urgent member's time — the others are pulled early"
msgstr "Il lotto segue il membro più urgente — gli altri vengono anticipati"
@@ -17266,6 +17347,9 @@ msgstr "Il costo dell'inventario riconosciuto quando una spedizione viene regist
msgid "The IRS recovery-period class for this asset under MACRS (3, 5, 7, 10, 15, 20, 27.5, 39-year)."
msgstr "La classe di periodo di recupero IRS per questo bene secondo MACRS (3, 5, 7, 10, 15, 20, 27,5, 39 anni)."
+msgid "The item each job produces — require it to match to merge output lots"
+msgstr "L'articolo che ogni ordine di produzione produce — richiedi che corrisponda per unire i lotti"
+
msgid "the job hours due that day (a due-date basis, not the day the work runs), with overdue work in Past due."
msgstr "le ore di ordine di produzione dovute quel giorno (sulla base della scadenza, non il giorno in cui il lavoro viene eseguito), con il lavoro in ritardo in Scaduto."
@@ -17800,6 +17884,11 @@ msgstr "Queste righe collegano i dati al di fuori di questa azienda, quindi non
msgid "this ability"
msgstr "questa competenza"
+#. placeholder {0}: jobIds.length
+#. placeholder {1}: jobIds.join(", ")
+msgid "This also releases {0} jobs ({1}). They become available to the shop floor and drive purchasing and production."
+msgstr "Questo rilascia anche {0} ordini di produzione ({1}). Diventano disponibili all'officina e guidano gli acquisti e la produzione."
+
msgid "This backup could not be completed."
msgstr "Non è stato possibile completare questo backup."
diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.po
index 184b9c3e31..748bfb99dc 100644
--- a/packages/locale/locales/it/mes.po
+++ b/packages/locale/locales/it/mes.po
@@ -25,14 +25,28 @@ msgstr "{0} Attivi"
msgid "{0} ago"
msgstr "{0} fa"
+#. placeholder {0}: batchFacts.customers.length
+msgid "{0} customers"
+msgstr ""
+
+#. placeholder {0}: unplanned .map( (m) => (m.job as { jobId?: string | null } | null)?.jobId ) .filter(Boolean) .join(", ")
+msgid "{0} has no lot number. Set it on the batch or job in Carbon, then complete."
+msgstr "{0} non ha alcun numero di Lotto. Impostalo sul Lotto di produzione o sull'Ordine di produzione in Carbon, quindi completa."
+
+#. placeholder {0}: batchFacts.items.length
+msgid "{0} items"
+msgstr ""
+
#. placeholder {0}: (batch.operations ?? []).length
msgid "{0} jobs"
msgstr "{0} ordini di produzione"
+#. placeholder {0}: issuedLines.length
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
#. placeholder {1}: operation.targetQuantity
+#. placeholder {1}: trackedLines.length
msgid "{0} of {1}"
msgstr "{0} di {1}"
@@ -54,16 +68,28 @@ msgstr "{0} in coda"
msgid "{0} running"
msgstr "{0} in esecuzione"
+#. placeholder {0}: operation.jobReadableId
+#. placeholder {1}: batch.readableId
+msgid "{0} runs in batch {1}"
+msgstr ""
+
#. placeholder {0}: item.quantityScrapped
msgid "{0} Scrapped"
msgstr "{0} Scartati"
+msgid "{completed} of {quantity}"
+msgstr "{completed} di {quantity}"
+
msgid "{completions} passed unit(s) will be completed."
msgstr "{completions} unità superate verranno completate."
msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
msgstr "{fails} errore(i) campionato(i) registrato(i) e NON sarà(sarranno) completato(i) — risolvere(li) dal menu azioni."
+#. placeholder {0}: step.perMember.length
+msgid "{recorded}/{0} jobs"
+msgstr ""
+
msgid "+{overflow} more"
msgstr "+{overflow} altri"
@@ -88,6 +114,10 @@ msgstr "Impostazioni Account"
msgid "Acknowledge & finish"
msgstr "Riconosci e completa"
+#. placeholder {0}: members.length
+msgid "across {0} jobs"
+msgstr "su {0} Ordini di produzione"
+
msgid "Active"
msgstr "Attivo"
@@ -118,6 +148,13 @@ msgstr "Tutti"
msgid "All clear"
msgstr "Tutto libero"
+msgid "All jobs"
+msgstr "Tutti gli ordini di produzione"
+
+#. placeholder {0}: batch.outputLotNumber
+msgid "All output goes to lot <0>{0}</0>"
+msgstr "Tutto l'output va al Lotto <0>{0}</0>"
+
msgid "All rework"
msgstr "Tutto rilavorazione"
@@ -166,6 +203,9 @@ msgstr "disponibile"
msgid "Available"
msgstr "Disponibile"
+msgid "Back to batch"
+msgstr ""
+
msgid "Batch"
msgstr "Lotto"
@@ -179,12 +219,21 @@ msgstr "Numero Lotto {0}"
msgid "Batch number is required"
msgstr "Il numero di lotto è obbligatorio"
-msgid "Batched jobs"
-msgstr "Ordini di produzione raggruppati"
+msgid "Batch quantity"
+msgstr "Quantità del lotto di produzione"
+
+msgid "batch total"
+msgstr "totale Lotto di produzione"
msgid "Behind target by {daysBehindTarget} day(s)"
msgstr "In ritardo rispetto al target di {daysBehindTarget} giorno(i)"
+#. placeholder {0}: step.minValue
+#. placeholder {1}: step.maxValue
+#. placeholder {2}: step.unitOfMeasureCode ?? ""
+msgid "Between {0} and {1} {2}"
+msgstr ""
+
#. placeholder {0}: column.blockingDispatchReadableId
msgid "Blocked by {0}"
msgstr "Bloccato da {0}"
@@ -222,6 +271,9 @@ msgstr "Chat"
msgid "Check your email"
msgstr "Controlla la tua email"
+msgid "Choose a job"
+msgstr ""
+
msgid "Clear"
msgstr "Cancella"
@@ -249,6 +301,9 @@ msgstr "Chiudi"
msgid "Collapse features table"
msgstr "Comprimi tabella funzionalità"
+msgid "Collapse panel"
+msgstr "Comprimi pannello"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -278,6 +333,9 @@ msgstr "Completa"
msgid "Complete All"
msgstr "Completa tutto"
+msgid "Complete batch"
+msgstr ""
+
msgid "Complete Batch"
msgstr "Completa Lotto"
@@ -377,6 +435,9 @@ msgstr "Visualizzazione"
msgid "Displays"
msgstr "Display"
+msgid "Done"
+msgstr ""
+
msgid "Down"
msgstr "Fermo"
@@ -409,9 +470,12 @@ msgstr "Trascinare per ridimensionare il disegno e le caratteristiche"
msgid "Dragging {0} cancelled."
msgstr "Trascinamento di {0} annullato."
+msgid "Due"
+msgstr ""
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
msgid "Due {0}"
msgstr "Scadenza {0}"
@@ -434,6 +498,9 @@ msgstr "Numero di serie duplicato"
msgid "Duration"
msgstr "Durata"
+msgid "Each job's output is its own lot — keep each job's parts apart."
+msgstr ""
+
msgid "Edit"
msgstr "Modifica"
@@ -449,6 +516,9 @@ msgstr "Centri di lavoro vuoti"
msgid "End Operations"
msgstr "Termina Operazioni"
+msgid "Enter each job's value, or fill every job at once from the first row. Empty rows are skipped."
+msgstr ""
+
#. placeholder {0}: selectedPerson.name
msgid "Enter PIN for {0}"
msgstr "Inserisci il PIN per {0}"
@@ -465,12 +535,18 @@ msgstr "Errore"
msgid "Estimated"
msgstr "Stimato"
+msgid "Every job in the batch follows these steps. Record a step for all of them at once."
+msgstr ""
+
msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
msgstr "Ogni unità ha un verdetto: {passes} superate e {fails} fallite. Il lotto si chiude con ogni unità indirizzata al suo esito."
msgid "Expand features table"
msgstr "Espandi tabella funzionalità"
+msgid "Expand panel"
+msgstr "Espandi pannello"
+
msgid "Expired"
msgstr "Scaduto"
@@ -511,6 +587,10 @@ msgstr "Errore durante il salvataggio della misurazione"
msgid "Failed to save result"
msgstr "Errore durante il salvataggio del risultato"
+#. placeholder {0}: file.name
+msgid "Failed to upload {0}"
+msgstr ""
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Impossibile caricare il file: {0}"
@@ -555,6 +635,10 @@ msgstr "Completa la configurazione del tuo account"
msgid "Finish with material unpicked?"
msgstr "Terminare con il materiale non prelevato?"
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(batchFacts.dueDate) )
+msgid "First due {0}"
+msgstr ""
+
msgid "Forgot to Clock Out?"
msgstr "Hai dimenticato il timbra fine?"
@@ -567,6 +651,9 @@ msgstr "Torna all'operazione"
msgid "Go to onboarding"
msgstr "Vai all'onboarding"
+msgid "Hide description"
+msgstr ""
+
msgid "How many were actually picked?"
msgstr "Quanti sono stati effettivamente prelevati?"
@@ -631,6 +718,9 @@ msgstr "Preleva Materiale"
msgid "Issue Type"
msgstr "Tipo di Problema"
+msgid "Issued"
+msgstr "Emesso"
+
msgid "Issued {issuedQuantity} of {lotLabel}"
msgstr "Emesso {issuedQuantity} di {lotLabel}"
@@ -688,6 +778,9 @@ msgstr "righe"
msgid "List view"
msgstr "Vista elenco"
+msgid "Load list"
+msgstr ""
+
msgid "Loading item details..."
msgstr "Caricamento dettagli articolo..."
@@ -700,6 +793,9 @@ msgstr "Locale"
msgid "Location"
msgstr "Ubicazione"
+msgid "Log completed"
+msgstr ""
+
msgid "Log Completed"
msgstr "Registra Completati"
@@ -727,6 +823,12 @@ msgstr "Accedi"
msgid "Lot"
msgstr "Lotto"
+msgid "Lot numbers missing"
+msgstr "Numeri di Lotto mancanti"
+
+msgid "Lot tracked"
+msgstr ""
+
msgid "Machine"
msgstr "Macchina"
@@ -763,6 +865,9 @@ msgstr "corrisponde a"
msgid "Materials"
msgstr "Materiali"
+msgid "Materials issued"
+msgstr "Materiali prelevati"
+
msgid "Maximum number of records reached"
msgstr "Numero massimo di registrazioni raggiunto"
@@ -866,6 +971,9 @@ msgstr "Nessuna corrispondenza. Digita per crearne una."
msgid "No materials"
msgstr "Nessun materiale"
+msgid "No materials on this batch."
+msgstr "Nessun materiale in questo Lotto di produzione."
+
msgid "No open jobs"
msgstr "Nessun ordine di produzione aperto"
@@ -959,9 +1067,22 @@ msgstr "Impatto OEE"
msgid "OEM Required"
msgstr "Richiesto OEM"
+#. placeholder {0}: m.operationQuantity ?? 0
+msgid "of {0}"
+msgstr ""
+
msgid "Oldest first"
msgstr "Più vecchio prima"
+msgid "one combined lot · planned"
+msgstr "un unico Lotto di produzione combinato · Pianificato"
+
+msgid "one per job · planned"
+msgstr "uno per Ordine di produzione · Pianificato"
+
+msgid "One pick covers the whole batch — it is shared out to the jobs automatically."
+msgstr ""
+
#. placeholder {0}: batch.quantity
msgid "Only {0} available"
msgstr "Solo {0} disponibili"
@@ -975,6 +1096,9 @@ msgstr "Aperto"
msgid "Open a display on the screen mounted at the work center and leave it running. Each board refreshes on its own."
msgstr "Apri un display sullo schermo montato al centro di lavoro e lascialo in esecuzione. Ogni bacheca si aggiorna automaticamente."
+msgid "Open a job in this batch"
+msgstr ""
+
msgid "Open an NCR for MRB disposition"
msgstr "Apri un NCR per la disposizione MRB"
@@ -999,6 +1123,9 @@ msgstr "Facoltativo"
msgid "or"
msgstr "o"
+msgid "Output lot"
+msgstr "Lotto di output"
+
msgid "Overall result"
msgstr "Risultato complessivo"
@@ -1017,6 +1144,9 @@ msgstr "Parziale"
msgid "Partial Disposition"
msgstr "Disposizione Parziale"
+msgid "Passed inspection"
+msgstr ""
+
msgid "Passed Inspection"
msgstr "Controllo superato"
@@ -1029,6 +1159,10 @@ msgstr "Sospendi"
msgid "Pick"
msgstr "Preleva"
+#. placeholder {0}: m.required - m.issued
+msgid "Pick {0}"
+msgstr "Prelievo {0}"
+
msgid "Pick tracked item"
msgstr "Seleziona articolo tracciato"
@@ -1098,6 +1232,9 @@ msgstr "Procedura"
msgid "Process"
msgstr "Processo"
+msgid "Process parameters"
+msgstr "Parametri del processo"
+
msgid "Process Parameters"
msgstr "Parametri di Processo"
@@ -1140,18 +1277,28 @@ msgstr "Registra"
msgid "Record {0}"
msgstr "Registrazione {0}"
+#. placeholder {0}: changed.length
+msgid "Record {0} jobs"
+msgstr ""
+
msgid "Record only"
msgstr "Solo registrazione"
msgid "Record Partial"
msgstr "Registra Parziale"
+msgid "Recorded"
+msgstr ""
+
msgid "Reject"
msgstr "Rifiuta"
msgid "Reject Lot"
msgstr "Rifiuta Lotto"
+msgid "Released"
+msgstr ""
+
msgid "Remove"
msgstr "Rimuovi"
@@ -1167,6 +1314,9 @@ msgstr "Rimuovi componente"
msgid "Reopen the subassembly and create a replacement unit"
msgstr "Riaprire il sottoassieme e creare un'unità di ricambio"
+msgid "Required"
+msgstr "Obbligatorio"
+
msgid "Result"
msgstr "Risultato"
@@ -1188,6 +1338,9 @@ msgstr "In esecuzione"
msgid "Sales Order"
msgstr "Ordine di Vendita"
+msgid "Same for every job"
+msgstr ""
+
msgid "Save"
msgstr "Salva"
@@ -1307,6 +1460,9 @@ msgstr "Invia"
msgid "Send to Carbon"
msgstr "Invia a Carbon"
+msgid "Separate lots"
+msgstr "Lotti separati"
+
msgid "Serial"
msgstr "Seriale"
@@ -1326,6 +1482,9 @@ msgstr "Numeri di serie"
msgid "Serial Numbers"
msgstr "Numeri di Serie"
+msgid "Serialized"
+msgstr ""
+
msgid "Session locked"
msgstr "Sessione bloccata"
@@ -1338,6 +1497,9 @@ msgstr "Imposta orario di uscita"
msgid "Set up in Carbon"
msgstr "Configura in Carbon"
+msgid "Set when the batch was planned."
+msgstr "Impostato quando il Lotto di produzione è stato pianificato."
+
msgid "Setup"
msgstr "Attrezzaggio"
@@ -1350,6 +1512,9 @@ msgstr "Carente"
msgid "Short pick {itemName}"
msgstr "Prelievo breve {itemName}"
+msgid "Show description"
+msgstr ""
+
msgid "Show this overlay"
msgstr "Mostra questo pannello"
@@ -1389,6 +1554,10 @@ msgstr "Ricambi Utilizzati"
msgid "Start"
msgstr "Avvia"
+#. placeholder {0}: workTypeLabels[ eventType.toLowerCase() as keyof typeof workTypeLabels ].toLowerCase()
+msgid "Start {0}"
+msgstr ""
+
msgid "Start or pause the operation"
msgstr "Avvia o sospendi l'operazione"
@@ -1438,12 +1607,22 @@ msgstr "Etichetta"
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "La quantità completata per questa operazione è inferiore alla quantità richiesta di {targetQuantity}."
+msgid "The jobs and parts that make up this run."
+msgstr ""
+
+msgid "The jobs make different items — keep each job's parts apart."
+msgstr ""
+
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "Il lotto sarà contrassegnato come Superato e {remaining} unità/unità rimanente/i saranno completate in questa operazione."
msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "Il lotto sarà comunque disposizionato, ma non è possibile creare un NCR finché non è configurato almeno un tipo di problema."
+#. placeholder {0}: (batch.operations ?? []).length
+msgid "The timer and completion are shared by all {0} jobs. Steps, materials and files here are this job's own."
+msgstr ""
+
msgid "There are no available or consumed tracked parts for this material."
msgstr "Non ci sono componenti tracciati disponibili o consumati per questo materiale."
@@ -1453,6 +1632,9 @@ msgstr "Ci sono materiali tracciati per numero di serie o lotto nella distinta b
msgid "These items still have material to pick. Finishing now marks the list Partial."
msgstr "Questi articoli hanno ancora materiale da prelevare. Il completamento ora contrassegna l'elenco come Parziale."
+msgid "This batch has no work instructions."
+msgstr ""
+
msgid "This lot is expired and can't be picked."
msgstr "Questo lotto è scaduto e non può essere prelevato."
@@ -1468,6 +1650,9 @@ msgstr "Questa unità sarà permanentemente scartata e verrà creato un nuovo nu
msgid "Thumbnail"
msgstr "Miniatura"
+msgid "Tick the jobs this was done for."
+msgstr ""
+
msgid "Time and cost split across jobs proportionally to quantity."
msgstr "Tempo e costo ripartiti tra gli ordini di produzione in proporzione alla quantità."
@@ -1478,6 +1663,12 @@ msgstr "Registrazioni Orarie"
msgid "Time Worked: {0}"
msgstr "Tempo Lavorato: {0}"
+msgid "To pick"
+msgstr ""
+
+msgid "To run"
+msgstr ""
+
msgid "Today"
msgstr "Oggi"
@@ -1487,6 +1678,9 @@ msgstr "Attiva/disattiva la barra laterale"
msgid "Tools"
msgstr "Utensili"
+msgid "Total"
+msgstr ""
+
msgid "Total Quantity"
msgstr "Quantità Totale"
@@ -1501,6 +1695,9 @@ msgstr "Totale: {0}"
msgid "Tracked Entity"
msgstr "Entità Tracciata"
+msgid "tracked lines"
+msgstr "Righe tracciate"
+
msgid "Tracking"
msgstr "Tracciamento"
@@ -1572,6 +1769,12 @@ msgstr "Caricamento di {0}"
msgid "Use a different account"
msgstr "Usa un account diverso"
+msgid "Used automatically at completion"
+msgstr ""
+
+msgid "Value"
+msgstr ""
+
msgid "Verify"
msgstr "Verifica"
@@ -1584,6 +1787,9 @@ msgstr "Ti abbiamo inviato un link di accesso al tuo account."
msgid "What is {translatedTerm}?"
msgstr "Cos'è {translatedTerm}?"
+msgid "Whole batch"
+msgstr "Intero Lotto di produzione"
+
msgid "WIP"
msgstr "WIP"
@@ -1593,6 +1799,9 @@ msgstr "Centro di Lavoro"
msgid "Work Center Displays"
msgstr "Display del Centro di Lavoro"
+msgid "Work instructions"
+msgstr "Istruzioni di lavoro"
+
msgid "Yes"
msgstr "Sì"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index b6bac44fb3..6aa14ab293 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -111,6 +111,10 @@ msgstr "{0}が正常に削除されました"
msgid "{0} draft journal entries"
msgstr "{0}件の下書き仕訳"
+#. placeholder {0}: op.description
+msgid "{0} has no supplier"
+msgstr ""
+
#. placeholder {0}: formatter.format(onHand)
#. placeholder {1}: formatter.format(assembliesInStock)
#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
@@ -141,6 +145,10 @@ msgstr "{0} 件/{1} 件の転記勘定がマップされました"
msgid "{0} of {maxSlots} provider slots used"
msgstr "{0}個の{maxSlots}プロバイダースロットが使用されています"
+#. placeholder {0}: pendingJobs.length
+msgid "{0} of {memberCount} member jobs are not completed yet — their output stays out of stock until each job is completed."
+msgstr "{memberCount}個の製造指図のうち{0}件がまだ完了していません。各製造指図が完了するまで、それらの出力は在庫に入りません。"
+
#. placeholder {0}: selected.length
msgid "{0} operations · {totalQuantity} parts"
msgstr "{0} 工程 · {totalQuantity} 部品"
@@ -1652,6 +1660,10 @@ msgstr "すべてのアイテム"
msgid "All Locations"
msgstr "すべての場所"
+#. placeholder {0}: tracked[0]?.itemReadableId ?? ""
+msgid "all make {0}"
+msgstr "すべて内製 {0}"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "選択されたグループのすべてのメンバーと選択された個人が承認リクエストを承認できます"
@@ -3550,6 +3562,9 @@ msgstr "メールを確認してください"
msgid "Checking Stripe for this customer…"
msgstr "この得意先の Stripe を確認中…"
+msgid "Checking the batch's jobs..."
+msgstr "バッチの製造指図を確認しています..."
+
msgid "Checkpoint ·"
msgstr "チェックポイント ·"
@@ -3574,6 +3589,10 @@ msgstr "左側の行を選択して、在庫がどこから来るかを確認し
msgid "Choose a serial number"
msgstr "シリアル番号を選択"
+#. placeholder {0}: op.description
+msgid "choose a supplier for {0} on the job"
+msgstr ""
+
msgid "Choose another file"
msgstr "別のファイルを選択"
@@ -3736,6 +3755,9 @@ msgstr "列"
msgid "Combine filters"
msgstr "絞り込みを組み合わせ"
+msgid "Combine output into one lot"
+msgstr "出力を1つのロットに統合"
+
msgid "Coming soon"
msgstr "近日公開予定"
@@ -4526,6 +4548,9 @@ msgstr "{0}個の値を作成"
msgid "Create & Release"
msgstr "作成 & リリース"
+msgid "Create & release batch"
+msgstr "バッチを作成してリリース"
+
msgid "Create & Snapshot"
msgstr "作成とスナップショット"
@@ -4598,6 +4623,9 @@ msgstr "製造指図を作成"
msgid "Create Kanban"
msgstr "かんばんを作成"
+msgid "Create New"
+msgstr "新規作成"
+
msgid "Create new rule"
msgstr "新しいルールを作成"
@@ -6269,6 +6297,12 @@ msgstr "例:Zebra 2x1"
msgid "Each cell is the people assigned against the people the day's work needs."
msgstr "各セルは、その日の作業に必要な人員に対して配置された人員です"
+msgid "Each job keeps its own lot. The shop floor can't change these."
+msgstr "各製造指図は独自のロットを保持します。製造現場は変更できません。"
+
+msgid "Each job needs its own lot number — or combine them into one lot."
+msgstr "各製造指図は独自のロット番号が必要です。または1つのロットに統合します。"
+
msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."
msgstr "各明細はこの会社のデータから、それが所有していない行へのリンクです。これらの行を含むバックアップは復元できません。"
@@ -6281,6 +6315,9 @@ msgstr "各操作の未使用材料は操作が完了するとすぐに戻され
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "各物理的な個が独自の追跡対象と一意番号を取得します。1 追跡対象 = 1 個。"
+msgid "Each supplier's outside operations from every job go on one new purchase order, or on an existing draft you choose."
+msgstr "各仕入先の全製造指図からの外注工程は、1つの新規発注書、または選択した既存の下書きに計上されます。"
+
msgid "Each, lb, ft…"
msgstr "各、ポンド、フィート…"
@@ -7027,6 +7064,9 @@ msgstr "その他すべて"
msgid "Everything else covers people, imports, integrations and the API — anything that is not one of your workflows."
msgstr "その他はすべて、人員、インポート、連携、およびAPI(ワークフロー以外のすべて)をカバーしています。"
+msgid "Everything this run makes lands in one lot. The shop floor can't change it."
+msgstr "このランで製造されるすべてが1つのロットに入ります。製造現場は変更できません。"
+
msgid "Exceeds {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB total — remove some attachments to send."
msgstr "{PO_EMAIL_ATTACHMENT_LIMIT_MB} MBを超えています。送信するために一部の添付ファイルを除去してください。"
@@ -7804,6 +7844,9 @@ msgstr "ビューに合わせる"
msgid "Fix the problems with this workflow before testing it"
msgstr "テストする前に、このワークフローの問題を修正してください"
+msgid "Fix these jobs before releasing"
+msgstr "リリースする前にこれらの製造指図を修正してください"
+
msgid "Fixed"
msgstr "固定"
@@ -9610,7 +9653,7 @@ msgid "Lines"
msgstr "行"
msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."
-msgstr "発注書入荷が転記済になった後、ここに明細が表示されます。別の仕入先返却で既に認可された数量は表示されません。盲目的な返却には明細を追加を使用してください。"
+msgstr "発注書の入荷が転記済になると、ここに明細が表示されます。ただし、他の仕入先返品で既に承認されていない数量のみです。その他の返品の場合は「明細を追加」を使用してください。"
msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."
msgstr "受注出荷が転記された後に、別のRMAで既に認可されていない数量のみが表示されます。目隠し返品の場合は「明細を追加」を使用してください。"
@@ -9806,6 +9849,9 @@ msgstr "失注"
msgid "Lot"
msgstr "ロット"
+msgid "Lot number"
+msgstr "ロット番号"
+
msgid "Lot size"
msgstr "ロットサイズ"
@@ -9986,6 +10032,9 @@ msgstr "メーカー部品番号"
msgid "Manufacturing"
msgstr "製造"
+msgid "manufacturing is blocked"
+msgstr "製造がブロックされています"
+
msgid "Map accounts"
msgstr "勘定をマップ"
@@ -10275,6 +10324,13 @@ msgstr "メモID"
msgid "Merchant"
msgstr "マーチャント"
+#. placeholder {0}: getItemReadableId(items, itemId) ?? itemId
+msgid "Merge {0} lots"
+msgstr ""
+
+msgid "Merge output lots"
+msgstr "出力ロットをマージ"
+
msgid "MES"
msgstr "MES"
@@ -11264,6 +11320,10 @@ msgstr "オープン受注明細がありません"
msgid "No operations found."
msgstr "工程が見つかりません。"
+#. placeholder {0}: job.missingAssemblies .map((m) => m.description) .join(", ")
+msgid "no operations on {0}"
+msgstr "{0}に工程がありません"
+
msgid "No operations require picking at this location"
msgstr "この拠点でピッキングが必要な工程はありません"
@@ -11385,7 +11445,7 @@ msgid "No results found"
msgstr "検索結果が見つかりません"
msgid "No returnable lines for this customer"
-msgstr "この得意先に返却可能な明細がありません"
+msgstr "この得意先の返品対象明細がありません"
msgid "No returnable lines for this supplier"
msgstr "この仕入先に返品対象の明細がありません。"
@@ -13014,6 +13074,12 @@ msgstr "プロセス"
msgid "Procurement status — needs ordering, planned, on order, or received. The same indicator shown in the BoM tree."
msgstr "調達ステータス — 発注が必要、計画済み、発注済み、または入荷済み。BoM ツリーに表示されるものと同じインジケーター。"
+msgid "produced item"
+msgstr "製造品目"
+
+msgid "Produced item"
+msgstr "製造品目"
+
msgid "Product issues during hypercare"
msgstr "ハイパーケア中の製品の問題"
@@ -13923,6 +13989,11 @@ msgstr "{0}個のバッチをリリース"
msgid "Release Batch"
msgstr "バッチをリリース"
+#. placeholder {0}: batch.readableId
+#. placeholder {0}: releaseTarget.readableId
+msgid "Release batch {0}"
+msgstr "バッチ {0} をリリース"
+
msgid "Release change notice"
msgstr "変更通知をリリース"
@@ -13951,6 +14022,9 @@ msgstr "リリースされたリビジョン"
msgid "Released revision is locked"
msgstr "発行済みリビジョンはロック中です"
+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
+msgstr "バッチをリリースするとその製造指図がリリースされ、それぞれが製造現場に対応可能である必要があります。"
+
msgid "Remaining"
msgstr "残高"
@@ -15324,7 +15398,7 @@ msgid "Select operations"
msgstr "工程を選択"
msgid "Select posted receipt lines from this supplier to return."
-msgstr "この仕入先からの転記済の入荷明細を選択してください。"
+msgstr "この仕入先からの転記済入荷明細を返品するために選択してください。"
msgid "Select posted shipment lines to this customer to return."
msgstr "この得意先への転記済出荷明細を選択して返品する"
@@ -15523,7 +15597,7 @@ msgid "Session locked"
msgstr "セッションがロック中"
msgid "Set a customer on this return to add from a shipment."
-msgstr "この返却に得意先を設定して、出荷から追加してください。"
+msgstr "この返品に得意先を設定して出荷から追加してください。"
msgid "Set a supplier on this return to add from a receipt."
msgstr "この返品に仕入先を設定して入荷から追加"
@@ -15822,6 +15896,10 @@ msgstr "ショートカット"
msgid "Show"
msgstr "表示"
+#. placeholder {0}: overflow.length
+msgid "Show {0} more"
+msgstr ""
+
msgid "Show a readable Customer ID column on the customer list, customer forms, and dropdowns. Customers are still identified internally either way."
msgstr "得意先リスト、得意先フォーム、ドロップダウンで読みやすい得意先IDカラムを表示します。得意先はどちらの方法でも内部的に識別されます。"
@@ -16981,6 +17059,9 @@ msgstr "バックアップジョブがこのエラーを報告しました。"
msgid "The backward-computed date an operation must finish by to keep its job on time, written to the operation's due date. A stable target for measuring progress — never a constraint on placement."
msgstr "その製造指図を時間通りに保つために、工程が終了する必要のある後方計算日であり、工程の期日に書き込まれます。進捗を測定するための安定した目標であり、配置の制約ではありません。"
+msgid "The batch goes to the shop floor. Its jobs are already released."
+msgstr "バッチが製造現場に移動します。その製造指図は既にリリース済です。"
+
msgid "The batch runs at its most urgent member's time — the others are pulled early"
msgstr "バッチは最も急ぎのメンバーに合わせて実行され、他は前倒しになります"
@@ -17266,6 +17347,9 @@ msgstr "出荷が転記されるときに認識されるインベントリコス
msgid "The IRS recovery-period class for this asset under MACRS (3, 5, 7, 10, 15, 20, 27.5, 39-year)."
msgstr "MACRS(3、5、7、10、15、20、27.5、39年)に基づくこのアセットのIRS回収期間クラス。"
+msgid "The item each job produces — require it to match to merge output lots"
+msgstr "各製造指図が生産する品目 — 出力ロットをマージするには一致する必要があります"
+
msgid "the job hours due that day (a due-date basis, not the day the work runs), with overdue work in Past due."
msgstr "その日に期限切れになるジョブの時間(作業が実行される日ではなく、期限日ベース)、期限超過の作業は「期限超過」に表示されます。"
@@ -17800,6 +17884,11 @@ msgstr "これらの行は会社外のデータにリンクしているため、
msgid "this ability"
msgstr "このスキル"
+#. placeholder {0}: jobIds.length
+#. placeholder {1}: jobIds.join(", ")
+msgid "This also releases {0} jobs ({1}). They become available to the shop floor and drive purchasing and production."
+msgstr "これにより{0}個の製造指図({1})もリリースされます。それらは製造現場で利用可能になり、購買と生産を推進します。"
+
msgid "This backup could not be completed."
msgstr "このバックアップを完了できませんでした。"
diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.po
index 3d12dff796..cf3cbeb836 100644
--- a/packages/locale/locales/ja/mes.po
+++ b/packages/locale/locales/ja/mes.po
@@ -25,14 +25,28 @@ msgstr "{0} アクティブ"
msgid "{0} ago"
msgstr "{0}前"
+#. placeholder {0}: batchFacts.customers.length
+msgid "{0} customers"
+msgstr ""
+
+#. placeholder {0}: unplanned .map( (m) => (m.job as { jobId?: string | null } | null)?.jobId ) .filter(Boolean) .join(", ")
+msgid "{0} has no lot number. Set it on the batch or job in Carbon, then complete."
+msgstr "{0}にはロット番号がありません。Carbonでバッチまたは製造指図に設定してから、完了してください。"
+
+#. placeholder {0}: batchFacts.items.length
+msgid "{0} items"
+msgstr ""
+
#. placeholder {0}: (batch.operations ?? []).length
msgid "{0} jobs"
msgstr "{0} 製造指図"
+#. placeholder {0}: issuedLines.length
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
#. placeholder {1}: operation.targetQuantity
+#. placeholder {1}: trackedLines.length
msgid "{0} of {1}"
msgstr "{0} / {1}"
@@ -54,16 +68,28 @@ msgstr "{0}件がキュー待ちです"
msgid "{0} running"
msgstr "{0} 実行中"
+#. placeholder {0}: operation.jobReadableId
+#. placeholder {1}: batch.readableId
+msgid "{0} runs in batch {1}"
+msgstr ""
+
#. placeholder {0}: item.quantityScrapped
msgid "{0} Scrapped"
msgstr "{0} スクラップ"
+msgid "{completed} of {quantity}"
+msgstr "{completed} / {quantity}"
+
msgid "{completions} passed unit(s) will be completed."
msgstr "{completions}個の合格ユニットが完了します。"
msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
msgstr "{fails}件のサンプル不良が記録されており、完了されません — アクションメニューから対応してください。"
+#. placeholder {0}: step.perMember.length
+msgid "{recorded}/{0} jobs"
+msgstr ""
+
msgid "+{overflow} more"
msgstr "+{overflow} その他"
@@ -88,6 +114,10 @@ msgstr "アカウント設定"
msgid "Acknowledge & finish"
msgstr "確認して完了"
+#. placeholder {0}: members.length
+msgid "across {0} jobs"
+msgstr "{0}個の製造指図にわたって"
+
msgid "Active"
msgstr "アクティブ"
@@ -118,6 +148,13 @@ msgstr "すべて"
msgid "All clear"
msgstr "異常なし"
+msgid "All jobs"
+msgstr "すべての製造指図"
+
+#. placeholder {0}: batch.outputLotNumber
+msgid "All output goes to lot <0>{0}</0>"
+msgstr "すべての出力がロット<0>{0}</0>に入ります"
+
msgid "All rework"
msgstr "全て手直し"
@@ -166,6 +203,9 @@ msgstr "利用可能"
msgid "Available"
msgstr "利用可能"
+msgid "Back to batch"
+msgstr ""
+
msgid "Batch"
msgstr "バッチ"
@@ -179,12 +219,21 @@ msgstr "バッチ番号 {0}"
msgid "Batch number is required"
msgstr "バッチ番号は必須です"
-msgid "Batched jobs"
-msgstr "バッチ製造指図"
+msgid "Batch quantity"
+msgstr "バッチ数量"
+
+msgid "batch total"
+msgstr "バッチ合計"
msgid "Behind target by {daysBehindTarget} day(s)"
msgstr "目標より{daysBehindTarget}日遅れ"
+#. placeholder {0}: step.minValue
+#. placeholder {1}: step.maxValue
+#. placeholder {2}: step.unitOfMeasureCode ?? ""
+msgid "Between {0} and {1} {2}"
+msgstr ""
+
#. placeholder {0}: column.blockingDispatchReadableId
msgid "Blocked by {0}"
msgstr "{0} によりブロック中"
@@ -222,6 +271,9 @@ msgstr "チャット"
msgid "Check your email"
msgstr "メールを確認してください"
+msgid "Choose a job"
+msgstr ""
+
msgid "Clear"
msgstr "クリア"
@@ -249,6 +301,9 @@ msgstr "閉じる"
msgid "Collapse features table"
msgstr "機能テーブルを折りたたむ"
+msgid "Collapse panel"
+msgstr "パネルを折りたたむ"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -278,6 +333,9 @@ msgstr "完了"
msgid "Complete All"
msgstr "すべて完了"
+msgid "Complete batch"
+msgstr ""
+
msgid "Complete Batch"
msgstr "バッチを完了"
@@ -377,6 +435,9 @@ msgstr "表示"
msgid "Displays"
msgstr "表示"
+msgid "Done"
+msgstr ""
+
msgid "Down"
msgstr "停止"
@@ -409,9 +470,12 @@ msgstr "描画と機能をリサイズするためにドラッグします"
msgid "Dragging {0} cancelled."
msgstr "ドラッグ {0} キャンセル済。"
+msgid "Due"
+msgstr ""
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
msgid "Due {0}"
msgstr "期限 {0}"
@@ -434,6 +498,9 @@ msgstr "シリアル番号の複製"
msgid "Duration"
msgstr "時間"
+msgid "Each job's output is its own lot — keep each job's parts apart."
+msgstr ""
+
msgid "Edit"
msgstr "編集"
@@ -449,6 +516,9 @@ msgstr "作業区が空です"
msgid "End Operations"
msgstr "工程を終了"
+msgid "Enter each job's value, or fill every job at once from the first row. Empty rows are skipped."
+msgstr ""
+
#. placeholder {0}: selectedPerson.name
msgid "Enter PIN for {0}"
msgstr "{0} のPINを入力"
@@ -465,12 +535,18 @@ msgstr "エラー"
msgid "Estimated"
msgstr "見積"
+msgid "Every job in the batch follows these steps. Record a step for all of them at once."
+msgstr ""
+
msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
msgstr "すべてのユニットに判定があります: {passes}件が合格し、{fails}件が不合格です。ロットは各ユニットが独自の結果にルーティングされて終了します。"
msgid "Expand features table"
msgstr "機能テーブルを展開"
+msgid "Expand panel"
+msgstr "パネルを展開"
+
msgid "Expired"
msgstr "期限切れ"
@@ -511,6 +587,10 @@ msgstr "測定の保存に失敗しました"
msgid "Failed to save result"
msgstr "結果の保存に失敗しました"
+#. placeholder {0}: file.name
+msgid "Failed to upload {0}"
+msgstr ""
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "ファイルのアップロードに失敗しました: {0}"
@@ -555,6 +635,10 @@ msgstr "アカウントのセットアップを完了する"
msgid "Finish with material unpicked?"
msgstr "材料がピッキングされていない状態で終了しますか?"
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(batchFacts.dueDate) )
+msgid "First due {0}"
+msgstr ""
+
msgid "Forgot to Clock Out?"
msgstr "作業終了を忘れていませんか?"
@@ -567,6 +651,9 @@ msgstr "操作に戻る"
msgid "Go to onboarding"
msgstr "オンボーディングに移動"
+msgid "Hide description"
+msgstr ""
+
msgid "How many were actually picked?"
msgstr "実際にはいくつ選ばれましたか?"
@@ -631,6 +718,9 @@ msgstr "材料払出"
msgid "Issue Type"
msgstr "問題タイプ"
+msgid "Issued"
+msgstr "発行済み"
+
msgid "Issued {issuedQuantity} of {lotLabel}"
msgstr "{lotLabel} から {issuedQuantity} を発行しました"
@@ -688,6 +778,9 @@ msgstr "行"
msgid "List view"
msgstr "リスト表示"
+msgid "Load list"
+msgstr ""
+
msgid "Loading item details..."
msgstr "品目詳細を読み込み中..."
@@ -700,6 +793,9 @@ msgstr "ローカル"
msgid "Location"
msgstr "ロケーション"
+msgid "Log completed"
+msgstr ""
+
msgid "Log Completed"
msgstr "完了を記録"
@@ -727,6 +823,12 @@ msgstr "ログイン"
msgid "Lot"
msgstr "ロット"
+msgid "Lot numbers missing"
+msgstr "ロット番号がありません"
+
+msgid "Lot tracked"
+msgstr ""
+
msgid "Machine"
msgstr "機械"
@@ -763,6 +865,9 @@ msgstr "が一致"
msgid "Materials"
msgstr "材料"
+msgid "Materials issued"
+msgstr "発行済み材料"
+
msgid "Maximum number of records reached"
msgstr "レコードの最大数に達しました"
@@ -866,6 +971,9 @@ msgstr "一致するものがありません。入力して新しく作成して
msgid "No materials"
msgstr "材料なし"
+msgid "No materials on this batch."
+msgstr "このバッチに材料がありません。"
+
msgid "No open jobs"
msgstr "オープンな製造指図はありません。"
@@ -959,9 +1067,22 @@ msgstr "OEE影響度"
msgid "OEM Required"
msgstr "OEM対応必要"
+#. placeholder {0}: m.operationQuantity ?? 0
+msgid "of {0}"
+msgstr ""
+
msgid "Oldest first"
msgstr "最も古い順"
+msgid "one combined lot · planned"
+msgstr "1つの統合ロット · 計画済"
+
+msgid "one per job · planned"
+msgstr "1つ/製造指図 · 計画済"
+
+msgid "One pick covers the whole batch — it is shared out to the jobs automatically."
+msgstr ""
+
#. placeholder {0}: batch.quantity
msgid "Only {0} available"
msgstr "{0} のみ利用可能"
@@ -975,6 +1096,9 @@ msgstr "未対応"
msgid "Open a display on the screen mounted at the work center and leave it running. Each board refreshes on its own."
msgstr "作業区に設置されたスクリーン上にディスプレイを表示して、実行し続けてください。各ボードは自動的に更新されます。"
+msgid "Open a job in this batch"
+msgstr ""
+
msgid "Open an NCR for MRB disposition"
msgstr "MRB処置のためにNCRを開く"
@@ -999,6 +1123,9 @@ msgstr "オプション"
msgid "or"
msgstr "または"
+msgid "Output lot"
+msgstr "出力ロット"
+
msgid "Overall result"
msgstr "全体的な結果"
@@ -1017,6 +1144,9 @@ msgstr "一部"
msgid "Partial Disposition"
msgstr "一部処置"
+msgid "Passed inspection"
+msgstr ""
+
msgid "Passed Inspection"
msgstr "検査合格"
@@ -1029,6 +1159,10 @@ msgstr "一時停止"
msgid "Pick"
msgstr "ピック"
+#. placeholder {0}: m.required - m.issued
+msgid "Pick {0}"
+msgstr "ピッキング {0}"
+
msgid "Pick tracked item"
msgstr "追跡品目をピック"
@@ -1098,6 +1232,9 @@ msgstr "手順書"
msgid "Process"
msgstr "プロセス"
+msgid "Process parameters"
+msgstr "工法パラメータ"
+
msgid "Process Parameters"
msgstr "プロセスパラメーター"
@@ -1140,18 +1277,28 @@ msgstr "記録"
msgid "Record {0}"
msgstr "レコード {0}"
+#. placeholder {0}: changed.length
+msgid "Record {0} jobs"
+msgstr ""
+
msgid "Record only"
msgstr "記録のみ"
msgid "Record Partial"
msgstr "一部を記録"
+msgid "Recorded"
+msgstr ""
+
msgid "Reject"
msgstr "却下"
msgid "Reject Lot"
msgstr "ロットを却下"
+msgid "Released"
+msgstr ""
+
msgid "Remove"
msgstr "除去"
@@ -1167,6 +1314,9 @@ msgstr "部品を除去"
msgid "Reopen the subassembly and create a replacement unit"
msgstr "サブアセンブリを再オープンし、代替品を作成"
+msgid "Required"
+msgstr "必須"
+
msgid "Result"
msgstr "結果"
@@ -1188,6 +1338,9 @@ msgstr "実行中"
msgid "Sales Order"
msgstr "受注"
+msgid "Same for every job"
+msgstr ""
+
msgid "Save"
msgstr "保存"
@@ -1307,6 +1460,9 @@ msgstr "送信"
msgid "Send to Carbon"
msgstr "Carbonに送信"
+msgid "Separate lots"
+msgstr "個別のロット"
+
msgid "Serial"
msgstr "シリアル"
@@ -1326,6 +1482,9 @@ msgstr "シリアル番号"
msgid "Serial Numbers"
msgstr "シリアル番号"
+msgid "Serialized"
+msgstr ""
+
msgid "Session locked"
msgstr "セッションはロック中です。"
@@ -1338,6 +1497,9 @@ msgstr "退勤時間を設定"
msgid "Set up in Carbon"
msgstr "Carbonで設定"
+msgid "Set when the batch was planned."
+msgstr "バッチが計画されたときに設定します。"
+
msgid "Setup"
msgstr "段取り"
@@ -1350,6 +1512,9 @@ msgstr "不足"
msgid "Short pick {itemName}"
msgstr "短いピック {itemName}"
+msgid "Show description"
+msgstr ""
+
msgid "Show this overlay"
msgstr "このオーバーレイを表示"
@@ -1389,6 +1554,10 @@ msgstr "使用予備品"
msgid "Start"
msgstr "開始"
+#. placeholder {0}: workTypeLabels[ eventType.toLowerCase() as keyof typeof workTypeLabels ].toLowerCase()
+msgid "Start {0}"
+msgstr ""
+
msgid "Start or pause the operation"
msgstr "工程を開始 / 一時停止"
@@ -1438,12 +1607,22 @@ msgstr "タグ"
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "この工程の完了数量が必要数量 {targetQuantity} を下回っています。"
+msgid "The jobs and parts that make up this run."
+msgstr ""
+
+msgid "The jobs make different items — keep each job's parts apart."
+msgstr ""
+
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "ロットは「合格」とマークされ、{remaining}個の残りユニットがこの工程で完了します。"
msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "ロットは引き続き処分されますが、少なくとも1つの問題タイプが設定されるまでNCRを作成することはできません。"
+#. placeholder {0}: (batch.operations ?? []).length
+msgid "The timer and completion are shared by all {0} jobs. Steps, materials and files here are this job's own."
+msgstr ""
+
msgid "There are no available or consumed tracked parts for this material."
msgstr "このマテリアルについて、利用可能または消費済みの追跡部品がありません。"
@@ -1453,6 +1632,9 @@ msgstr "部品表にシリアルまたはバッチ追跡対象の材料が完全
msgid "These items still have material to pick. Finishing now marks the list Partial."
msgstr "これらの品目にはまだピッキングする材料があります。今、完了するとリストが一部としてマークされます。"
+msgid "This batch has no work instructions."
+msgstr ""
+
msgid "This lot is expired and can't be picked."
msgstr "このロットは期限切れであり、ピックできません。"
@@ -1468,6 +1650,9 @@ msgstr "このユニットは永久にスクラップされ、代替シリアル
msgid "Thumbnail"
msgstr "サムネイル"
+msgid "Tick the jobs this was done for."
+msgstr ""
+
msgid "Time and cost split across jobs proportionally to quantity."
msgstr "時間と原価が数量に比例して製造指図全体に分配されます。"
@@ -1478,6 +1663,12 @@ msgstr "タイムエントリー"
msgid "Time Worked: {0}"
msgstr "作業時間: {0}"
+msgid "To pick"
+msgstr ""
+
+msgid "To run"
+msgstr ""
+
msgid "Today"
msgstr "今日"
@@ -1487,6 +1678,9 @@ msgstr "サイドバーの表示/非表示を切り替える"
msgid "Tools"
msgstr "工具"
+msgid "Total"
+msgstr ""
+
msgid "Total Quantity"
msgstr "合計数量"
@@ -1501,6 +1695,9 @@ msgstr "合計: {0}"
msgid "Tracked Entity"
msgstr "追跡対象"
+msgid "tracked lines"
+msgstr "追跡対象の明細"
+
msgid "Tracking"
msgstr "追跡"
@@ -1572,6 +1769,12 @@ msgstr "{0} をアップロード中"
msgid "Use a different account"
msgstr "別のアカウントを使用"
+msgid "Used automatically at completion"
+msgstr ""
+
+msgid "Value"
+msgstr ""
+
msgid "Verify"
msgstr "確認"
@@ -1584,6 +1787,9 @@ msgstr "アカウントにサインインするためのマジックリンクを
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm}とは何ですか?"
+msgid "Whole batch"
+msgstr "バッチ全体"
+
msgid "WIP"
msgstr "仕掛品"
@@ -1593,6 +1799,9 @@ msgstr "作業区"
msgid "Work Center Displays"
msgstr "作業区ディスプレイ"
+msgid "Work instructions"
+msgstr "作業手順書"
+
msgid "Yes"
msgstr "はい"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 754b774301..7801ac8c7d 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -111,6 +111,10 @@ msgstr "{0}이(가) 삭제되었습니다"
msgid "{0} draft journal entries"
msgstr "{0}개의 초안 전표"
+#. placeholder {0}: op.description
+msgid "{0} has no supplier"
+msgstr ""
+
#. placeholder {0}: formatter.format(onHand)
#. placeholder {1}: formatter.format(assembliesInStock)
#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
@@ -141,6 +145,10 @@ msgstr "{0}개의 {1}개 전기 계정 매핑됨"
msgid "{0} of {maxSlots} provider slots used"
msgstr "{0}개 중 {maxSlots}개 제공자 슬롯 사용됨"
+#. placeholder {0}: pendingJobs.length
+msgid "{0} of {memberCount} member jobs are not completed yet — their output stays out of stock until each job is completed."
+msgstr "{memberCount}개의 작업 지시 중 {0}개가 아직 완료되지 않았습니다 — 각 작업 지시가 완료될 때까지 산출물은 재고로 집계되지 않습니다."
+
#. placeholder {0}: selected.length
msgid "{0} operations · {totalQuantity} parts"
msgstr "{0}개 공정 · {totalQuantity}개 부품"
@@ -1652,6 +1660,10 @@ msgstr "모든 품목"
msgid "All Locations"
msgstr "모든 위치"
+#. placeholder {0}: tracked[0]?.itemReadableId ?? ""
+msgid "all make {0}"
+msgstr "모두 사내 생산 {0}"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "선택한 그룹의 모든 구성원과 선택한 개인이 요청을 승인할 수 있습니다"
@@ -3550,6 +3562,9 @@ msgstr "이메일을 확인하세요"
msgid "Checking Stripe for this customer…"
msgstr "이 고객의 Stripe 확인 중…"
+msgid "Checking the batch's jobs..."
+msgstr "배치의 작업 지시 확인 중..."
+
msgid "Checkpoint ·"
msgstr "체크포인트 ·"
@@ -3574,6 +3589,10 @@ msgstr "왼쪽의 행을 선택하여 해당 재고가 어디서 올 수 있는
msgid "Choose a serial number"
msgstr "시리얼 번호를 선택하십시오"
+#. placeholder {0}: op.description
+msgid "choose a supplier for {0} on the job"
+msgstr ""
+
msgid "Choose another file"
msgstr "다른 파일을 선택하세요"
@@ -3736,6 +3755,9 @@ msgstr "열"
msgid "Combine filters"
msgstr "필터 결합"
+msgid "Combine output into one lot"
+msgstr "산출물을 한 로트로 병합"
+
msgid "Coming soon"
msgstr "출시 예정"
@@ -4526,6 +4548,9 @@ msgstr "{0} 값 생성"
msgid "Create & Release"
msgstr "생성 & 릴리스"
+msgid "Create & release batch"
+msgstr "배치 생성 및 릴리스"
+
msgid "Create & Snapshot"
msgstr "생성 및 스냅샷"
@@ -4598,6 +4623,9 @@ msgstr "작업 지시 생성"
msgid "Create Kanban"
msgstr "칸반 생성"
+msgid "Create New"
+msgstr "새로 생성"
+
msgid "Create new rule"
msgstr "새 규칙 생성"
@@ -6269,6 +6297,12 @@ msgstr "예: Zebra 2x1"
msgid "Each cell is the people assigned against the people the day's work needs."
msgstr "각 셀은 그 날 일에 필요한 인원 대비 할당된 인원입니다."
+msgid "Each job keeps its own lot. The shop floor can't change these."
+msgstr "각 작업 지시는 자체 로트를 유지합니다. 현장에서 이를 변경할 수 없습니다."
+
+msgid "Each job needs its own lot number — or combine them into one lot."
+msgstr "각 작업 지시는 자체 로트 번호가 필요합니다. 또는 이들을 한 로트로 결합할 수 있습니다."
+
msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."
msgstr "각 라인은 이 회사 데이터에서 소유하지 않은 행으로의 링크입니다. 이 행들이 포함된 백업은 복원할 수 없습니다."
@@ -6281,6 +6315,9 @@ msgstr "각 작업의 미사용 재료는 해당 작업이 완료되는 즉시
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "각 물리적 개는 자신의 추적 대상과 고유 번호를 받습니다 — 하나의 추적 대상, 하나의 개."
+msgid "Each supplier's outside operations from every job go on one new purchase order, or on an existing draft you choose."
+msgstr "각 공급업체의 외주 공정은 모든 작업 지시에서 새로운 발주서 하나에 배치되거나 선택한 기존 초안에 배치됩니다."
+
msgid "Each, lb, ft…"
msgstr "개, lb, ft…"
@@ -7027,6 +7064,9 @@ msgstr "그 외 모든 것"
msgid "Everything else covers people, imports, integrations and the API — anything that is not one of your workflows."
msgstr "그 외 모든 것은 인원, 가져오기, 연동 및 API를 다룹니다 — 워크플로 중 하나가 아닌 모든 것입니다."
+msgid "Everything this run makes lands in one lot. The shop floor can't change it."
+msgstr "이 작업이 생산하는 모든 것은 한 로트로 분류됩니다. 현장에서 이를 변경할 수 없습니다."
+
msgid "Exceeds {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB total — remove some attachments to send."
msgstr "총 {PO_EMAIL_ATTACHMENT_LIMIT_MB}MB를 초과합니다 — 발송하려면 일부 첨부 파일을 제거하세요."
@@ -7804,6 +7844,9 @@ msgstr "보기에 맞춤"
msgid "Fix the problems with this workflow before testing it"
msgstr "테스트하기 전에 이 워크플로우의 문제를 해결하십시오"
+msgid "Fix these jobs before releasing"
+msgstr "릴리스하기 전에 이 작업 지시들을 수정하세요"
+
msgid "Fixed"
msgstr "고정"
@@ -9610,7 +9653,7 @@ msgid "Lines"
msgstr "라인"
msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."
-msgstr "발주서 입고가 전기됨되면 라인이 여기에 표시되며, 다른 공급업체 반품에서 아직 승인되지 않은 수량에 대해서만 표시됩니다. 맹검 반품의 경우 라인 추가를 사용하세요."
+msgstr "발주서 입고가 전기된 후 라인이 여기에 표시되며, 다른 공급업체 반품에서 아직 승인되지 않은 수량에만 표시됩니다. 맹목적 반품의 경우 라인 품목 추가를 사용하세요."
msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."
msgstr "수주 출하가 전기된 후 라인이 여기에 나타나며, 다른 RMA에서 이미 승인되지 않은 수량만 나타납니다. 맹목적 반품의 경우 「라인 항목 추가」를 사용하세요."
@@ -9806,6 +9849,9 @@ msgstr "실주"
msgid "Lot"
msgstr "로트"
+msgid "Lot number"
+msgstr "로트 번호"
+
msgid "Lot size"
msgstr "로트 크기"
@@ -9986,6 +10032,9 @@ msgstr "제조사 부품 번호"
msgid "Manufacturing"
msgstr "제조"
+msgid "manufacturing is blocked"
+msgstr "제조가 차단되었습니다"
+
msgid "Map accounts"
msgstr "계정 매핑"
@@ -10275,6 +10324,13 @@ msgstr "메모 ID"
msgid "Merchant"
msgstr "가맹점"
+#. placeholder {0}: getItemReadableId(items, itemId) ?? itemId
+msgid "Merge {0} lots"
+msgstr ""
+
+msgid "Merge output lots"
+msgstr "생산 로트 병합"
+
msgid "MES"
msgstr "MES"
@@ -11264,6 +11320,10 @@ msgstr "미결 수주 라인이 없습니다."
msgid "No operations found."
msgstr "공정을 찾을 수 없습니다."
+#. placeholder {0}: job.missingAssemblies .map((m) => m.description) .join(", ")
+msgid "no operations on {0}"
+msgstr "{0}에 공정이 없습니다"
+
msgid "No operations require picking at this location"
msgstr "이 위치에서 피킹이 필요한 공정작업이 없습니다"
@@ -11388,7 +11448,7 @@ msgid "No returnable lines for this customer"
msgstr "이 고객에 대한 반품 가능 라인이 없습니다."
msgid "No returnable lines for this supplier"
-msgstr "이 공급업체에 대해 반품 가능한 라인이 없습니다."
+msgstr "이 공급업체에 대한 반품 가능 라인이 없습니다."
msgid "No returnable lines match your search"
msgstr "검색과 일치하는 반품 가능한 라인이 없습니다."
@@ -13014,6 +13074,12 @@ msgstr "공정"
msgid "Procurement status — needs ordering, planned, on order, or received. The same indicator shown in the BoM tree."
msgstr "조달 상태 — 주문 필요, 계획됨, 주문됨, 입고됨 중 하나입니다. BOM 트리에 표시되는 것과 동일한 지표입니다."
+msgid "produced item"
+msgstr "생산된 품목"
+
+msgid "Produced item"
+msgstr "생산된 품목"
+
msgid "Product issues during hypercare"
msgstr "하이퍼케어 기간 중 발생한 제품 이슈"
@@ -13923,6 +13989,11 @@ msgstr "{0}개 배치 릴리스"
msgid "Release Batch"
msgstr "배치 릴리스"
+#. placeholder {0}: batch.readableId
+#. placeholder {0}: releaseTarget.readableId
+msgid "Release batch {0}"
+msgstr "배치 {0} 릴리스"
+
msgid "Release change notice"
msgstr "변경 통지 릴리스"
@@ -13951,6 +14022,9 @@ msgstr "릴리스된 리비전"
msgid "Released revision is locked"
msgstr "릴리스된 리비전은 잠김입니다."
+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
+msgstr "배치를 릴리스하면 포함된 작업 지시들도 릴리스되고, 각각은 현장에 준비되어야 합니다."
+
msgid "Remaining"
msgstr "남음"
@@ -15324,7 +15398,7 @@ msgid "Select operations"
msgstr "공정 선택"
msgid "Select posted receipt lines from this supplier to return."
-msgstr "이 공급업체로부터 반품할 전기됨된 입고 라인을 선택하세요."
+msgstr "이 공급업체에서 전기된 입고 라인을 선택하여 반품하세요."
msgid "Select posted shipment lines to this customer to return."
msgstr "이 고객의 전기된 출하 라인을 선택하여 반품하세요."
@@ -15822,6 +15896,10 @@ msgstr "단축키"
msgid "Show"
msgstr "표시"
+#. placeholder {0}: overflow.length
+msgid "Show {0} more"
+msgstr ""
+
msgid "Show a readable Customer ID column on the customer list, customer forms, and dropdowns. Customers are still identified internally either way."
msgstr "고객 목록, 고객 양식, 드롭다운에 읽기 쉬운 고객 ID 열을 표시합니다. 어느 쪽이든 고객은 내부적으로 동일하게 식별됩니다."
@@ -16981,6 +17059,9 @@ msgstr "백업 작업이 이 오류를 보고했습니다."
msgid "The backward-computed date an operation must finish by to keep its job on time, written to the operation's due date. A stable target for measuring progress — never a constraint on placement."
msgstr "공정이 작업 지시를 제때 완료하기 위해 마감일까지 완료되어야 하는 역계산된 날짜이며 공정의 마감일에 기록됩니다. 진행 상황을 측정하기 위한 안정적인 목표 — 배치에 대한 제약 조건이 아닙니다."
+msgid "The batch goes to the shop floor. Its jobs are already released."
+msgstr "배치가 현장으로 이동합니다. 포함된 작업 지시들은 이미 릴리스되었습니다."
+
msgid "The batch runs at its most urgent member's time — the others are pulled early"
msgstr "배치는 가장 급한 항목의 일정에 맞춰 실행되며 나머지는 앞당겨집니다"
@@ -17266,6 +17347,9 @@ msgstr "출하가 전기될 때 인식되는 재고 원가로, 품목의 원가
msgid "The IRS recovery-period class for this asset under MACRS (3, 5, 7, 10, 15, 20, 27.5, 39-year)."
msgstr "MACRS(수정가속상각법)에 따른 이 자산의 IRS 내용연수 등급(3, 5, 7, 10, 15, 20, 27.5, 39년)입니다."
+msgid "The item each job produces — require it to match to merge output lots"
+msgstr "각 작업 지시가 생산하는 품목 — 출력 로트를 병합하기 위해 일치 필수"
+
msgid "the job hours due that day (a due-date basis, not the day the work runs), with overdue work in Past due."
msgstr "그 날에 마감될 작업 지시 시간(작업이 실행되는 날이 아닌 마감일 기준)이며, 기한 초과 작업은 기한 초과 섹션에 표시됩니다."
@@ -17800,6 +17884,11 @@ msgstr "이 행들은 회사 외부의 데이터와 연결되어 있어 복원
msgid "this ability"
msgstr "이 역량"
+#. placeholder {0}: jobIds.length
+#. placeholder {1}: jobIds.join(", ")
+msgid "This also releases {0} jobs ({1}). They become available to the shop floor and drive purchasing and production."
+msgstr "또한 {0}개의 작업 지시({1})를 릴리스합니다. 현장에 가용하게 되어 구매 및 생산을 추진합니다."
+
msgid "This backup could not be completed."
msgstr "이 백업을 완료할 수 없습니다."
diff --git a/packages/locale/locales/ko/mes.po b/packages/locale/locales/ko/mes.po
index 5f8b391d97..73cd23727b 100644
--- a/packages/locale/locales/ko/mes.po
+++ b/packages/locale/locales/ko/mes.po
@@ -25,14 +25,28 @@ msgstr "{0} 활성"
msgid "{0} ago"
msgstr "{0} 전"
+#. placeholder {0}: batchFacts.customers.length
+msgid "{0} customers"
+msgstr ""
+
+#. placeholder {0}: unplanned .map( (m) => (m.job as { jobId?: string | null } | null)?.jobId ) .filter(Boolean) .join(", ")
+msgid "{0} has no lot number. Set it on the batch or job in Carbon, then complete."
+msgstr "{0}에 로트 번호가 없습니다. Carbon에서 배치 또는 작업 지시에 설정한 다음 완료 처리하세요."
+
+#. placeholder {0}: batchFacts.items.length
+msgid "{0} items"
+msgstr ""
+
#. placeholder {0}: (batch.operations ?? []).length
msgid "{0} jobs"
msgstr "{0} 작업 지시"
+#. placeholder {0}: issuedLines.length
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
#. placeholder {1}: operation.targetQuantity
+#. placeholder {1}: trackedLines.length
msgid "{0} of {1}"
msgstr "{1} 중 {0}"
@@ -54,16 +68,28 @@ msgstr "{0} 대기열"
msgid "{0} running"
msgstr "{0} 실행 중"
+#. placeholder {0}: operation.jobReadableId
+#. placeholder {1}: batch.readableId
+msgid "{0} runs in batch {1}"
+msgstr ""
+
#. placeholder {0}: item.quantityScrapped
msgid "{0} Scrapped"
msgstr "{0} 스크랩됨"
+msgid "{completed} of {quantity}"
+msgstr "{completed} / {quantity}"
+
msgid "{completions} passed unit(s) will be completed."
msgstr "{completions}개의 통과 단위가 완료 처리될 예정입니다."
msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
msgstr "{fails}개의 샘플 불량이 기록되었으며 완료되지 않습니다 — 작업 메뉴에서 해결하세요."
+#. placeholder {0}: step.perMember.length
+msgid "{recorded}/{0} jobs"
+msgstr ""
+
msgid "+{overflow} more"
msgstr "+{overflow} 더 보기"
@@ -88,6 +114,10 @@ msgstr "계정 설정"
msgid "Acknowledge & finish"
msgstr "확인 및 완료"
+#. placeholder {0}: members.length
+msgid "across {0} jobs"
+msgstr "{0}개의 작업 지시 전체"
+
msgid "Active"
msgstr "활성"
@@ -118,6 +148,13 @@ msgstr "전체"
msgid "All clear"
msgstr "모두 정상"
+msgid "All jobs"
+msgstr "모든 작업 지시"
+
+#. placeholder {0}: batch.outputLotNumber
+msgid "All output goes to lot <0>{0}</0>"
+msgstr "모든 산출물이 로트 <0>{0}</0>로 이동합니다."
+
msgid "All rework"
msgstr "모두 재작업"
@@ -166,6 +203,9 @@ msgstr "가용"
msgid "Available"
msgstr "가용"
+msgid "Back to batch"
+msgstr ""
+
msgid "Batch"
msgstr "배치"
@@ -179,12 +219,21 @@ msgstr "배치 번호 {0}"
msgid "Batch number is required"
msgstr "배치 번호가 필요합니다"
-msgid "Batched jobs"
-msgstr "일괄 작업 지시"
+msgid "Batch quantity"
+msgstr "배치 수량"
+
+msgid "batch total"
+msgstr "배치 총계"
msgid "Behind target by {daysBehindTarget} day(s)"
msgstr "목표에서 {daysBehindTarget}일 뒤짐"
+#. placeholder {0}: step.minValue
+#. placeholder {1}: step.maxValue
+#. placeholder {2}: step.unitOfMeasureCode ?? ""
+msgid "Between {0} and {1} {2}"
+msgstr ""
+
#. placeholder {0}: column.blockingDispatchReadableId
msgid "Blocked by {0}"
msgstr "{0}에 의해 차단됨"
@@ -222,6 +271,9 @@ msgstr "채팅"
msgid "Check your email"
msgstr "이메일을 확인하세요"
+msgid "Choose a job"
+msgstr ""
+
msgid "Clear"
msgstr "지우기"
@@ -249,6 +301,9 @@ msgstr "닫기"
msgid "Collapse features table"
msgstr "기능 테이블 축소"
+msgid "Collapse panel"
+msgstr "패널 축소"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -278,6 +333,9 @@ msgstr "완료"
msgid "Complete All"
msgstr "모두 완료"
+msgid "Complete batch"
+msgstr ""
+
msgid "Complete Batch"
msgstr "배치 완료"
@@ -377,6 +435,9 @@ msgstr "표시"
msgid "Displays"
msgstr "디스플레이"
+msgid "Done"
+msgstr ""
+
msgid "Down"
msgstr "가동중단"
@@ -409,9 +470,12 @@ msgstr "그리기 및 기능 크기 조정하려면 드래그하세요"
msgid "Dragging {0} cancelled."
msgstr "{0} 드래그 취소됨."
+msgid "Due"
+msgstr ""
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
msgid "Due {0}"
msgstr "기한 {0}"
@@ -434,6 +498,9 @@ msgstr "중복된 시리얼 번호"
msgid "Duration"
msgstr "기간"
+msgid "Each job's output is its own lot — keep each job's parts apart."
+msgstr ""
+
msgid "Edit"
msgstr "편집"
@@ -449,6 +516,9 @@ msgstr "빈 작업장"
msgid "End Operations"
msgstr "공정작업 종료"
+msgid "Enter each job's value, or fill every job at once from the first row. Empty rows are skipped."
+msgstr ""
+
#. placeholder {0}: selectedPerson.name
msgid "Enter PIN for {0}"
msgstr "{0}의 PIN 입력"
@@ -465,12 +535,18 @@ msgstr "오류"
msgid "Estimated"
msgstr "예상"
+msgid "Every job in the batch follows these steps. Record a step for all of them at once."
+msgstr ""
+
msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
msgstr "각 개는 판정을 가집니다: {passes}개 통과하고 {fails}개 불합격합니다. 로트는 각 개가 자신의 결과로 배정되면서 마감됩니다."
msgid "Expand features table"
msgstr "기능 테이블 확장"
+msgid "Expand panel"
+msgstr "패널 확대"
+
msgid "Expired"
msgstr "만료됨"
@@ -511,6 +587,10 @@ msgstr "측정값 저장 실패"
msgid "Failed to save result"
msgstr "결과 저장 실패"
+#. placeholder {0}: file.name
+msgid "Failed to upload {0}"
+msgstr ""
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "파일을 업로드하지 못했습니다: {0}"
@@ -555,6 +635,10 @@ msgstr "계정 설정을 완료하세요"
msgid "Finish with material unpicked?"
msgstr "미선택 재료가 있는 상태로 완료하시겠습니까?"
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(batchFacts.dueDate) )
+msgid "First due {0}"
+msgstr ""
+
msgid "Forgot to Clock Out?"
msgstr "작업 종료를 잊었나요?"
@@ -567,6 +651,9 @@ msgstr "공정작업으로 돌아가기"
msgid "Go to onboarding"
msgstr "온보딩으로 이동"
+msgid "Hide description"
+msgstr ""
+
msgid "How many were actually picked?"
msgstr "실제로 몇 개를 피킹했습니까?"
@@ -631,6 +718,9 @@ msgstr "자재 출고"
msgid "Issue Type"
msgstr "이슈 유형"
+msgid "Issued"
+msgstr "발급됨"
+
msgid "Issued {issuedQuantity} of {lotLabel}"
msgstr "{issuedQuantity}를 {lotLabel}에서 발급함"
@@ -688,6 +778,9 @@ msgstr "라인"
msgid "List view"
msgstr "목록 보기"
+msgid "Load list"
+msgstr ""
+
msgid "Loading item details..."
msgstr "품목 세부정보를 불러오는 중..."
@@ -700,6 +793,9 @@ msgstr "로컬"
msgid "Location"
msgstr "위치"
+msgid "Log completed"
+msgstr ""
+
msgid "Log Completed"
msgstr "완료 기록"
@@ -727,6 +823,12 @@ msgstr "로그인"
msgid "Lot"
msgstr "로트"
+msgid "Lot numbers missing"
+msgstr "로트 번호 누락"
+
+msgid "Lot tracked"
+msgstr ""
+
msgid "Machine"
msgstr "기계"
@@ -763,6 +865,9 @@ msgstr "일치"
msgid "Materials"
msgstr "자재"
+msgid "Materials issued"
+msgstr "발급된 자재"
+
msgid "Maximum number of records reached"
msgstr "최대 레코드 수에 도달했습니다"
@@ -866,6 +971,9 @@ msgstr "일치항목이 없습니다. 입력하여 새로 만드세요."
msgid "No materials"
msgstr "자재 없음"
+msgid "No materials on this batch."
+msgstr "이 배치에 자재가 없습니다."
+
msgid "No open jobs"
msgstr "미결 작업 지시가 없습니다"
@@ -959,9 +1067,22 @@ msgstr "OEE 영향"
msgid "OEM Required"
msgstr "OEM 필요"
+#. placeholder {0}: m.operationQuantity ?? 0
+msgid "of {0}"
+msgstr ""
+
msgid "Oldest first"
msgstr "오래된순"
+msgid "one combined lot · planned"
+msgstr "결합된 로트 하나 · 계획됨"
+
+msgid "one per job · planned"
+msgstr "작업 지시당 하나 · 계획됨"
+
+msgid "One pick covers the whole batch — it is shared out to the jobs automatically."
+msgstr ""
+
#. placeholder {0}: batch.quantity
msgid "Only {0} available"
msgstr "{0}개만 가용합니다"
@@ -975,6 +1096,9 @@ msgstr "열림"
msgid "Open a display on the screen mounted at the work center and leave it running. Each board refreshes on its own."
msgstr "작업장에 설치된 화면에 디스플레이를 열고 계속 실행 상태로 두세요. 각 보드는 자동으로 새로고침됩니다."
+msgid "Open a job in this batch"
+msgstr ""
+
msgid "Open an NCR for MRB disposition"
msgstr "MRB 처분 결정을 위해 NCR을 여세요"
@@ -999,6 +1123,9 @@ msgstr "선택 사항"
msgid "or"
msgstr "또는"
+msgid "Output lot"
+msgstr "출력 로트"
+
msgid "Overall result"
msgstr "전체 결과"
@@ -1017,6 +1144,9 @@ msgstr "부분"
msgid "Partial Disposition"
msgstr "부분 처분 결정"
+msgid "Passed inspection"
+msgstr ""
+
msgid "Passed Inspection"
msgstr "검사 통과"
@@ -1029,6 +1159,10 @@ msgstr "일시 중지"
msgid "Pick"
msgstr "피킹"
+#. placeholder {0}: m.required - m.issued
+msgid "Pick {0}"
+msgstr "피킹 {0}"
+
msgid "Pick tracked item"
msgstr "추적 품목 선택"
@@ -1098,6 +1232,9 @@ msgstr "절차서"
msgid "Process"
msgstr "공정"
+msgid "Process parameters"
+msgstr "공법 파라미터"
+
msgid "Process Parameters"
msgstr "공정 파라미터"
@@ -1140,18 +1277,28 @@ msgstr "기록"
msgid "Record {0}"
msgstr "{0} 기록"
+#. placeholder {0}: changed.length
+msgid "Record {0} jobs"
+msgstr ""
+
msgid "Record only"
msgstr "기록만"
msgid "Record Partial"
msgstr "부분 기록"
+msgid "Recorded"
+msgstr ""
+
msgid "Reject"
msgstr "거부"
msgid "Reject Lot"
msgstr "로트 거부"
+msgid "Released"
+msgstr ""
+
msgid "Remove"
msgstr "제거"
@@ -1167,6 +1314,9 @@ msgstr "품목 제거"
msgid "Reopen the subassembly and create a replacement unit"
msgstr "서브어셈블리를 다시 열고 대체 부품을 생성하세요"
+msgid "Required"
+msgstr "필수"
+
msgid "Result"
msgstr "결과"
@@ -1188,6 +1338,9 @@ msgstr "실행 중"
msgid "Sales Order"
msgstr "수주"
+msgid "Same for every job"
+msgstr ""
+
msgid "Save"
msgstr "저장"
@@ -1307,6 +1460,9 @@ msgstr "전송"
msgid "Send to Carbon"
msgstr "Carbon으로 보내기"
+msgid "Separate lots"
+msgstr "별도 로트"
+
msgid "Serial"
msgstr "일련번호"
@@ -1326,6 +1482,9 @@ msgstr "시리얼 번호"
msgid "Serial Numbers"
msgstr "시리얼 번호"
+msgid "Serialized"
+msgstr ""
+
msgid "Session locked"
msgstr "세션 잠김"
@@ -1338,6 +1497,9 @@ msgstr "퇴근 시간 설정"
msgid "Set up in Carbon"
msgstr "Carbon에서 설정하기"
+msgid "Set when the batch was planned."
+msgstr "배치가 계획되었을 때 설정됩니다."
+
msgid "Setup"
msgstr "설정"
@@ -1350,6 +1512,9 @@ msgstr "짧게"
msgid "Short pick {itemName}"
msgstr "{itemName} 부족 피킹"
+msgid "Show description"
+msgstr ""
+
msgid "Show this overlay"
msgstr "이 오버레이 표시"
@@ -1389,6 +1554,10 @@ msgstr "사용된 예비 부품"
msgid "Start"
msgstr "시작"
+#. placeholder {0}: workTypeLabels[ eventType.toLowerCase() as keyof typeof workTypeLabels ].toLowerCase()
+msgid "Start {0}"
+msgstr ""
+
msgid "Start or pause the operation"
msgstr "공정을 시작하거나 일시 중지"
@@ -1438,12 +1607,22 @@ msgstr "태그"
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "이 공정작업의 완료 수량이 필요 수량 {targetQuantity}보다 적습니다."
+msgid "The jobs and parts that make up this run."
+msgstr ""
+
+msgid "The jobs make different items — keep each job's parts apart."
+msgstr ""
+
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "로트는 통과로 표시되고 이 공정에서 남은 {remaining}개가 완료됩니다."
msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "로트는 여전히 처리되지만 최소한 하나의 Issue Type이 구성될 때까지 NCR을 생성할 수 없습니다."
+#. placeholder {0}: (batch.operations ?? []).length
+msgid "The timer and completion are shared by all {0} jobs. Steps, materials and files here are this job's own."
+msgstr ""
+
msgid "There are no available or consumed tracked parts for this material."
msgstr "이 자재에 대해 가용 또는 소모된 추적 부품이 없습니다."
@@ -1453,6 +1632,9 @@ msgstr "부품표(BOM)에 완전히 발행되지 않은 시리얼 또는 배치
msgid "These items still have material to pick. Finishing now marks the list Partial."
msgstr "이 항목들은 아직 선택할 재료가 있습니다. 지금 완료하면 목록이 부분으로 표시됩니다."
+msgid "This batch has no work instructions."
+msgstr ""
+
msgid "This lot is expired and can't be picked."
msgstr "로트가 만료되었으며 피킹할 수 없습니다."
@@ -1468,6 +1650,9 @@ msgstr "이 개가 영구적으로 스크랩되고 대체 시리얼 번호가
msgid "Thumbnail"
msgstr "썸네일"
+msgid "Tick the jobs this was done for."
+msgstr ""
+
msgid "Time and cost split across jobs proportionally to quantity."
msgstr "시간과 원가는 수량에 비례하여 작업 지시 간에 배분됩니다."
@@ -1478,6 +1663,12 @@ msgstr "시간 기록"
msgid "Time Worked: {0}"
msgstr "작업 시간: {0}"
+msgid "To pick"
+msgstr ""
+
+msgid "To run"
+msgstr ""
+
msgid "Today"
msgstr "오늘"
@@ -1487,6 +1678,9 @@ msgstr "사이드바 전환"
msgid "Tools"
msgstr "공구"
+msgid "Total"
+msgstr ""
+
msgid "Total Quantity"
msgstr "총 수량"
@@ -1501,6 +1695,9 @@ msgstr "합계: {0}"
msgid "Tracked Entity"
msgstr "추적 대상"
+msgid "tracked lines"
+msgstr "추적된 라인"
+
msgid "Tracking"
msgstr "추적"
@@ -1572,6 +1769,12 @@ msgstr "{0} 업로드 중"
msgid "Use a different account"
msgstr "다른 계정 사용"
+msgid "Used automatically at completion"
+msgstr ""
+
+msgid "Value"
+msgstr ""
+
msgid "Verify"
msgstr "확인"
@@ -1584,6 +1787,9 @@ msgstr "계정에 로그인할 수 있는 매직 링크를 보내드렸습니다
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm}란 무엇인가요?"
+msgid "Whole batch"
+msgstr "전체 배치"
+
msgid "WIP"
msgstr "재공품"
@@ -1593,6 +1799,9 @@ msgstr "작업장"
msgid "Work Center Displays"
msgstr "작업장 화면"
+msgid "Work instructions"
+msgstr "작업 표준서"
+
msgid "Yes"
msgstr "예"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index b6dff12938..8a3da5b3b0 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -111,6 +111,10 @@ msgstr "{0} usunięty pomyślnie"
msgid "{0} draft journal entries"
msgstr "{0} wpisów z wersji roboczej dowodu księgowego"
+#. placeholder {0}: op.description
+msgid "{0} has no supplier"
+msgstr ""
+
#. placeholder {0}: formatter.format(onHand)
#. placeholder {1}: formatter.format(assembliesInStock)
#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
@@ -141,6 +145,10 @@ msgstr "{0} z {1} kont księgowych zmapowanych"
msgid "{0} of {maxSlots} provider slots used"
msgstr "{0} z {maxSlots} slotów dostawcy jest w użyciu"
+#. placeholder {0}: pendingJobs.length
+msgid "{0} of {memberCount} member jobs are not completed yet — their output stays out of stock until each job is completed."
+msgstr "{0} z {memberCount} zleceń produkcyjnych nie zostały jeszcze zakończone — ich wyjście pozostaje poza zapasem, dopóki każde zlecenie produkcyjne nie zostanie zakończone."
+
#. placeholder {0}: selected.length
msgid "{0} operations · {totalQuantity} parts"
msgstr "{0} operacji · {totalQuantity} części"
@@ -1652,6 +1660,10 @@ msgstr "Wszystkie elementy"
msgid "All Locations"
msgstr "Wszystkie lokalizacje"
+#. placeholder {0}: tracked[0]?.itemReadableId ?? ""
+msgid "all make {0}"
+msgstr "całość produkcji {0}"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "Wszyscy członkowie wybranych grup i wybrane osoby będą mogły zatwierdzać żądania"
@@ -3550,6 +3562,9 @@ msgstr "Sprawdź swoją pocztę"
msgid "Checking Stripe for this customer…"
msgstr "Sprawdzanie Stripe dla tego klienta…"
+msgid "Checking the batch's jobs..."
+msgstr "Sprawdzanie zleceń partii produkcyjnej..."
+
msgid "Checkpoint ·"
msgstr "Punkt kontrolny ·"
@@ -3574,6 +3589,10 @@ msgstr "Wybierz wiersz po lewej, aby zobaczyć, skąd może pochodzić jego zapa
msgid "Choose a serial number"
msgstr "Wybierz numer seryjny"
+#. placeholder {0}: op.description
+msgid "choose a supplier for {0} on the job"
+msgstr ""
+
msgid "Choose another file"
msgstr "Wybierz inny plik"
@@ -3736,6 +3755,9 @@ msgstr "Kolumny"
msgid "Combine filters"
msgstr "Połącz filtry"
+msgid "Combine output into one lot"
+msgstr "Połącz produkty w jedną partię"
+
msgid "Coming soon"
msgstr "Wkrótce"
@@ -4526,6 +4548,9 @@ msgstr "Utwórz {0} wartości"
msgid "Create & Release"
msgstr "Utwórz i zwolnij"
+msgid "Create & release batch"
+msgstr "Utwórz i zwolnij partię produkcyjną"
+
msgid "Create & Snapshot"
msgstr "Utwórz i Snapshot"
@@ -4598,6 +4623,9 @@ msgstr "Utwórz zlecenia produkcyjne"
msgid "Create Kanban"
msgstr "Utwórz Kanban"
+msgid "Create New"
+msgstr "Utwórz nowy"
+
msgid "Create new rule"
msgstr "Utwórz nową regułę"
@@ -6269,6 +6297,12 @@ msgstr "np. Zebra 2x1"
msgid "Each cell is the people assigned against the people the day's work needs."
msgstr "W każdej komórce znajdują się przydzieleni pracownicy w stosunku do pracowników potrzebnych do pracy tego dnia."
+msgid "Each job keeps its own lot. The shop floor can't change these."
+msgstr "Każde zlecenie produkcyjne ma własną partię. Hala produkcyjna nie może tego zmienić."
+
+msgid "Each job needs its own lot number — or combine them into one lot."
+msgstr "Każde zlecenie produkcyjne potrzebuje własnego numeru partii — lub połącz je w jedną partię."
+
msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."
msgstr "Każdy wiersz to łącze z danych tej firmy do wiersza, którego nie jest właścicielem. Kopia bezpieczeństwa z tymi wierszami nigdy nie mogłaby być przywrócona."
@@ -6281,6 +6315,9 @@ msgstr "Niewykorzystany materiał z każdej operacji powraca natychmiast po zako
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Każda jednostka fizyczna otrzymuje swoją własną jednostkę śledzenia i unikalny numer — jedna jednostka, jedna jednostka."
+msgid "Each supplier's outside operations from every job go on one new purchase order, or on an existing draft you choose."
+msgstr "Operacje zewnętrzne każdego dostawcy z każdego zlecenia produkcyjnego trafiają na nowe zamówienie zakupu lub na istniejącą wersję roboczą, którą wybierzesz."
+
msgid "Each, lb, ft…"
msgstr "Każdy, lb, ft…"
@@ -7027,6 +7064,9 @@ msgstr "Wszystko inne"
msgid "Everything else covers people, imports, integrations and the API — anything that is not one of your workflows."
msgstr "Wszystko inne obejmuje pracowników, importy, integracje i API — wszystko, co nie jest jednym z twoich przepływów pracy."
+msgid "Everything this run makes lands in one lot. The shop floor can't change it."
+msgstr "Całość produkcji z tego cyklu trafia do jednej partii. Hala produkcyjna nie może tego zmienić."
+
msgid "Exceeds {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB total — remove some attachments to send."
msgstr "Przekracza {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB łącznie — usuń kilka załączników, aby wysłać."
@@ -7804,6 +7844,9 @@ msgstr "Dopasuj widok"
msgid "Fix the problems with this workflow before testing it"
msgstr "Napraw problemy tego przepływu pracy przed jego testowaniem"
+msgid "Fix these jobs before releasing"
+msgstr "Napraw te zlecenia produkcyjne przed zwolnieniem"
+
msgid "Fixed"
msgstr "Stałe"
@@ -9610,7 +9653,7 @@ msgid "Lines"
msgstr "Linie"
msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."
-msgstr "Pozycje pojawiają się tutaj po zaksięgowaniu przyjęcia z zamówienia zakupu i tylko dla ilości nieautoryzowanych już w innym zwrocie dostawcy. Użyj Dodaj pozycję dla zwrotu ślepego."
+msgstr "Pozycje pojawiają się tutaj po zaksięgowaniu przyjęcia zamówienia zakupu, tylko dla ilości nie już uwzględnionych w innym zwrocie dostawcy. Użyj opcji Dodaj pozycję dla ślepego zwrotu."
msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."
msgstr "Pozycje pojawiają się tutaj po zaksięgowaniu wysyłki zamówienia sprzedaży i tylko dla ilości, które nie zostały już autoryzowane w innym RMA. Użyj opcji Dodaj pozycję dla zwrotu ślepego."
@@ -9806,6 +9849,9 @@ msgstr "Przegrana"
msgid "Lot"
msgstr "Partia"
+msgid "Lot number"
+msgstr "Numer partii"
+
msgid "Lot size"
msgstr "Wielkość partii"
@@ -9986,6 +10032,9 @@ msgstr "Numer części producenta"
msgid "Manufacturing"
msgstr "Produkcja"
+msgid "manufacturing is blocked"
+msgstr "produkcja jest zablokowana"
+
msgid "Map accounts"
msgstr "Zmapuj konta"
@@ -10275,6 +10324,13 @@ msgstr "ID Notatki"
msgid "Merchant"
msgstr "Handlowiec"
+#. placeholder {0}: getItemReadableId(items, itemId) ?? itemId
+msgid "Merge {0} lots"
+msgstr ""
+
+msgid "Merge output lots"
+msgstr "Połącz partie wyjściowe"
+
msgid "MES"
msgstr "MES"
@@ -11264,6 +11320,10 @@ msgstr "Brak otwartych pozycji zamówienia sprzedaży"
msgid "No operations found."
msgstr "Nie znaleziono operacji."
+#. placeholder {0}: job.missingAssemblies .map((m) => m.description) .join(", ")
+msgid "no operations on {0}"
+msgstr "brak operacji na {0}"
+
msgid "No operations require picking at this location"
msgstr "Żadne operacje nie wymagają kompletacji w tej lokalizacji"
@@ -11385,7 +11445,7 @@ msgid "No results found"
msgstr "Nie znaleziono wyników"
msgid "No returnable lines for this customer"
-msgstr "Brak pozycji możliwych do zwrotu dla tego klienta"
+msgstr "Brak zwracalnych pozycji dla tego klienta"
msgid "No returnable lines for this supplier"
msgstr "Brak pozycji do zwrotu dla tego dostawcy"
@@ -13014,6 +13074,12 @@ msgstr "Procesy"
msgid "Procurement status — needs ordering, planned, on order, or received. The same indicator shown in the BoM tree."
msgstr "Status zaopatrzenia — wymaga zamówienia, zaplanowane, zamówione lub odebrane. Ten sam wskaźnik wyświetlany w drzewie BoM."
+msgid "produced item"
+msgstr "artykuł wyprodukowany"
+
+msgid "Produced item"
+msgstr "Artykuł wyprodukowany"
+
msgid "Product issues during hypercare"
msgstr "Problemy z produktem podczas hypercare"
@@ -13923,6 +13989,11 @@ msgstr "Zwolnij {0} partie produkcyjne"
msgid "Release Batch"
msgstr "Zwolnij partię produkcyjną"
+#. placeholder {0}: batch.readableId
+#. placeholder {0}: releaseTarget.readableId
+msgid "Release batch {0}"
+msgstr "Zwolnij partię produkcyjną {0}"
+
msgid "Release change notice"
msgstr "Zwolnij zawiadomienie o zmianie"
@@ -13951,6 +14022,9 @@ msgstr "Zwolniona rewizja"
msgid "Released revision is locked"
msgstr "Zwolniona rewizja jest zablokowana"
+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
+msgstr "Zwolnienie partii produkcyjnej zwalnia jej zlecenia produkcyjne, a każde musi być gotowe na halę produkcyjną."
+
msgid "Remaining"
msgstr "Pozostało"
@@ -15822,6 +15896,10 @@ msgstr "Skróty"
msgid "Show"
msgstr "Pokaż"
+#. placeholder {0}: overflow.length
+msgid "Show {0} more"
+msgstr ""
+
msgid "Show a readable Customer ID column on the customer list, customer forms, and dropdowns. Customers are still identified internally either way."
msgstr "Pokaż kolumnę czytelnego identyfikatora klienta na liście klientów, formularzach klientów i listach rozwijanych. Klienci są nadal identyfikowani wewnętrznie w każdym przypadku."
@@ -16981,6 +17059,9 @@ msgstr "Zadanie kopii zapasowej zgłosiło ten błąd."
msgid "The backward-computed date an operation must finish by to keep its job on time, written to the operation's due date. A stable target for measuring progress — never a constraint on placement."
msgstr "Data obliczona wstecz, do której operacja musi być ukończona, aby zlecenie produkcyjne dotrzymało terminu, zapisana jako termin operacji. Stabilny punkt odniesienia do pomiaru postępu — nigdy nie jest ograniczeniem na rozmieszczenie pracy."
+msgid "The batch goes to the shop floor. Its jobs are already released."
+msgstr "Partia produkcyjna przechodzi na halę produkcyjną. Jej zlecenia produkcyjne są już zwolnione."
+
msgid "The batch runs at its most urgent member's time — the others are pulled early"
msgstr "Partia biegnie według najpilniejszego elementu — pozostałe są przyspieszane"
@@ -17266,6 +17347,9 @@ msgstr "Koszt zapasów uznany, gdy wysyłka się zaksięgowuje, wyceniony metod
msgid "The IRS recovery-period class for this asset under MACRS (3, 5, 7, 10, 15, 20, 27.5, 39-year)."
msgstr "Klasa okresu odzyskania IRS dla tego zasobu w ramach MACRS (3, 5, 7, 10, 15, 20, 27,5, 39 lat)."
+msgid "The item each job produces — require it to match to merge output lots"
+msgstr "Artykuł, który każde zlecenie produkcyjne wytwarza — wymagaj jego dopasowania, aby połączyć partie wyjściowe"
+
msgid "the job hours due that day (a due-date basis, not the day the work runs), with overdue work in Past due."
msgstr "godziny zadania należne tego dnia (na podstawie terminu, nie dnia wykonania), z zalegającymi pracami w Zalegające."
@@ -17800,6 +17884,11 @@ msgstr "Te wiersze są połączone z danymi spoza tej firmy, dlatego nigdy nie m
msgid "this ability"
msgstr "ta umiejętność"
+#. placeholder {0}: jobIds.length
+#. placeholder {1}: jobIds.join(", ")
+msgid "This also releases {0} jobs ({1}). They become available to the shop floor and drive purchasing and production."
+msgstr "To również zwalnia {0} zleceń produkcyjnych ({1}). Stają się dostępne dla hali produkcyjnej i napędzają zakupy i produkcję."
+
msgid "This backup could not be completed."
msgstr "Nie można było ukończyć tej kopii zapasowej."
diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.po
index 1a726a34ef..a4cd6c01e7 100644
--- a/packages/locale/locales/pl/mes.po
+++ b/packages/locale/locales/pl/mes.po
@@ -25,14 +25,28 @@ msgstr "{0} Aktywnych"
msgid "{0} ago"
msgstr "{0} temu"
+#. placeholder {0}: batchFacts.customers.length
+msgid "{0} customers"
+msgstr ""
+
+#. placeholder {0}: unplanned .map( (m) => (m.job as { jobId?: string | null } | null)?.jobId ) .filter(Boolean) .join(", ")
+msgid "{0} has no lot number. Set it on the batch or job in Carbon, then complete."
+msgstr "{0} nie ma numeru partii. Ustaw go w partii produkcyjnej lub zleceniu w Carbon, a następnie zakończ."
+
+#. placeholder {0}: batchFacts.items.length
+msgid "{0} items"
+msgstr ""
+
#. placeholder {0}: (batch.operations ?? []).length
msgid "{0} jobs"
msgstr "{0} Zlecenia produkcyjne"
+#. placeholder {0}: issuedLines.length
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
#. placeholder {1}: operation.targetQuantity
+#. placeholder {1}: trackedLines.length
msgid "{0} of {1}"
msgstr "{0} z {1}"
@@ -54,16 +68,28 @@ msgstr "{0} w kolejce"
msgid "{0} running"
msgstr "{0} w trakcie"
+#. placeholder {0}: operation.jobReadableId
+#. placeholder {1}: batch.readableId
+msgid "{0} runs in batch {1}"
+msgstr ""
+
#. placeholder {0}: item.quantityScrapped
msgid "{0} Scrapped"
msgstr "{0} Odrzuconych"
+msgid "{completed} of {quantity}"
+msgstr "{completed} z {quantity}"
+
msgid "{completions} passed unit(s) will be completed."
msgstr "{completions} zaliczonych sztuk będzie zakończone."
msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
msgstr "{fails} zarejestrowanych niepowodzeń będzie NIEUKOŃCZONYCH — rozwiąż je z menu akcji."
+#. placeholder {0}: step.perMember.length
+msgid "{recorded}/{0} jobs"
+msgstr ""
+
msgid "+{overflow} more"
msgstr "+{overflow} więcej"
@@ -88,6 +114,10 @@ msgstr "Ustawienia konta"
msgid "Acknowledge & finish"
msgstr "Potwierdź i zakończ"
+#. placeholder {0}: members.length
+msgid "across {0} jobs"
+msgstr "na {0} zleceniach produkcyjnych"
+
msgid "Active"
msgstr "Aktywne"
@@ -118,6 +148,13 @@ msgstr "Wszystkie"
msgid "All clear"
msgstr "Wszystko jasne"
+msgid "All jobs"
+msgstr "Wszystkie zlecenia produkcyjne"
+
+#. placeholder {0}: batch.outputLotNumber
+msgid "All output goes to lot <0>{0}</0>"
+msgstr "Całość produktu trafia do partii <0>{0}</0>"
+
msgid "All rework"
msgstr "Wszystkie poprawki"
@@ -166,6 +203,9 @@ msgstr "dostępne"
msgid "Available"
msgstr "Dostępne"
+msgid "Back to batch"
+msgstr ""
+
msgid "Batch"
msgstr "Partia"
@@ -179,12 +219,21 @@ msgstr "Numer partii {0}"
msgid "Batch number is required"
msgstr "Numer partii jest wymagany"
-msgid "Batched jobs"
-msgstr "Zbiorcze zlecenia produkcyjne"
+msgid "Batch quantity"
+msgstr "Ilość partii produkcyjnej"
+
+msgid "batch total"
+msgstr "razem partia produkcyjna"
msgid "Behind target by {daysBehindTarget} day(s)"
msgstr "Opóźnione o {daysBehindTarget} dni"
+#. placeholder {0}: step.minValue
+#. placeholder {1}: step.maxValue
+#. placeholder {2}: step.unitOfMeasureCode ?? ""
+msgid "Between {0} and {1} {2}"
+msgstr ""
+
#. placeholder {0}: column.blockingDispatchReadableId
msgid "Blocked by {0}"
msgstr "Zablokowane przez {0}"
@@ -222,6 +271,9 @@ msgstr "Czat"
msgid "Check your email"
msgstr "Sprawdź swoją skrzynkę e-mail"
+msgid "Choose a job"
+msgstr ""
+
msgid "Clear"
msgstr "Wyczyść"
@@ -249,6 +301,9 @@ msgstr "Zamknij"
msgid "Collapse features table"
msgstr "Zwiń tabelę funkcji"
+msgid "Collapse panel"
+msgstr "Zwiń panel"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -278,6 +333,9 @@ msgstr "Ukończ"
msgid "Complete All"
msgstr "Uzupełnij wszystko"
+msgid "Complete batch"
+msgstr ""
+
msgid "Complete Batch"
msgstr "Zakończ partię"
@@ -377,6 +435,9 @@ msgstr "Wyświetlanie"
msgid "Displays"
msgstr "Wyświetlacze"
+msgid "Done"
+msgstr ""
+
msgid "Down"
msgstr "Awaria"
@@ -409,9 +470,12 @@ msgstr "Przeciągnij, aby zmienić rozmiar rysunku i funkcji"
msgid "Dragging {0} cancelled."
msgstr "Przeciąganie {0} anulowane."
+msgid "Due"
+msgstr ""
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
msgid "Due {0}"
msgstr "Termin {0}"
@@ -434,6 +498,9 @@ msgstr "Zduplikowany numer seryjny"
msgid "Duration"
msgstr "Czas trwania"
+msgid "Each job's output is its own lot — keep each job's parts apart."
+msgstr ""
+
msgid "Edit"
msgstr "Edytuj"
@@ -449,6 +516,9 @@ msgstr "Puste stanowiska robocze"
msgid "End Operations"
msgstr "Zakończ operacje"
+msgid "Enter each job's value, or fill every job at once from the first row. Empty rows are skipped."
+msgstr ""
+
#. placeholder {0}: selectedPerson.name
msgid "Enter PIN for {0}"
msgstr "Wprowadź PIN dla {0}"
@@ -465,12 +535,18 @@ msgstr "Błąd"
msgid "Estimated"
msgstr "Szacowane"
+msgid "Every job in the batch follows these steps. Record a step for all of them at once."
+msgstr ""
+
msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
msgstr "Każda sztuka ma wyrok: {passes} zaliczonych i {fails} niezaliczonych. Partia zamyka się, każda sztuka kierowana jest do jej wyniku."
msgid "Expand features table"
msgstr "Rozwiń tabelę funkcji"
+msgid "Expand panel"
+msgstr "Rozwiń panel"
+
msgid "Expired"
msgstr "Wygasło"
@@ -511,6 +587,10 @@ msgstr "Nie udało się zapisać pomiaru"
msgid "Failed to save result"
msgstr "Nie udało się zapisać wyniku"
+#. placeholder {0}: file.name
+msgid "Failed to upload {0}"
+msgstr ""
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Nie udało się przesłać pliku: {0}"
@@ -555,6 +635,10 @@ msgstr "Dokończ konfigurowanie swojego konta"
msgid "Finish with material unpicked?"
msgstr "Zakończyć bez wybranego materiału?"
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(batchFacts.dueDate) )
+msgid "First due {0}"
+msgstr ""
+
msgid "Forgot to Clock Out?"
msgstr "Zapomniano o zakończeniu pracy?"
@@ -567,6 +651,9 @@ msgstr "Wróć do operacji"
msgid "Go to onboarding"
msgstr "Przejdź do wdrożenia"
+msgid "Hide description"
+msgstr ""
+
msgid "How many were actually picked?"
msgstr "Ile faktycznie zostało zebrane?"
@@ -631,6 +718,9 @@ msgstr "Wydaj materiał"
msgid "Issue Type"
msgstr "Typ problemu"
+msgid "Issued"
+msgstr "Wydane"
+
msgid "Issued {issuedQuantity} of {lotLabel}"
msgstr "Wydane {issuedQuantity} z {lotLabel}"
@@ -688,6 +778,9 @@ msgstr "linie"
msgid "List view"
msgstr "Widok listy"
+msgid "Load list"
+msgstr ""
+
msgid "Loading item details..."
msgstr "Ładowanie szczegółów pozycji..."
@@ -700,6 +793,9 @@ msgstr "Lokalne"
msgid "Location"
msgstr "Lokalizacja"
+msgid "Log completed"
+msgstr ""
+
msgid "Log Completed"
msgstr "Rejestruj ukończone"
@@ -727,6 +823,12 @@ msgstr "Zaloguj się"
msgid "Lot"
msgstr "Partia"
+msgid "Lot numbers missing"
+msgstr "Brakuje numerów partii"
+
+msgid "Lot tracked"
+msgstr ""
+
msgid "Machine"
msgstr "Maszyna"
@@ -763,6 +865,9 @@ msgstr "pasuje do"
msgid "Materials"
msgstr "Materiały"
+msgid "Materials issued"
+msgstr "Wydane materiały"
+
msgid "Maximum number of records reached"
msgstr "Osiągnięto maksymalną liczbę rekordów"
@@ -866,6 +971,9 @@ msgstr "Brak wyników. Wpisz, aby utworzyć nowy."
msgid "No materials"
msgstr "Brak materiałów"
+msgid "No materials on this batch."
+msgstr "Brak materiałów w tej partii produkcyjnej."
+
msgid "No open jobs"
msgstr "Brak otwartych zleceń produkcyjnych"
@@ -959,9 +1067,22 @@ msgstr "Wpływ na OEE"
msgid "OEM Required"
msgstr "Wymagany OEM"
+#. placeholder {0}: m.operationQuantity ?? 0
+msgid "of {0}"
+msgstr ""
+
msgid "Oldest first"
msgstr "Najstarsze pierwsze"
+msgid "one combined lot · planned"
+msgstr "jedna połączona partia · zaplanowana"
+
+msgid "one per job · planned"
+msgstr "jedna na zlecenie · zaplanowana"
+
+msgid "One pick covers the whole batch — it is shared out to the jobs automatically."
+msgstr ""
+
#. placeholder {0}: batch.quantity
msgid "Only {0} available"
msgstr "Tylko {0} dostępnych"
@@ -975,6 +1096,9 @@ msgstr "Otwarte"
msgid "Open a display on the screen mounted at the work center and leave it running. Each board refreshes on its own."
msgstr "Otwórz wyświetlacz na ekranie zainstalowanym na stanowisku roboczym i pozostaw go w działaniu. Każda tablica odświeża się automatycznie."
+msgid "Open a job in this batch"
+msgstr ""
+
msgid "Open an NCR for MRB disposition"
msgstr "Otwórz NCR dla dyspozycji MRB"
@@ -999,6 +1123,9 @@ msgstr "Opcjonalnie"
msgid "or"
msgstr "lub"
+msgid "Output lot"
+msgstr "Partia wyrobu"
+
msgid "Overall result"
msgstr "Wynik ogólny"
@@ -1017,6 +1144,9 @@ msgstr "Częściowo"
msgid "Partial Disposition"
msgstr "Częściowa dyspozycja"
+msgid "Passed inspection"
+msgstr ""
+
msgid "Passed Inspection"
msgstr "Zaliczona kontrola"
@@ -1029,6 +1159,10 @@ msgstr "Wstrzymaj"
msgid "Pick"
msgstr "Pobierz"
+#. placeholder {0}: m.required - m.issued
+msgid "Pick {0}"
+msgstr "Pobierz {0}"
+
msgid "Pick tracked item"
msgstr "Wybierz śledzony element"
@@ -1098,6 +1232,9 @@ msgstr "Procedura"
msgid "Process"
msgstr "Proces"
+msgid "Process parameters"
+msgstr "Parametry procesu"
+
msgid "Process Parameters"
msgstr "Parametry procesu"
@@ -1140,18 +1277,28 @@ msgstr "Rejestruj"
msgid "Record {0}"
msgstr "Rekord {0}"
+#. placeholder {0}: changed.length
+msgid "Record {0} jobs"
+msgstr ""
+
msgid "Record only"
msgstr "Tylko zarejestruj"
msgid "Record Partial"
msgstr "Zapisz częściowo"
+msgid "Recorded"
+msgstr ""
+
msgid "Reject"
msgstr "Odrzuć"
msgid "Reject Lot"
msgstr "Odrzuć partię"
+msgid "Released"
+msgstr ""
+
msgid "Remove"
msgstr "Usuń"
@@ -1167,6 +1314,9 @@ msgstr "Usuń część"
msgid "Reopen the subassembly and create a replacement unit"
msgstr "Ponownie otwórz podzespół i utwórz zastępczą jednostkę"
+msgid "Required"
+msgstr "Wymagane"
+
msgid "Result"
msgstr "Wynik"
@@ -1188,6 +1338,9 @@ msgstr "W trakcie"
msgid "Sales Order"
msgstr "Zamówienie sprzedaży"
+msgid "Same for every job"
+msgstr ""
+
msgid "Save"
msgstr "Zapisz"
@@ -1307,6 +1460,9 @@ msgstr "Wyślij"
msgid "Send to Carbon"
msgstr "Wyślij do Carbon"
+msgid "Separate lots"
+msgstr "Odrębne partie"
+
msgid "Serial"
msgstr "Seryjny"
@@ -1326,6 +1482,9 @@ msgstr "Numery seryjne"
msgid "Serial Numbers"
msgstr "Numery seryjne"
+msgid "Serialized"
+msgstr ""
+
msgid "Session locked"
msgstr "Sesja zablokowana"
@@ -1338,6 +1497,9 @@ msgstr "Ustaw czas zakończenia zmiany"
msgid "Set up in Carbon"
msgstr "Skonfiguruj w aplikacji Carbon"
+msgid "Set when the batch was planned."
+msgstr "Ustawiono, gdy partia produkcyjna została zaplanowana."
+
msgid "Setup"
msgstr "Ustawienie"
@@ -1350,6 +1512,9 @@ msgstr "Brakuje"
msgid "Short pick {itemName}"
msgstr "Krótki pick {itemName}"
+msgid "Show description"
+msgstr ""
+
msgid "Show this overlay"
msgstr "Wyświetl to okno nakładki"
@@ -1389,6 +1554,10 @@ msgstr "Użyte części zamienne"
msgid "Start"
msgstr "Start"
+#. placeholder {0}: workTypeLabels[ eventType.toLowerCase() as keyof typeof workTypeLabels ].toLowerCase()
+msgid "Start {0}"
+msgstr ""
+
msgid "Start or pause the operation"
msgstr "Uruchom lub wstrzymaj operację"
@@ -1438,12 +1607,22 @@ msgstr "Tag"
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "Ukończona ilość dla tej operacji jest mniejsza niż wymagana ilość {targetQuantity}."
+msgid "The jobs and parts that make up this run."
+msgstr ""
+
+msgid "The jobs make different items — keep each job's parts apart."
+msgstr ""
+
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "Partia będzie oznaczona jako zaliczona i {remaining} pozostałych sztuk będzie ukończonych w tej operacji."
msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "Partia będzie nadal dyspozycjonowana, ale nie można utworzyć NCR, dopóki nie zostanie skonfigurowany co najmniej jeden typ problemu."
+#. placeholder {0}: (batch.operations ?? []).length
+msgid "The timer and completion are shared by all {0} jobs. Steps, materials and files here are this job's own."
+msgstr ""
+
msgid "There are no available or consumed tracked parts for this material."
msgstr "Brak dostępnych lub zużytych śledzonych części dla tego materiału."
@@ -1453,6 +1632,9 @@ msgstr "Na specyfikacji materiałowej znajdują się materiały śledzone po num
msgid "These items still have material to pick. Finishing now marks the list Partial."
msgstr "Te pozycje mają jeszcze materiał do wybrania. Zakończenie teraz oznaczy listę jako Częściowa."
+msgid "This batch has no work instructions."
+msgstr ""
+
msgid "This lot is expired and can't be picked."
msgstr "Ta partia wygasła i nie można jej pobrać."
@@ -1468,6 +1650,9 @@ msgstr "Ta jednostka zostanie bezpowrotnie złomowana i zostanie utworzony nowy
msgid "Thumbnail"
msgstr "Miniatura"
+msgid "Tick the jobs this was done for."
+msgstr ""
+
msgid "Time and cost split across jobs proportionally to quantity."
msgstr "Czas i koszt rozdzielone na zlecenia produkcyjne proporcjonalnie do ilości."
@@ -1478,6 +1663,12 @@ msgstr "Wpisy czasu pracy"
msgid "Time Worked: {0}"
msgstr "Przepracowany czas: {0}"
+msgid "To pick"
+msgstr ""
+
+msgid "To run"
+msgstr ""
+
msgid "Today"
msgstr "Dzisiaj"
@@ -1487,6 +1678,9 @@ msgstr "Przełącz pasek boczny"
msgid "Tools"
msgstr "Narzędzia"
+msgid "Total"
+msgstr ""
+
msgid "Total Quantity"
msgstr "Ilość całkowita"
@@ -1501,6 +1695,9 @@ msgstr "Razem: {0}"
msgid "Tracked Entity"
msgstr "Jednostka śledzona"
+msgid "tracked lines"
+msgstr "śledzone pozycje"
+
msgid "Tracking"
msgstr "Śledzenie"
@@ -1572,6 +1769,12 @@ msgstr "Przesyłanie {0}"
msgid "Use a different account"
msgstr "Użyj innego konta"
+msgid "Used automatically at completion"
+msgstr ""
+
+msgid "Value"
+msgstr ""
+
msgid "Verify"
msgstr "Zweryfikuj"
@@ -1584,6 +1787,9 @@ msgstr "Wysłaliśmy Ci link do logowania na Twoje konto."
msgid "What is {translatedTerm}?"
msgstr "Co to jest {translatedTerm}?"
+msgid "Whole batch"
+msgstr "Całą partię produkcyjną"
+
msgid "WIP"
msgstr "Produkcja w toku"
@@ -1593,6 +1799,9 @@ msgstr "Stanowisko robocze"
msgid "Work Center Displays"
msgstr "Wyświetlacze stanowiska roboczego"
+msgid "Work instructions"
+msgstr "Instrukcje robocze"
+
msgid "Yes"
msgstr "Tak"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index a4342f5729..b728f8d77b 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -111,6 +111,10 @@ msgstr "{0} eliminado com sucesso"
msgid "{0} draft journal entries"
msgstr "{0} lançamentos de diário em rascunho"
+#. placeholder {0}: op.description
+msgid "{0} has no supplier"
+msgstr ""
+
#. placeholder {0}: formatter.format(onHand)
#. placeholder {1}: formatter.format(assembliesInStock)
#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
@@ -141,6 +145,10 @@ msgstr "{0} de {1} contas de contabilização mapeadas"
msgid "{0} of {maxSlots} provider slots used"
msgstr "{0} de {maxSlots} slots de provedor utilizados"
+#. placeholder {0}: pendingJobs.length
+msgid "{0} of {memberCount} member jobs are not completed yet — their output stays out of stock until each job is completed."
+msgstr "{0} de {memberCount} ordens de produção ainda não foram concluídas — sua saída permanece fora do estoque até que cada ordem de produção seja concluída."
+
#. placeholder {0}: selected.length
msgid "{0} operations · {totalQuantity} parts"
msgstr "{0} operações · {totalQuantity} peças"
@@ -1652,6 +1660,10 @@ msgstr "Todos os Itens"
msgid "All Locations"
msgstr "Todos os Locais"
+#. placeholder {0}: tracked[0]?.itemReadableId ?? ""
+msgid "all make {0}"
+msgstr "toda Fabricação {0}"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "Todos os membros dos grupos selecionados e indivíduos selecionados poderão aprovar solicitações"
@@ -3550,6 +3562,9 @@ msgstr "Verifique seu email"
msgid "Checking Stripe for this customer…"
msgstr "Verificando Stripe para este cliente…"
+msgid "Checking the batch's jobs..."
+msgstr "Verificando as ordens de produção do lote de produção..."
+
msgid "Checkpoint ·"
msgstr "Checkpoint ·"
@@ -3574,6 +3589,10 @@ msgstr "Escolha uma linha à esquerda para ver de onde seu estoque pode vir."
msgid "Choose a serial number"
msgstr "Escolha um número de série"
+#. placeholder {0}: op.description
+msgid "choose a supplier for {0} on the job"
+msgstr ""
+
msgid "Choose another file"
msgstr "Escolher outro arquivo"
@@ -3736,6 +3755,9 @@ msgstr "Colunas"
msgid "Combine filters"
msgstr "Combinar filtros"
+msgid "Combine output into one lot"
+msgstr "Combinar produção em um único lote"
+
msgid "Coming soon"
msgstr "Em breve"
@@ -4526,6 +4548,9 @@ msgstr "Criar {0} valores"
msgid "Create & Release"
msgstr "Criar & liberar"
+msgid "Create & release batch"
+msgstr "Criar e liberar lote de produção"
+
msgid "Create & Snapshot"
msgstr "Criar e Capturar"
@@ -4598,6 +4623,9 @@ msgstr "Criar Ordens de produção"
msgid "Create Kanban"
msgstr "Criar Kanban"
+msgid "Create New"
+msgstr "Criar novo"
+
msgid "Create new rule"
msgstr "Criar nova regra"
@@ -6269,6 +6297,12 @@ msgstr "p.ex. Zebra 2x1"
msgid "Each cell is the people assigned against the people the day's work needs."
msgstr "Cada célula mostra as pessoas atribuídas em comparação com as pessoas que o trabalho do dia precisa."
+msgid "Each job keeps its own lot. The shop floor can't change these."
+msgstr "Cada ordem de produção mantém seu próprio lote. O chão de fábrica não pode alterar estes."
+
+msgid "Each job needs its own lot number — or combine them into one lot."
+msgstr "Cada ordem de produção precisa de seu próprio número de lote — ou combine-os em um único lote."
+
msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."
msgstr "Cada linha é um vínculo dos dados desta empresa para uma linha que não é de sua propriedade. Um backup com essas linhas nunca poderia ser restaurado."
@@ -6281,6 +6315,9 @@ msgstr "O material não utilizado de cada operação retorna assim que a operaç
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Cada unidade física obtém sua própria entidade rastreada e número único — uma entidade, uma unidade."
+msgid "Each supplier's outside operations from every job go on one new purchase order, or on an existing draft you choose."
+msgstr "As operações terceirizadas de cada fornecedor de todas as ordens de produção vão em um novo pedido de compra ou em um rascunho existente que você escolhe."
+
msgid "Each, lb, ft…"
msgstr "Cada, lb, ft…"
@@ -7027,6 +7064,9 @@ msgstr "Tudo mais"
msgid "Everything else covers people, imports, integrations and the API — anything that is not one of your workflows."
msgstr "Tudo mais cobre pessoas, importações, integrações e a API — qualquer coisa que não seja um de seus fluxos de trabalho."
+msgid "Everything this run makes lands in one lot. The shop floor can't change it."
+msgstr "Tudo o que esta execução produz vai para um lote. O chão de fábrica não pode alterá-lo."
+
msgid "Exceeds {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB total — remove some attachments to send."
msgstr "Excede {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB no total — remova alguns anexos para enviar."
@@ -7804,6 +7844,9 @@ msgstr "Ajustar visualização"
msgid "Fix the problems with this workflow before testing it"
msgstr "Corrija os problemas com este fluxo de trabalho antes de testá-lo"
+msgid "Fix these jobs before releasing"
+msgstr "Corrija essas ordens de produção antes de liberar"
+
msgid "Fixed"
msgstr "Fixo"
@@ -9610,7 +9653,7 @@ msgid "Lines"
msgstr "Linhas"
msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."
-msgstr "Linhas aparecem aqui após um recebimento de pedido de compra ser contabilizado, e apenas para quantidades não autorizadas em outra devolução de fornecedor. Use Adicionar item para uma devolução sem documento."
+msgstr "As linhas aparecem aqui após um recebimento de pedido de compra ter sido contabilizado, e apenas para quantidades não já autorizadas em outra devolução de fornecedor. Use Adicionar Item de Linha para uma devolução às cegas."
msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."
msgstr "As linhas aparecem aqui uma vez que uma remessa de pedido de venda tenha sido contabilizada, e apenas para quantidades não já autorizadas em outro RMA. Use Adicionar Item de Linha para uma devolução cega."
@@ -9806,6 +9849,9 @@ msgstr "Perdido"
msgid "Lot"
msgstr "Lote"
+msgid "Lot number"
+msgstr "Número de lote"
+
msgid "Lot size"
msgstr "Tamanho do lote"
@@ -9986,6 +10032,9 @@ msgstr "Número de Peça do Fabricante"
msgid "Manufacturing"
msgstr "Manufatura"
+msgid "manufacturing is blocked"
+msgstr "a produção está bloqueada"
+
msgid "Map accounts"
msgstr "Mapear contas"
@@ -10275,6 +10324,13 @@ msgstr "ID do Memorando"
msgid "Merchant"
msgstr "Comerciante"
+#. placeholder {0}: getItemReadableId(items, itemId) ?? itemId
+msgid "Merge {0} lots"
+msgstr ""
+
+msgid "Merge output lots"
+msgstr "Mesclar lotes de saída"
+
msgid "MES"
msgstr "MES"
@@ -11264,6 +11320,10 @@ msgstr "Nenhuma linha de pedido de venda aberta"
msgid "No operations found."
msgstr "Nenhuma operação encontrada."
+#. placeholder {0}: job.missingAssemblies .map((m) => m.description) .join(", ")
+msgid "no operations on {0}"
+msgstr "nenhuma operação em {0}"
+
msgid "No operations require picking at this location"
msgstr "Nenhuma operação requer separação neste local"
@@ -13014,6 +13074,12 @@ msgstr "Processos"
msgid "Procurement status — needs ordering, planned, on order, or received. The same indicator shown in the BoM tree."
msgstr "Status de aquisição — requer pedido, planejado, em pedido ou recebido. O mesmo indicador exibido na árvore da BoM."
+msgid "produced item"
+msgstr "item produzido"
+
+msgid "Produced item"
+msgstr "Item produzido"
+
msgid "Product issues during hypercare"
msgstr "Problemas de produto durante hipercare"
@@ -13923,6 +13989,11 @@ msgstr "Liberar {0} lotes de produção"
msgid "Release Batch"
msgstr "Liberar lote de produção"
+#. placeholder {0}: batch.readableId
+#. placeholder {0}: releaseTarget.readableId
+msgid "Release batch {0}"
+msgstr "Liberar lote de produção {0}"
+
msgid "Release change notice"
msgstr "Liberar aviso de alteração"
@@ -13951,6 +14022,9 @@ msgstr "Revisão lançada"
msgid "Released revision is locked"
msgstr "A revisão lançada está bloqueada"
+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
+msgstr "Liberar o lote de produção libera suas ordens de produção, e cada uma deve estar pronta para o chão de fábrica."
+
msgid "Remaining"
msgstr "Restante"
@@ -15074,7 +15148,7 @@ msgid "Search by linear issue title..."
msgstr "Pesquisar por título do problema Linear..."
msgid "Search by receipt, PO, or item"
-msgstr "Pesquisar por recebimento, pedido de compra ou item"
+msgstr "Pesquise por recebimento, PO ou item"
msgid "Search by shipment, sales order, or item"
msgstr "Pesquisar por remessa, pedido de venda ou item"
@@ -15324,7 +15398,7 @@ msgid "Select operations"
msgstr "Selecionar operações"
msgid "Select posted receipt lines from this supplier to return."
-msgstr "Selecione linhas de recebimento contabilizadas deste fornecedor para devolução."
+msgstr "Selecione linhas de recebimento contabilizadas deste fornecedor para devolver."
msgid "Select posted shipment lines to this customer to return."
msgstr "Selecionar linhas de remessa contabilizada para este cliente para devolver."
@@ -15822,6 +15896,10 @@ msgstr "Atalhos"
msgid "Show"
msgstr "Mostrar"
+#. placeholder {0}: overflow.length
+msgid "Show {0} more"
+msgstr ""
+
msgid "Show a readable Customer ID column on the customer list, customer forms, and dropdowns. Customers are still identified internally either way."
msgstr "Mostrar uma coluna de ID de Cliente legível na lista de clientes, formulários de clientes e menus suspensos. Os clientes ainda são identificados internamente de qualquer forma."
@@ -16981,6 +17059,9 @@ msgstr "O trabalho de backup informou este erro."
msgid "The backward-computed date an operation must finish by to keep its job on time, written to the operation's due date. A stable target for measuring progress — never a constraint on placement."
msgstr "A data calculada retroativamente que uma operação deve terminar para manter sua ordem de produção no prazo, escrita na data de vencimento da operação. Um alvo estável para medir o progresso — nunca uma restrição de colocação."
+msgid "The batch goes to the shop floor. Its jobs are already released."
+msgstr "O lote de produção vai para o chão de fábrica. Suas ordens de produção já foram liberadas."
+
msgid "The batch runs at its most urgent member's time — the others are pulled early"
msgstr "O lote é executado no prazo do membro mais urgente — os demais são adiantados"
@@ -17266,6 +17347,9 @@ msgstr "O custo de inventário reconhecido quando uma remessa é registrada, ava
msgid "The IRS recovery-period class for this asset under MACRS (3, 5, 7, 10, 15, 20, 27.5, 39-year)."
msgstr "A classe de período de recuperação IRS para este ativo sob MACRS (3, 5, 7, 10, 15, 20, 27,5, 39 anos)."
+msgid "The item each job produces — require it to match to merge output lots"
+msgstr "O item que cada ordem de produção produz — exija que corresponda para mesclar lotes de saída"
+
msgid "the job hours due that day (a due-date basis, not the day the work runs), with overdue work in Past due."
msgstr "as horas de trabalho devidas naquele dia (com base na data de vencimento, não no dia em que o trabalho é executado), com trabalho atrasado em Vencido."
@@ -17800,6 +17884,11 @@ msgstr "Essas linhas estão vinculadas a dados fora desta empresa, portanto nunc
msgid "this ability"
msgstr "esta habilidade"
+#. placeholder {0}: jobIds.length
+#. placeholder {1}: jobIds.join(", ")
+msgid "This also releases {0} jobs ({1}). They become available to the shop floor and drive purchasing and production."
+msgstr "Isto também libera {0} ordens de produção ({1}). Elas ficam disponíveis para o chão de fábrica e impulsionam as compras e a produção."
+
msgid "This backup could not be completed."
msgstr "Este backup não pôde ser concluído."
diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.po
index ac54a394dd..cc5d4d4a60 100644
--- a/packages/locale/locales/pt/mes.po
+++ b/packages/locale/locales/pt/mes.po
@@ -25,14 +25,28 @@ msgstr "{0} Ativo(s)"
msgid "{0} ago"
msgstr "há {0}"
+#. placeholder {0}: batchFacts.customers.length
+msgid "{0} customers"
+msgstr ""
+
+#. placeholder {0}: unplanned .map( (m) => (m.job as { jobId?: string | null } | null)?.jobId ) .filter(Boolean) .join(", ")
+msgid "{0} has no lot number. Set it on the batch or job in Carbon, then complete."
+msgstr "{0} não tem número de lote. Defina-o no lote de produção ou ordem de produção no Carbon, depois concluir."
+
+#. placeholder {0}: batchFacts.items.length
+msgid "{0} items"
+msgstr ""
+
#. placeholder {0}: (batch.operations ?? []).length
msgid "{0} jobs"
msgstr "{0} ordens de produção"
+#. placeholder {0}: issuedLines.length
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
#. placeholder {1}: operation.targetQuantity
+#. placeholder {1}: trackedLines.length
msgid "{0} of {1}"
msgstr "{0} de {1}"
@@ -54,16 +68,28 @@ msgstr "{0} na fila"
msgid "{0} running"
msgstr "{0} em execução"
+#. placeholder {0}: operation.jobReadableId
+#. placeholder {1}: batch.readableId
+msgid "{0} runs in batch {1}"
+msgstr ""
+
#. placeholder {0}: item.quantityScrapped
msgid "{0} Scrapped"
msgstr "{0} Refugado(s)"
+msgid "{completed} of {quantity}"
+msgstr "{completed} de {quantity}"
+
msgid "{completions} passed unit(s) will be completed."
msgstr "{completions} unidade(s) aprovada(s) será(ão) concluída(s)."
msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
msgstr "{fails} falha(s) amostrada(s) registrada(s) e NÃO será(ão) concluída(s) — resolva-as no menu de ações."
+#. placeholder {0}: step.perMember.length
+msgid "{recorded}/{0} jobs"
+msgstr ""
+
msgid "+{overflow} more"
msgstr "+{overflow} mais"
@@ -88,6 +114,10 @@ msgstr "Configurações da Conta"
msgid "Acknowledge & finish"
msgstr "Confirmar e finalizar"
+#. placeholder {0}: members.length
+msgid "across {0} jobs"
+msgstr "em {0} ordens de produção"
+
msgid "Active"
msgstr "Ativo"
@@ -118,6 +148,13 @@ msgstr "Todos"
msgid "All clear"
msgstr "Tudo limpo"
+msgid "All jobs"
+msgstr "Todas as ordens de produção"
+
+#. placeholder {0}: batch.outputLotNumber
+msgid "All output goes to lot <0>{0}</0>"
+msgstr "Toda saída vai para o lote <0>{0}</0>"
+
msgid "All rework"
msgstr "Todos para retrabalho"
@@ -166,6 +203,9 @@ msgstr "disponível"
msgid "Available"
msgstr "Disponível"
+msgid "Back to batch"
+msgstr ""
+
msgid "Batch"
msgstr "Lote"
@@ -179,12 +219,21 @@ msgstr "Número do Lote {0}"
msgid "Batch number is required"
msgstr "Número do lote é obrigatório"
-msgid "Batched jobs"
-msgstr "Ordens de produção em lote"
+msgid "Batch quantity"
+msgstr "Quantidade do lote de produção"
+
+msgid "batch total"
+msgstr "total do lote de produção"
msgid "Behind target by {daysBehindTarget} day(s)"
msgstr "Atraso de {daysBehindTarget} dia(s)"
+#. placeholder {0}: step.minValue
+#. placeholder {1}: step.maxValue
+#. placeholder {2}: step.unitOfMeasureCode ?? ""
+msgid "Between {0} and {1} {2}"
+msgstr ""
+
#. placeholder {0}: column.blockingDispatchReadableId
msgid "Blocked by {0}"
msgstr "Bloqueado por {0}"
@@ -222,6 +271,9 @@ msgstr "Chat"
msgid "Check your email"
msgstr "Verifique seu e-mail"
+msgid "Choose a job"
+msgstr ""
+
msgid "Clear"
msgstr "Limpar"
@@ -249,6 +301,9 @@ msgstr "Fechar"
msgid "Collapse features table"
msgstr "Recolher tabela de recursos"
+msgid "Collapse panel"
+msgstr "Recolher painel"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -278,6 +333,9 @@ msgstr "Concluir"
msgid "Complete All"
msgstr "Completar Tudo"
+msgid "Complete batch"
+msgstr ""
+
msgid "Complete Batch"
msgstr "Completar Lote"
@@ -377,6 +435,9 @@ msgstr "Exibição"
msgid "Displays"
msgstr "Exibições"
+msgid "Done"
+msgstr ""
+
msgid "Down"
msgstr "Parado"
@@ -409,9 +470,12 @@ msgstr "Arraste para redimensionar desenho e recursos"
msgid "Dragging {0} cancelled."
msgstr "Arraste de {0} cancelado."
+msgid "Due"
+msgstr ""
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
msgid "Due {0}"
msgstr "Vencimento {0}"
@@ -434,6 +498,9 @@ msgstr "Número de série duplicado"
msgid "Duration"
msgstr "Duração"
+msgid "Each job's output is its own lot — keep each job's parts apart."
+msgstr ""
+
msgid "Edit"
msgstr "Editar"
@@ -449,6 +516,9 @@ msgstr "Centros de trabalho vazios"
msgid "End Operations"
msgstr "Encerrar Operações"
+msgid "Enter each job's value, or fill every job at once from the first row. Empty rows are skipped."
+msgstr ""
+
#. placeholder {0}: selectedPerson.name
msgid "Enter PIN for {0}"
msgstr "Insira o PIN de {0}"
@@ -465,12 +535,18 @@ msgstr "Erro"
msgid "Estimated"
msgstr "Estimado"
+msgid "Every job in the batch follows these steps. Record a step for all of them at once."
+msgstr ""
+
msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
msgstr "Cada unidade tem um veredicto: {passes} aprovada(s) e {fails} reprovada(s). O lote fecha com cada unidade encaminhada para seu próprio resultado."
msgid "Expand features table"
msgstr "Expandir tabela de recursos"
+msgid "Expand panel"
+msgstr "Expandir painel"
+
msgid "Expired"
msgstr "Vencido"
@@ -511,6 +587,10 @@ msgstr "Falha ao salvar medição"
msgid "Failed to save result"
msgstr "Falha ao salvar resultado"
+#. placeholder {0}: file.name
+msgid "Failed to upload {0}"
+msgstr ""
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Falha ao enviar arquivo: {0}"
@@ -555,6 +635,10 @@ msgstr "Finalize a configuração de sua conta"
msgid "Finish with material unpicked?"
msgstr "Finalizar com material não selecionado?"
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(batchFacts.dueDate) )
+msgid "First due {0}"
+msgstr ""
+
msgid "Forgot to Clock Out?"
msgstr "Esqueceu de apontar fim?"
@@ -567,6 +651,9 @@ msgstr "Voltar para operação"
msgid "Go to onboarding"
msgstr "Ir para integração"
+msgid "Hide description"
+msgstr ""
+
msgid "How many were actually picked?"
msgstr "Quantos foram realmente apanhados?"
@@ -631,6 +718,9 @@ msgstr "Emitir Material"
msgid "Issue Type"
msgstr "Tipo de Problema"
+msgid "Issued"
+msgstr "Expedido"
+
msgid "Issued {issuedQuantity} of {lotLabel}"
msgstr "Emitido {issuedQuantity} de {lotLabel}"
@@ -688,6 +778,9 @@ msgstr "linhas"
msgid "List view"
msgstr "Visualização em lista"
+msgid "Load list"
+msgstr ""
+
msgid "Loading item details..."
msgstr "Carregando detalhes do item..."
@@ -700,6 +793,9 @@ msgstr "Local"
msgid "Location"
msgstr "Localização"
+msgid "Log completed"
+msgstr ""
+
msgid "Log Completed"
msgstr "Registrar Concluído"
@@ -727,6 +823,12 @@ msgstr "Entrar"
msgid "Lot"
msgstr "Lote"
+msgid "Lot numbers missing"
+msgstr "Números de lote ausentes"
+
+msgid "Lot tracked"
+msgstr ""
+
msgid "Machine"
msgstr "Máquina"
@@ -763,6 +865,9 @@ msgstr "corresponde"
msgid "Materials"
msgstr "Materiais"
+msgid "Materials issued"
+msgstr "Materiais expedidos"
+
msgid "Maximum number of records reached"
msgstr "Número máximo de registros atingido"
@@ -866,6 +971,9 @@ msgstr "Nenhuma correspondência. Digite para criar uma."
msgid "No materials"
msgstr "Nenhum material"
+msgid "No materials on this batch."
+msgstr "Nenhum material neste lote de produção."
+
msgid "No open jobs"
msgstr "Nenhuma ordem de produção aberta"
@@ -959,9 +1067,22 @@ msgstr "Impacto OEE"
msgid "OEM Required"
msgstr "OEM Necessário"
+#. placeholder {0}: m.operationQuantity ?? 0
+msgid "of {0}"
+msgstr ""
+
msgid "Oldest first"
msgstr "Mais antigo primeiro"
+msgid "one combined lot · planned"
+msgstr "um lote combinado · planejado"
+
+msgid "one per job · planned"
+msgstr "um por ordem de produção · planejado"
+
+msgid "One pick covers the whole batch — it is shared out to the jobs automatically."
+msgstr ""
+
#. placeholder {0}: batch.quantity
msgid "Only {0} available"
msgstr "Apenas {0} disponível"
@@ -975,6 +1096,9 @@ msgstr "Aberto"
msgid "Open a display on the screen mounted at the work center and leave it running. Each board refreshes on its own."
msgstr "Abra uma exibição na tela montada no centro de trabalho e deixe-a em execução. Cada quadro se atualiza automaticamente."
+msgid "Open a job in this batch"
+msgstr ""
+
msgid "Open an NCR for MRB disposition"
msgstr "Abrir um NCR para disposição MRB"
@@ -999,6 +1123,9 @@ msgstr "Opcional"
msgid "or"
msgstr "ou"
+msgid "Output lot"
+msgstr "Lote de saída"
+
msgid "Overall result"
msgstr "Resultado geral"
@@ -1017,6 +1144,9 @@ msgstr "Parcial"
msgid "Partial Disposition"
msgstr "Disposição Parcial"
+msgid "Passed inspection"
+msgstr ""
+
msgid "Passed Inspection"
msgstr "Aprovado na Inspeção"
@@ -1029,6 +1159,10 @@ msgstr "Pausar"
msgid "Pick"
msgstr "Apanhar"
+#. placeholder {0}: m.required - m.issued
+msgid "Pick {0}"
+msgstr "Separar {0}"
+
msgid "Pick tracked item"
msgstr "Selecionar item rastreado"
@@ -1098,6 +1232,9 @@ msgstr "Procedimento"
msgid "Process"
msgstr "Processo"
+msgid "Process parameters"
+msgstr "Parâmetros do processo"
+
msgid "Process Parameters"
msgstr "Parâmetros do Processo"
@@ -1140,18 +1277,28 @@ msgstr "Registrar"
msgid "Record {0}"
msgstr "Registro {0}"
+#. placeholder {0}: changed.length
+msgid "Record {0} jobs"
+msgstr ""
+
msgid "Record only"
msgstr "Apenas registrar"
msgid "Record Partial"
msgstr "Registrar Parcial"
+msgid "Recorded"
+msgstr ""
+
msgid "Reject"
msgstr "Rejeitar"
msgid "Reject Lot"
msgstr "Rejeitar Lote"
+msgid "Released"
+msgstr ""
+
msgid "Remove"
msgstr "Remover"
@@ -1167,6 +1314,9 @@ msgstr "Remover peça"
msgid "Reopen the subassembly and create a replacement unit"
msgstr "Reabrir o subconjunto e criar uma unidade de substituição"
+msgid "Required"
+msgstr "Obrigatório"
+
msgid "Result"
msgstr "Resultado"
@@ -1188,6 +1338,9 @@ msgstr "Em execução"
msgid "Sales Order"
msgstr "Pedido de Venda"
+msgid "Same for every job"
+msgstr ""
+
msgid "Save"
msgstr "Salvar"
@@ -1307,6 +1460,9 @@ msgstr "Enviar"
msgid "Send to Carbon"
msgstr "Enviar para Carbon"
+msgid "Separate lots"
+msgstr "Lotes separados"
+
msgid "Serial"
msgstr "Série"
@@ -1326,6 +1482,9 @@ msgstr "Números de série"
msgid "Serial Numbers"
msgstr "Números de Série"
+msgid "Serialized"
+msgstr ""
+
msgid "Session locked"
msgstr "Sessão bloqueada"
@@ -1338,6 +1497,9 @@ msgstr "Definir horário de saída"
msgid "Set up in Carbon"
msgstr "Configurar no Carbon"
+msgid "Set when the batch was planned."
+msgstr "Definido quando o lote de produção é planejado."
+
msgid "Setup"
msgstr "Setup"
@@ -1350,6 +1512,9 @@ msgstr "Falta"
msgid "Short pick {itemName}"
msgstr "Colheita curta {itemName}"
+msgid "Show description"
+msgstr ""
+
msgid "Show this overlay"
msgstr "Mostrar esta sobreposição"
@@ -1389,6 +1554,10 @@ msgstr "Peças de reposição utilizadas"
msgid "Start"
msgstr "Iniciar"
+#. placeholder {0}: workTypeLabels[ eventType.toLowerCase() as keyof typeof workTypeLabels ].toLowerCase()
+msgid "Start {0}"
+msgstr ""
+
msgid "Start or pause the operation"
msgstr "Iniciar ou pausar a operação"
@@ -1438,12 +1607,22 @@ msgstr "Etiqueta"
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "A quantidade concluída para esta operação é menor que a quantidade requerida de {targetQuantity}."
+msgid "The jobs and parts that make up this run."
+msgstr ""
+
+msgid "The jobs make different items — keep each job's parts apart."
+msgstr ""
+
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "O lote será marcado como Aprovado e {remaining} unidade(s) restante(s) será(ão) concluída(s) nesta operação."
msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "O lote ainda será disposicionado, mas um NCR não pode ser criado até que pelo menos um Tipo de Problema seja configurado."
+#. placeholder {0}: (batch.operations ?? []).length
+msgid "The timer and completion are shared by all {0} jobs. Steps, materials and files here are this job's own."
+msgstr ""
+
msgid "There are no available or consumed tracked parts for this material."
msgstr "Não há peças rastreadas disponíveis ou consumidas para este material."
@@ -1453,6 +1632,9 @@ msgstr "Existem materiais rastreados por série ou lote na lista de materiais qu
msgid "These items still have material to pick. Finishing now marks the list Partial."
msgstr "Estes itens ainda têm material para selecionar. Finalizar agora marca a lista como Parcial."
+msgid "This batch has no work instructions."
+msgstr ""
+
msgid "This lot is expired and can't be picked."
msgstr "Este lote está vencido e não pode ser separado."
@@ -1468,6 +1650,9 @@ msgstr "Esta unidade será permanentemente descartada e um novo número de séri
msgid "Thumbnail"
msgstr "Miniatura"
+msgid "Tick the jobs this was done for."
+msgstr ""
+
msgid "Time and cost split across jobs proportionally to quantity."
msgstr "Tempo e custo divididos entre as ordens de produção na proporção da quantidade."
@@ -1478,6 +1663,12 @@ msgstr "Registros de Horas"
msgid "Time Worked: {0}"
msgstr "Tempo Trabalhado: {0}"
+msgid "To pick"
+msgstr ""
+
+msgid "To run"
+msgstr ""
+
msgid "Today"
msgstr "Hoje"
@@ -1487,6 +1678,9 @@ msgstr "Alternar barra lateral"
msgid "Tools"
msgstr "Ferramentas"
+msgid "Total"
+msgstr ""
+
msgid "Total Quantity"
msgstr "Quantidade Total"
@@ -1501,6 +1695,9 @@ msgstr "Total: {0}"
msgid "Tracked Entity"
msgstr "Entidade Rastreada"
+msgid "tracked lines"
+msgstr "linhas rastreadas"
+
msgid "Tracking"
msgstr "Rastreamento"
@@ -1572,6 +1769,12 @@ msgstr "Enviando {0}"
msgid "Use a different account"
msgstr "Usar uma conta diferente"
+msgid "Used automatically at completion"
+msgstr ""
+
+msgid "Value"
+msgstr ""
+
msgid "Verify"
msgstr "Verificar"
@@ -1584,6 +1787,9 @@ msgstr "Enviamos um link mágico para você entrar na sua conta."
msgid "What is {translatedTerm}?"
msgstr "O que é {translatedTerm}?"
+msgid "Whole batch"
+msgstr "Todo o lote de produção"
+
msgid "WIP"
msgstr "Produto em processo"
@@ -1593,6 +1799,9 @@ msgstr "Centro de Trabalho"
msgid "Work Center Displays"
msgstr "Exibições do Centro de Trabalho"
+msgid "Work instructions"
+msgstr "Instruções de trabalho"
+
msgid "Yes"
msgstr "Sim"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index f7a74b5e4d..f7f55d3fbc 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -111,6 +111,10 @@ msgstr "{0} успешно удален"
msgid "{0} draft journal entries"
msgstr "{0} черновых операций"
+#. placeholder {0}: op.description
+msgid "{0} has no supplier"
+msgstr ""
+
#. placeholder {0}: formatter.format(onHand)
#. placeholder {1}: formatter.format(assembliesInStock)
#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
@@ -141,6 +145,10 @@ msgstr "{0} из {1} счетов проведения отображено"
msgid "{0} of {maxSlots} provider slots used"
msgstr "{0} из {maxSlots} слотов провайдера используется"
+#. placeholder {0}: pendingJobs.length
+msgid "{0} of {memberCount} member jobs are not completed yet — their output stays out of stock until each job is completed."
+msgstr "{0} из {memberCount} производственных заказов еще не завершены — их выпуск остается вне запаса до завершения каждого производственного заказа."
+
#. placeholder {0}: selected.length
msgid "{0} operations · {totalQuantity} parts"
msgstr "{0} операций · {totalQuantity} деталей"
@@ -1652,6 +1660,10 @@ msgstr "Все элементы"
msgid "All Locations"
msgstr "Все местоположения"
+#. placeholder {0}: tracked[0]?.itemReadableId ?? ""
+msgid "all make {0}"
+msgstr "все производят {0}"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "Все члены выбранных групп и выбранные лица смогут утвердить запросы"
@@ -3550,6 +3562,9 @@ msgstr "Проверьте вашу почту"
msgid "Checking Stripe for this customer…"
msgstr "Проверка Stripe для этого покупателя…"
+msgid "Checking the batch's jobs..."
+msgstr "Проверка производственных заказов серии..."
+
msgid "Checkpoint ·"
msgstr "Контрольная точка ·"
@@ -3574,6 +3589,10 @@ msgstr "Выберите строку слева, чтобы увидеть, о
msgid "Choose a serial number"
msgstr "Выберите серийный номер"
+#. placeholder {0}: op.description
+msgid "choose a supplier for {0} on the job"
+msgstr ""
+
msgid "Choose another file"
msgstr "Выбрать другой файл"
@@ -3736,6 +3755,9 @@ msgstr "Столбцы"
msgid "Combine filters"
msgstr "Объединить фильтры"
+msgid "Combine output into one lot"
+msgstr "Объединить выход в одну партию"
+
msgid "Coming soon"
msgstr "Скоро"
@@ -4526,6 +4548,9 @@ msgstr "Создать {0} значений"
msgid "Create & Release"
msgstr "Создать и запустить в работу"
+msgid "Create & release batch"
+msgstr "Создать и запустить в работу серию"
+
msgid "Create & Snapshot"
msgstr "Создать и снимок"
@@ -4598,6 +4623,9 @@ msgstr "Создать производственные заказы"
msgid "Create Kanban"
msgstr "Создать канбан"
+msgid "Create New"
+msgstr "Создать"
+
msgid "Create new rule"
msgstr "Создать новое правило"
@@ -6269,6 +6297,12 @@ msgstr "например Zebra 2x1"
msgid "Each cell is the people assigned against the people the day's work needs."
msgstr "Каждая ячейка — это назначенные сотрудники в сравнении с необходимыми для работы в день сотрудниками."
+msgid "Each job keeps its own lot. The shop floor can't change these."
+msgstr "Каждый производственный заказ сохраняет свою партию. Цех не может их менять."
+
+msgid "Each job needs its own lot number — or combine them into one lot."
+msgstr "Каждый производственный заказ требует собственный номер партии — или объедините их в одну партию."
+
msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."
msgstr "Каждая строка — это связь данных этой организации со строкой, которой она не владеет. Резервную копию с этими строками никогда не удастся восстановить."
@@ -6281,6 +6315,9 @@ msgstr "Неиспользованный материал каждой опер
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Каждая физическая единица получает свой отслеживаемый объект и уникальный номер — один объект, одна единица."
+msgid "Each supplier's outside operations from every job go on one new purchase order, or on an existing draft you choose."
+msgstr "Внешние операции каждого поставщика из каждого производственного заказа размещаются на одном новом заказе поставщику или на существующем черновике на ваш выбор."
+
msgid "Each, lb, ft…"
msgstr "Каждый, фунт, фут…"
@@ -7027,6 +7064,9 @@ msgstr "Все остальное"
msgid "Everything else covers people, imports, integrations and the API — anything that is not one of your workflows."
msgstr "Все остальное включает сотрудников, импорты, интеграции и API — все остальное, кроме ваших рабочих процессов."
+msgid "Everything this run makes lands in one lot. The shop floor can't change it."
+msgstr "Всё, что производится в этом цикле, попадает в одну партию. Цех не может это менять."
+
msgid "Exceeds {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB total — remove some attachments to send."
msgstr "Превышает {PO_EMAIL_ATTACHMENT_LIMIT_MB} МБ всего — удалите некоторые вложения для отправки."
@@ -7804,6 +7844,9 @@ msgstr "Уместить в окно"
msgid "Fix the problems with this workflow before testing it"
msgstr "Исправьте проблемы в этом рабочем процессе перед его тестированием"
+msgid "Fix these jobs before releasing"
+msgstr "Исправьте эти производственные заказы перед запуском"
+
msgid "Fixed"
msgstr "Фиксированный"
@@ -9610,7 +9653,7 @@ msgid "Lines"
msgstr "Строки"
msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."
-msgstr "Строки появляются здесь, когда поступление по заказу поставщику было проведено, и только для количеств, не уже запрошенных на другом возврате. Используйте «Добавить строку» для слепого возврата."
+msgstr "Строки появляются здесь, когда поступление проведено, и только для количеств, не авторизованных на другом возврате поставщику. Используйте добавление строки для слепого возврата."
msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."
msgstr "Строки появляются здесь после проведения отгрузки, и только для количеств, не авторизованных на другой RMA. Используйте функцию «Добавить строку» для слепого возврата."
@@ -9806,6 +9849,9 @@ msgstr "Проиграно"
msgid "Lot"
msgstr "Партия"
+msgid "Lot number"
+msgstr "Номер партии"
+
msgid "Lot size"
msgstr "Размер партии"
@@ -9986,6 +10032,9 @@ msgstr "Номер детали производителя"
msgid "Manufacturing"
msgstr "Производство"
+msgid "manufacturing is blocked"
+msgstr "Производство заблокировано"
+
msgid "Map accounts"
msgstr "Сопоставить счета"
@@ -10275,6 +10324,13 @@ msgstr "ID Памятки"
msgid "Merchant"
msgstr "Продавец"
+#. placeholder {0}: getItemReadableId(items, itemId) ?? itemId
+msgid "Merge {0} lots"
+msgstr ""
+
+msgid "Merge output lots"
+msgstr "Объединить выходные партии"
+
msgid "MES"
msgstr "MES"
@@ -11264,6 +11320,10 @@ msgstr "Нет открытых строк заказов покупателя"
msgid "No operations found."
msgstr "Операции не найдены."
+#. placeholder {0}: job.missingAssemblies .map((m) => m.description) .join(", ")
+msgid "no operations on {0}"
+msgstr "нет операций на {0}"
+
msgid "No operations require picking at this location"
msgstr "Ни одна операция не требует отбора на этой площадке"
@@ -13014,6 +13074,12 @@ msgstr "Процессы"
msgid "Procurement status — needs ordering, planned, on order, or received. The same indicator shown in the BoM tree."
msgstr "Статус снабжения — требуется заказ, запланировано, заказано или получено. Тот же индикатор, что показан в дереве BoM."
+msgid "produced item"
+msgstr "произведенная номенклатура"
+
+msgid "Produced item"
+msgstr "Произведенная номенклатура"
+
msgid "Product issues during hypercare"
msgstr "Проблемы с продуктом во время гиперпомощи"
@@ -13923,6 +13989,11 @@ msgstr "Запустить в работу {0} серий"
msgid "Release Batch"
msgstr "Запустить серию в работу"
+#. placeholder {0}: batch.readableId
+#. placeholder {0}: releaseTarget.readableId
+msgid "Release batch {0}"
+msgstr "Запустить в работу серию {0}"
+
msgid "Release change notice"
msgstr "Запустить в работу извещение об изменении"
@@ -13951,6 +14022,9 @@ msgstr "Выпущенная ревизия"
msgid "Released revision is locked"
msgstr "Выпущенная ревизия заблокирована"
+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
+msgstr "Запуск серии запускает её производственные заказы, и каждый должен быть готов к цеху."
+
msgid "Remaining"
msgstr "Остаток"
@@ -15324,7 +15398,7 @@ msgid "Select operations"
msgstr "Выберите операции"
msgid "Select posted receipt lines from this supplier to return."
-msgstr "Выберите проведённые строки поступления от этого поставщика для возврата."
+msgstr "Выберите проведенные строки поступления от этого поставщика для возврата."
msgid "Select posted shipment lines to this customer to return."
msgstr "Выберите проведённые строки отгрузки этому покупателю для возврата."
@@ -15523,7 +15597,7 @@ msgid "Session locked"
msgstr "Сеанс заблокирован"
msgid "Set a customer on this return to add from a shipment."
-msgstr "Установите покупателя для этого возврата чтобы добавить из отгрузки."
+msgstr "Укажите покупателя в этом возврате для добавления из отгрузки."
msgid "Set a supplier on this return to add from a receipt."
msgstr "Установите поставщика для этого возврата, чтобы добавить из поступления."
@@ -15822,6 +15896,10 @@ msgstr "Сочетания клавиш"
msgid "Show"
msgstr "Показать"
+#. placeholder {0}: overflow.length
+msgid "Show {0} more"
+msgstr ""
+
msgid "Show a readable Customer ID column on the customer list, customer forms, and dropdowns. Customers are still identified internally either way."
msgstr "Показывать столбец с читаемым ID Покупателя в списке покупателей, формах и выпадающих списках. Покупатели по-прежнему идентифицируются внутренне одинаково."
@@ -16981,6 +17059,9 @@ msgstr "Задача резервного копирования сообщил
msgid "The backward-computed date an operation must finish by to keep its job on time, written to the operation's due date. A stable target for measuring progress — never a constraint on placement."
msgstr "Дата завершения операции, вычисленная в обратном порядке, чтобы производственный заказ был выполнен вовремя, записываемая в срок выполнения операции. Стабильная цель для измерения прогресса — никогда не является ограничением при размещении."
+msgid "The batch goes to the shop floor. Its jobs are already released."
+msgstr "Серия поступает на цех. Её производственные заказы уже запущены."
+
msgid "The batch runs at its most urgent member's time — the others are pulled early"
msgstr "Партия выполняется по самому срочному элементу — остальные сдвигаются раньше"
@@ -17266,6 +17347,9 @@ msgstr "Себестоимость Запасов, признаваемая пр
msgid "The IRS recovery-period class for this asset under MACRS (3, 5, 7, 10, 15, 20, 27.5, 39-year)."
msgstr "Класс периода восстановления IRS для этого основного средства в соответствии с MACRS (3, 5, 7, 10, 15, 20, 27,5, 39 лет)."
+msgid "The item each job produces — require it to match to merge output lots"
+msgstr "Номенклатура, которую производит каждый производственный заказ — требуется совпадение для объединения выходных партий"
+
msgid "the job hours due that day (a due-date basis, not the day the work runs), with overdue work in Past due."
msgstr "рабочие часы, подлежащие в этот день (на основе даты срока, не дня выполнения работы), с просроченной работой в разделе «Просроченные»."
@@ -17800,6 +17884,11 @@ msgstr "Эти строки ссылаются на данные вне этой
msgid "this ability"
msgstr "этот навык"
+#. placeholder {0}: jobIds.length
+#. placeholder {1}: jobIds.join(", ")
+msgid "This also releases {0} jobs ({1}). They become available to the shop floor and drive purchasing and production."
+msgstr "Это также запускает {0} производственных заказов ({1}). Они становятся доступны цеху и управляют закупками и производством."
+
msgid "This backup could not be completed."
msgstr "Эта резервная копия не может быть завершена."
diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.po
index a8ba88623e..9a2c0c5a1c 100644
--- a/packages/locale/locales/ru/mes.po
+++ b/packages/locale/locales/ru/mes.po
@@ -25,14 +25,28 @@ msgstr "{0} Активных"
msgid "{0} ago"
msgstr "{0} назад"
+#. placeholder {0}: batchFacts.customers.length
+msgid "{0} customers"
+msgstr ""
+
+#. placeholder {0}: unplanned .map( (m) => (m.job as { jobId?: string | null } | null)?.jobId ) .filter(Boolean) .join(", ")
+msgid "{0} has no lot number. Set it on the batch or job in Carbon, then complete."
+msgstr "{0} не имеет номера партии. Установите его в серии или производственном заказе в Carbon, затем завершите."
+
+#. placeholder {0}: batchFacts.items.length
+msgid "{0} items"
+msgstr ""
+
#. placeholder {0}: (batch.operations ?? []).length
msgid "{0} jobs"
msgstr "{0} производственные заказы"
+#. placeholder {0}: issuedLines.length
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
#. placeholder {1}: operation.targetQuantity
+#. placeholder {1}: trackedLines.length
msgid "{0} of {1}"
msgstr "{0} из {1}"
@@ -54,16 +68,28 @@ msgstr "{0} в очереди"
msgid "{0} running"
msgstr "{0} выполняется"
+#. placeholder {0}: operation.jobReadableId
+#. placeholder {1}: batch.readableId
+msgid "{0} runs in batch {1}"
+msgstr ""
+
#. placeholder {0}: item.quantityScrapped
msgid "{0} Scrapped"
msgstr "{0} Списано"
+msgid "{completed} of {quantity}"
+msgstr "{completed} из {quantity}"
+
msgid "{completions} passed unit(s) will be completed."
msgstr "{completions} пройденных единиц будут завершены."
msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
msgstr "{fails} записанных отказов будут НЕ завершены — разрешите их из меню действий."
+#. placeholder {0}: step.perMember.length
+msgid "{recorded}/{0} jobs"
+msgstr ""
+
msgid "+{overflow} more"
msgstr "+{overflow} ещё"
@@ -88,6 +114,10 @@ msgstr "Настройки аккаунта"
msgid "Acknowledge & finish"
msgstr "Подтвердить и завершить"
+#. placeholder {0}: members.length
+msgid "across {0} jobs"
+msgstr "в {0} производственных заказах"
+
msgid "Active"
msgstr "Активные"
@@ -118,6 +148,13 @@ msgstr "Все"
msgid "All clear"
msgstr "Все в порядке"
+msgid "All jobs"
+msgstr "Все производственные заказы"
+
+#. placeholder {0}: batch.outputLotNumber
+msgid "All output goes to lot <0>{0}</0>"
+msgstr "Весь выпуск идёт в партию <0>{0}</0>"
+
msgid "All rework"
msgstr "Все доработки"
@@ -166,6 +203,9 @@ msgstr "доступно"
msgid "Available"
msgstr "Доступно"
+msgid "Back to batch"
+msgstr ""
+
msgid "Batch"
msgstr "Партия"
@@ -179,12 +219,21 @@ msgstr "Номер партии {0}"
msgid "Batch number is required"
msgstr "Номер партии обязателен"
-msgid "Batched jobs"
-msgstr "Производственные заказы в серии"
+msgid "Batch quantity"
+msgstr "Количество серии"
+
+msgid "batch total"
+msgstr "итого серии"
msgid "Behind target by {daysBehindTarget} day(s)"
msgstr "Отставание на {daysBehindTarget} дн."
+#. placeholder {0}: step.minValue
+#. placeholder {1}: step.maxValue
+#. placeholder {2}: step.unitOfMeasureCode ?? ""
+msgid "Between {0} and {1} {2}"
+msgstr ""
+
#. placeholder {0}: column.blockingDispatchReadableId
msgid "Blocked by {0}"
msgstr "Заблокировано {0}"
@@ -222,6 +271,9 @@ msgstr "Чат"
msgid "Check your email"
msgstr "Проверьте вашу электронную почту"
+msgid "Choose a job"
+msgstr ""
+
msgid "Clear"
msgstr "Очистить"
@@ -249,6 +301,9 @@ msgstr "Закрыть"
msgid "Collapse features table"
msgstr "Свернуть таблицу функций"
+msgid "Collapse panel"
+msgstr "Свернуть панель"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -278,6 +333,9 @@ msgstr "Завершить"
msgid "Complete All"
msgstr "Завершить все"
+msgid "Complete batch"
+msgstr ""
+
msgid "Complete Batch"
msgstr "Завершить партию"
@@ -377,6 +435,9 @@ msgstr "Отображение"
msgid "Displays"
msgstr "Дисплеи"
+msgid "Done"
+msgstr ""
+
msgid "Down"
msgstr "Простой"
@@ -409,9 +470,12 @@ msgstr "Перетащите, чтобы изменить размер черт
msgid "Dragging {0} cancelled."
msgstr "Перетаскивание {0} отменено."
+msgid "Due"
+msgstr ""
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
msgid "Due {0}"
msgstr "Срок {0}"
@@ -434,6 +498,9 @@ msgstr "Дублированный серийный номер"
msgid "Duration"
msgstr "Длительность"
+msgid "Each job's output is its own lot — keep each job's parts apart."
+msgstr ""
+
msgid "Edit"
msgstr "Изменить"
@@ -449,6 +516,9 @@ msgstr "Пустые рабочие центры"
msgid "End Operations"
msgstr "Завершить операции"
+msgid "Enter each job's value, or fill every job at once from the first row. Empty rows are skipped."
+msgstr ""
+
#. placeholder {0}: selectedPerson.name
msgid "Enter PIN for {0}"
msgstr "Введите PIN для {0}"
@@ -465,12 +535,18 @@ msgstr "Ошибка"
msgid "Estimated"
msgstr "План"
+msgid "Every job in the batch follows these steps. Record a step for all of them at once."
+msgstr ""
+
msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
msgstr "Каждая единица имеет результат: {passes} пройдено и {fails} отклонено. Партия закрывается с распределением каждой единицы по её результату."
msgid "Expand features table"
msgstr "Развернуть таблицу функций"
+msgid "Expand panel"
+msgstr "Развернуть панель"
+
msgid "Expired"
msgstr "Истек срок"
@@ -511,6 +587,10 @@ msgstr "Не удалось сохранить измерение"
msgid "Failed to save result"
msgstr "Не удалось сохранить результат"
+#. placeholder {0}: file.name
+msgid "Failed to upload {0}"
+msgstr ""
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Не удалось загрузить файл: {0}"
@@ -555,6 +635,10 @@ msgstr "Завершите настройку вашего аккаунта"
msgid "Finish with material unpicked?"
msgstr "Завершить с неподобранным материалом?"
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(batchFacts.dueDate) )
+msgid "First due {0}"
+msgstr ""
+
msgid "Forgot to Clock Out?"
msgstr "Забыли отметить окончание работы?"
@@ -567,6 +651,9 @@ msgstr "Вернуться к операции"
msgid "Go to onboarding"
msgstr "Перейти к первоначальной настройке"
+msgid "Hide description"
+msgstr ""
+
msgid "How many were actually picked?"
msgstr "Сколько было фактически собрано?"
@@ -631,6 +718,9 @@ msgstr "Выдать материал"
msgid "Issue Type"
msgstr "Тип проблемы"
+msgid "Issued"
+msgstr "Отпущено"
+
msgid "Issued {issuedQuantity} of {lotLabel}"
msgstr "Выпущено {issuedQuantity} из {lotLabel}"
@@ -688,6 +778,9 @@ msgstr "строки"
msgid "List view"
msgstr "Вид списка"
+msgid "Load list"
+msgstr ""
+
msgid "Loading item details..."
msgstr "Загрузка данных номенклатуры..."
@@ -700,6 +793,9 @@ msgstr "Локально"
msgid "Location"
msgstr "Расположение"
+msgid "Log completed"
+msgstr ""
+
msgid "Log Completed"
msgstr "Записать готовые"
@@ -727,6 +823,12 @@ msgstr "Вход"
msgid "Lot"
msgstr "Партия"
+msgid "Lot numbers missing"
+msgstr "Номера партий отсутствуют"
+
+msgid "Lot tracked"
+msgstr ""
+
msgid "Machine"
msgstr "Станок"
@@ -763,6 +865,9 @@ msgstr "соответствует"
msgid "Materials"
msgstr "Материалы"
+msgid "Materials issued"
+msgstr "Отпущенные материалы"
+
msgid "Maximum number of records reached"
msgstr "Достигнуто максимальное количество записей"
@@ -866,6 +971,9 @@ msgstr "Совпадений не найдено. Введите текст дл
msgid "No materials"
msgstr "Нет материалов"
+msgid "No materials on this batch."
+msgstr "На этой серии нет материалов."
+
msgid "No open jobs"
msgstr "Нет открытых производственных заказов"
@@ -959,9 +1067,22 @@ msgstr "Влияние на OEE"
msgid "OEM Required"
msgstr "Требуется OEM"
+#. placeholder {0}: m.operationQuantity ?? 0
+msgid "of {0}"
+msgstr ""
+
msgid "Oldest first"
msgstr "Самые старые первыми"
+msgid "one combined lot · planned"
+msgstr "одна объединённая партия · запланировано"
+
+msgid "one per job · planned"
+msgstr "одна на производственный заказ · запланировано"
+
+msgid "One pick covers the whole batch — it is shared out to the jobs automatically."
+msgstr ""
+
#. placeholder {0}: batch.quantity
msgid "Only {0} available"
msgstr "Доступно только {0}"
@@ -975,6 +1096,9 @@ msgstr "Открытые"
msgid "Open a display on the screen mounted at the work center and leave it running. Each board refreshes on its own."
msgstr "Откройте дисплей на экране, установленном на рабочем центре, и оставьте его работать. Каждая доска обновляется автоматически."
+msgid "Open a job in this batch"
+msgstr ""
+
msgid "Open an NCR for MRB disposition"
msgstr "Открыть NCR для решения MRB"
@@ -999,6 +1123,9 @@ msgstr "Опционально"
msgid "or"
msgstr "или"
+msgid "Output lot"
+msgstr "Партия выпуска"
+
msgid "Overall result"
msgstr "Общий результат"
@@ -1017,6 +1144,9 @@ msgstr "Частичный"
msgid "Partial Disposition"
msgstr "Частичное решение"
+msgid "Passed inspection"
+msgstr ""
+
msgid "Passed Inspection"
msgstr "Контроль пройден"
@@ -1029,6 +1159,10 @@ msgstr "Приостановить"
msgid "Pick"
msgstr "Выбрать"
+#. placeholder {0}: m.required - m.issued
+msgid "Pick {0}"
+msgstr "Отобрать {0}"
+
msgid "Pick tracked item"
msgstr "Выбрать отслеживаемый товар"
@@ -1098,6 +1232,9 @@ msgstr "Процедура"
msgid "Process"
msgstr "Процесс"
+msgid "Process parameters"
+msgstr "Параметры процесса"
+
msgid "Process Parameters"
msgstr "Параметры процесса"
@@ -1140,18 +1277,28 @@ msgstr "Записать"
msgid "Record {0}"
msgstr "Запись {0}"
+#. placeholder {0}: changed.length
+msgid "Record {0} jobs"
+msgstr ""
+
msgid "Record only"
msgstr "Только записать"
msgid "Record Partial"
msgstr "Записать частичный результат"
+msgid "Recorded"
+msgstr ""
+
msgid "Reject"
msgstr "Отклонить"
msgid "Reject Lot"
msgstr "Отклонить партию"
+msgid "Released"
+msgstr ""
+
msgid "Remove"
msgstr "Убрать"
@@ -1167,6 +1314,9 @@ msgstr "Убрать деталь"
msgid "Reopen the subassembly and create a replacement unit"
msgstr "Открыть заново узел и создать единицу для замены"
+msgid "Required"
+msgstr "Требуется"
+
msgid "Result"
msgstr "Результат"
@@ -1188,6 +1338,9 @@ msgstr "Работает"
msgid "Sales Order"
msgstr "Заказ покупателя"
+msgid "Same for every job"
+msgstr ""
+
msgid "Save"
msgstr "Сохранить"
@@ -1307,6 +1460,9 @@ msgstr "Отправить"
msgid "Send to Carbon"
msgstr "Отправить в Carbon"
+msgid "Separate lots"
+msgstr "Отдельные партии"
+
msgid "Serial"
msgstr "Серийный"
@@ -1326,6 +1482,9 @@ msgstr "Серийные номера"
msgid "Serial Numbers"
msgstr "Серийные номера"
+msgid "Serialized"
+msgstr ""
+
msgid "Session locked"
msgstr "Сеанс заблокирован"
@@ -1338,6 +1497,9 @@ msgstr "Установить время ухода"
msgid "Set up in Carbon"
msgstr "Настроить в Carbon"
+msgid "Set when the batch was planned."
+msgstr "Установлено при планировании серии."
+
msgid "Setup"
msgstr "Наладка"
@@ -1350,6 +1512,9 @@ msgstr "Недостача"
msgid "Short pick {itemName}"
msgstr "Короткий отбор {itemName}"
+msgid "Show description"
+msgstr ""
+
msgid "Show this overlay"
msgstr "Показать это окно"
@@ -1389,6 +1554,10 @@ msgstr "Использованные запасные части"
msgid "Start"
msgstr "Старт"
+#. placeholder {0}: workTypeLabels[ eventType.toLowerCase() as keyof typeof workTypeLabels ].toLowerCase()
+msgid "Start {0}"
+msgstr ""
+
msgid "Start or pause the operation"
msgstr "Запустить или приостановить операцию"
@@ -1438,12 +1607,22 @@ msgstr "Тег"
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "Количество готовой продукции по этой операции меньше требуемого количества {targetQuantity}."
+msgid "The jobs and parts that make up this run."
+msgstr ""
+
+msgid "The jobs make different items — keep each job's parts apart."
+msgstr ""
+
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "Партия будет отмечена как Пройдена, и {remaining} оставшихся единиц будут завершены в этой операции."
msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "Партия все еще будет распределена, но NCR не может быть создана до тех пор, пока не будет настроен хотя бы один тип проблемы."
+#. placeholder {0}: (batch.operations ?? []).length
+msgid "The timer and completion are shared by all {0} jobs. Steps, materials and files here are this job's own."
+msgstr ""
+
msgid "There are no available or consumed tracked parts for this material."
msgstr "Для этого материала нет доступных или израсходованных отслеживаемых деталей."
@@ -1453,6 +1632,9 @@ msgstr "В спецификации есть материалы с серийн
msgid "These items still have material to pick. Finishing now marks the list Partial."
msgstr "Эти позиции еще содержат материал для отбора. Завершение сейчас отметит список как частичный."
+msgid "This batch has no work instructions."
+msgstr ""
+
msgid "This lot is expired and can't be picked."
msgstr "Срок этой партии истек, и она не может быть отобрана."
@@ -1468,6 +1650,9 @@ msgstr "Эта единица будет окончательно списана
msgid "Thumbnail"
msgstr "Миниатюра"
+msgid "Tick the jobs this was done for."
+msgstr ""
+
msgid "Time and cost split across jobs proportionally to quantity."
msgstr "Время и себестоимость распределяются между производственными заказами пропорционально количеству."
@@ -1478,6 +1663,12 @@ msgstr "Записи учёта времени"
msgid "Time Worked: {0}"
msgstr "Отработанное время: {0}"
+msgid "To pick"
+msgstr ""
+
+msgid "To run"
+msgstr ""
+
msgid "Today"
msgstr "Сегодня"
@@ -1487,6 +1678,9 @@ msgstr "Открыть/закрыть боковую панель"
msgid "Tools"
msgstr "Инструменты"
+msgid "Total"
+msgstr ""
+
msgid "Total Quantity"
msgstr "Общее количество"
@@ -1501,6 +1695,9 @@ msgstr "Итого: {0}"
msgid "Tracked Entity"
msgstr "Отслеживаемый объект"
+msgid "tracked lines"
+msgstr "отслеживаемые строки"
+
msgid "Tracking"
msgstr "Отслеживание"
@@ -1572,6 +1769,12 @@ msgstr "Загрузка {0}"
msgid "Use a different account"
msgstr "Использовать другой аккаунт"
+msgid "Used automatically at completion"
+msgstr ""
+
+msgid "Value"
+msgstr ""
+
msgid "Verify"
msgstr "Подтвердить"
@@ -1584,6 +1787,9 @@ msgstr "Мы отправили вам ссылку для входа в ваш
msgid "What is {translatedTerm}?"
msgstr "Что такое {translatedTerm}?"
+msgid "Whole batch"
+msgstr "Вся серия"
+
msgid "WIP"
msgstr "Незавершенное производство"
@@ -1593,6 +1799,9 @@ msgstr "Рабочий центр"
msgid "Work Center Displays"
msgstr "Дисплеи рабочего центра"
+msgid "Work instructions"
+msgstr "Рабочие инструкции"
+
msgid "Yes"
msgstr "Да"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 2b900f66ce..da923d9558 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -111,6 +111,10 @@ msgstr "{0} başarıyla silindi"
msgid "{0} draft journal entries"
msgstr "{0} taslak muhasebe fişi"
+#. placeholder {0}: op.description
+msgid "{0} has no supplier"
+msgstr ""
+
#. placeholder {0}: formatter.format(onHand)
#. placeholder {1}: formatter.format(assembliesInStock)
#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
@@ -141,6 +145,10 @@ msgstr "{0}/{1} muhasebeleştirme hesabı eşleştirildi"
msgid "{0} of {maxSlots} provider slots used"
msgstr "{0}/{maxSlots} sağlayıcı yuvası kullanıldı"
+#. placeholder {0}: pendingJobs.length
+msgid "{0} of {memberCount} member jobs are not completed yet — their output stays out of stock until each job is completed."
+msgstr "{0} / {memberCount} üye iş emirlerinin henüz tamamlanmadığı — bunların çıktısı her bir iş emri tamamlanana kadar stok dışında kalır."
+
#. placeholder {0}: selected.length
msgid "{0} operations · {totalQuantity} parts"
msgstr "{0} operasyon · {totalQuantity} parça"
@@ -1370,7 +1378,7 @@ msgid "Add from library…"
msgstr "Kütüphaneden ekle…"
msgid "Add from receipt"
-msgstr "Mal kabulünden ekle"
+msgstr "Mal kabul'dan ekle"
msgid "Add from shipment"
msgstr "Sevkiyattan ekle"
@@ -1652,6 +1660,10 @@ msgstr "Tüm Öğeler"
msgid "All Locations"
msgstr "Tüm Konumlar"
+#. placeholder {0}: tracked[0]?.itemReadableId ?? ""
+msgid "all make {0}"
+msgstr "tümü {0} üretim"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "Seçilen gruplardaki ve bireylerdeki tüm üyeler talepleri onaylayabilecektir"
@@ -3550,6 +3562,9 @@ msgstr "E-postanızı kontrol edin"
msgid "Checking Stripe for this customer…"
msgstr "Bu müşteri için Stripe kontrol ediliyor…"
+msgid "Checking the batch's jobs..."
+msgstr "Partinin iş emirleri kontrol ediliyor..."
+
msgid "Checkpoint ·"
msgstr "Kontrol Noktası ·"
@@ -3574,6 +3589,10 @@ msgstr "Stokun nereden gelebileceğini görmek için sol taraftaki bir satırı
msgid "Choose a serial number"
msgstr "Bir seri numarası seçin"
+#. placeholder {0}: op.description
+msgid "choose a supplier for {0} on the job"
+msgstr ""
+
msgid "Choose another file"
msgstr "Başka bir dosya seç"
@@ -3736,6 +3755,9 @@ msgstr "Sütunlar"
msgid "Combine filters"
msgstr "Filtreleri birleştir"
+msgid "Combine output into one lot"
+msgstr "Çıktıyı bir Lota birleştir"
+
msgid "Coming soon"
msgstr "Yakında"
@@ -4526,6 +4548,9 @@ msgstr "{0} değerleri oluştur"
msgid "Create & Release"
msgstr "Oluştur ve Serbest Bırak"
+msgid "Create & release batch"
+msgstr "Parti oluştur ve serbest bırak"
+
msgid "Create & Snapshot"
msgstr "Oluştur & Anlık Görüntü"
@@ -4598,6 +4623,9 @@ msgstr "İş emirleri oluştur"
msgid "Create Kanban"
msgstr "Kanban Oluştur"
+msgid "Create New"
+msgstr "Yeni oluştur"
+
msgid "Create new rule"
msgstr "Yeni kural oluştur"
@@ -6269,6 +6297,12 @@ msgstr "örneğin Zebra 2x1"
msgid "Each cell is the people assigned against the people the day's work needs."
msgstr "Her hücre, atanmış personeli ile günün işinin gerektirdiği personeli gösterir."
+msgid "Each job keeps its own lot. The shop floor can't change these."
+msgstr "Her İş emri kendi Lotunu tutar. Atölye bunları değiştiremez."
+
+msgid "Each job needs its own lot number — or combine them into one lot."
+msgstr "Her İş emri kendi Lot numarasına ihtiyaç duyar — veya bunları bir Lota birleştir."
+
msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."
msgstr "Her satır, bu şirketin verilerinden sahibi olmadığı bir satıra bir bağlantıdır. Bu satırları içeren bir yedekleme asla geri yüklenemez."
@@ -6281,6 +6315,9 @@ msgstr "Her operasyonun kullanılmayan malzemesi operasyon tamamlandıktan hemen
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Her fiziksel birim kendi izlenen varlığını ve benzersiz numarasını alır — bir varlık, bir birim."
+msgid "Each supplier's outside operations from every job go on one new purchase order, or on an existing draft you choose."
+msgstr "Her tedarikçinin her iş emrinden dış operasyonları yeni bir satın alma siparişine veya seçtiğiniz mevcut bir taslağa yazılır."
+
msgid "Each, lb, ft…"
msgstr "Her, lb, ft…"
@@ -7027,6 +7064,9 @@ msgstr "Her şey başka"
msgid "Everything else covers people, imports, integrations and the API — anything that is not one of your workflows."
msgstr "Geri kalan her şey personel, içe aktarmalar, entegrasyonlar ve API'yi kapsar — iş akışlarınızdan biri olmayan herhangi bir şey."
+msgid "Everything this run makes lands in one lot. The shop floor can't change it."
+msgstr "Bu çalışmanın ürettiği her şey bir Lota iniş yapar. Atölye bunu değiştiremez."
+
msgid "Exceeds {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB total — remove some attachments to send."
msgstr "Toplamda {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB'ı aşıyor — göndermek için bazı ekler kaldırın."
@@ -7804,6 +7844,9 @@ msgstr "Uygun görünümü"
msgid "Fix the problems with this workflow before testing it"
msgstr "Bu iş akışının problemlerini test etmeden önce düzeltiniz"
+msgid "Fix these jobs before releasing"
+msgstr "Serbest bırakmadan önce bu iş emirlerini düzeltin"
+
msgid "Fixed"
msgstr "Sabit"
@@ -9610,7 +9653,7 @@ msgid "Lines"
msgstr "Satırlar"
msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."
-msgstr "Satırlar bir satın alma siparişi mal kabulü muhasebeleştirildiğinde burada görünür ve yalnızca başka bir tedarikçi iadesinde henüz yetkilendirilmemiş miktarlar için. Kör iade için Satır Öğesi Ekle'yi kullanın."
+msgstr "Satın alma siparişi mal kabulu muhasebeleştirildiğinde satırlar burada görüntülenir ve yalnızca başka bir tedarikçi iadesi üzerinde henüz yetkilendirilmemiş miktarlar için. Kör iade için Satır Ekle'yi kullanın."
msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."
msgstr "Satırlar, bir satış siparişi sevkiyatı muhasebeleştirildiğinde burada görünür ve yalnızca başka bir RMA üzerinde zaten yetkilendirilmemiş miktarlar için. Kör iade için satırı ekle kullanın."
@@ -9806,6 +9849,9 @@ msgstr "Kaybedildi"
msgid "Lot"
msgstr "Lot"
+msgid "Lot number"
+msgstr "Lot numarası"
+
msgid "Lot size"
msgstr "parti büyüklüğü"
@@ -9986,6 +10032,9 @@ msgstr "Üretici Parça Numarası"
msgid "Manufacturing"
msgstr "Üretim"
+msgid "manufacturing is blocked"
+msgstr "üretim engellendi"
+
msgid "Map accounts"
msgstr "Hesapları Eşle"
@@ -10275,6 +10324,13 @@ msgstr "Muhasebe Belgesi Kimliği"
msgid "Merchant"
msgstr "Satıcı"
+#. placeholder {0}: getItemReadableId(items, itemId) ?? itemId
+msgid "Merge {0} lots"
+msgstr ""
+
+msgid "Merge output lots"
+msgstr "Çıkış lotlarını birleştir"
+
msgid "MES"
msgstr "MES"
@@ -11264,6 +11320,10 @@ msgstr "Açık satış sipariş satırı yok"
msgid "No operations found."
msgstr "Operasyon bulunamadı."
+#. placeholder {0}: job.missingAssemblies .map((m) => m.description) .join(", ")
+msgid "no operations on {0}"
+msgstr "Operasyon yok {0} üzerinde"
+
msgid "No operations require picking at this location"
msgstr "Bu lokasyonda toplama gerektiren operasyon yok"
@@ -13014,6 +13074,12 @@ msgstr "Süreçler"
msgid "Procurement status — needs ordering, planned, on order, or received. The same indicator shown in the BoM tree."
msgstr "Tedarik durumu — sipariş gerekli, planlandı, siparişte veya teslim alındı. BoM ağacında gösterilen göstergeyle aynı."
+msgid "produced item"
+msgstr "üretilen stok kartı"
+
+msgid "Produced item"
+msgstr "Üretilen stok kartı"
+
msgid "Product issues during hypercare"
msgstr "Hypercare sırasında ürün sorunları"
@@ -13923,6 +13989,11 @@ msgstr "{0} partiyi serbest bırak"
msgid "Release Batch"
msgstr "Partiyi Serbest Bırak"
+#. placeholder {0}: batch.readableId
+#. placeholder {0}: releaseTarget.readableId
+msgid "Release batch {0}"
+msgstr "Parti {0} serbest bırak"
+
msgid "Release change notice"
msgstr "Değişiklik bildirimi serbest bırak"
@@ -13951,6 +14022,9 @@ msgstr "Yayınlanan revizyon"
msgid "Released revision is locked"
msgstr "Yayınlanan revizyon kilitlidir"
+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
+msgstr "Partiyi serbest bırakmak iş emirlerini serbest bırakır ve her birinin atölye için hazır olması gerekir."
+
msgid "Remaining"
msgstr "Kalan"
@@ -15324,7 +15398,7 @@ msgid "Select operations"
msgstr "Operasyon seç"
msgid "Select posted receipt lines from this supplier to return."
-msgstr "Bu tedarikçiden muhasebeleştirilmiş mal kabul satırlarını iade için seçin."
+msgstr "Bu tedarikçiden muhasebeleştirilmiş mal kabul satırlarını iade etmek üzere seçin."
msgid "Select posted shipment lines to this customer to return."
msgstr "Bu müşteriye muhasebeleştirilmiş sevkiyat satırlarını iade etmek için seçin."
@@ -15523,7 +15597,7 @@ msgid "Session locked"
msgstr "Oturum Kilitli"
msgid "Set a customer on this return to add from a shipment."
-msgstr "Sevkiyattan eklemek için bu iadede bir müşteri ayarlayın."
+msgstr "Sevkiyat'dan eklemek için bu iade'de bir müşteri ayarlayın."
msgid "Set a supplier on this return to add from a receipt."
msgstr "Mal kabulünden eklemek için bu iade kaydında bir tedarikçi belirleyin."
@@ -15822,6 +15896,10 @@ msgstr "Kısayollar"
msgid "Show"
msgstr "Göster"
+#. placeholder {0}: overflow.length
+msgid "Show {0} more"
+msgstr ""
+
msgid "Show a readable Customer ID column on the customer list, customer forms, and dropdowns. Customers are still identified internally either way."
msgstr "Müşteri listesinde, müşteri formlarında ve açılır menülerde okunabilir bir Müşteri Kimliği sütunu gösterir. Müşteriler her iki durumda da dahili olarak tanımlanmaya devam eder."
@@ -16981,6 +17059,9 @@ msgstr "Yedekleme işi bu hatayı bildirdi."
msgid "The backward-computed date an operation must finish by to keep its job on time, written to the operation's due date. A stable target for measuring progress — never a constraint on placement."
msgstr "Bir operasyon'un iş emri'sini zamanında tutmak için bitirmesi gereken geriye doğru hesaplanan tarih, operasyon'un son tarih'e yazılır. İlerlemeyi ölçmek için kararlı bir hedef — yerleştirilme üzerinde hiçbir zaman bir kısıtlama değildir."
+msgid "The batch goes to the shop floor. Its jobs are already released."
+msgstr "Parti atölyeye gider. İş emirleri zaten serbest bırakıldı."
+
msgid "The batch runs at its most urgent member's time — the others are pulled early"
msgstr "Parti en acil üyesinin zamanında çalışır — diğerleri öne çekilir"
@@ -17266,6 +17347,9 @@ msgstr "Bir Sevkiyat muhasebeleştirildiğinde tanınan ve Stok kartının Maliy
msgid "The IRS recovery-period class for this asset under MACRS (3, 5, 7, 10, 15, 20, 27.5, 39-year)."
msgstr "Bu varlık için MACRS kapsamında IRS kurtarma süresi sınıfı (3, 5, 7, 10, 15, 20, 27.5, 39 yıl)."
+msgid "The item each job produces — require it to match to merge output lots"
+msgstr "Her iş emrinin ürettiği stok kartı — çıkış lotlarını birleştirmek için eşleşmesi gerekir"
+
msgid "the job hours due that day (a due-date basis, not the day the work runs), with overdue work in Past due."
msgstr "o gün vadesi olan iş saatleri (çalışmanın çalıştığı günü değil, vade tarihine göre), gecikmiş iş Gecikmede."
@@ -17800,6 +17884,11 @@ msgstr "Bu satırlar bu şirket dışındaki verilere bağlantılı, bu nedenle
msgid "this ability"
msgstr "bu yetkinlik"
+#. placeholder {0}: jobIds.length
+#. placeholder {1}: jobIds.join(", ")
+msgid "This also releases {0} jobs ({1}). They become available to the shop floor and drive purchasing and production."
+msgstr "Bu aynı zamanda {0} iş emrini ({1}) serbest bırakır. Bunlar atölye için kullanılabilir hale gelir ve satın alma ve üretimi yönlendirir."
+
msgid "This backup could not be completed."
msgstr "Bu yedekleme tamamlanamadı."
diff --git a/packages/locale/locales/tr/mes.po b/packages/locale/locales/tr/mes.po
index 61b894d690..070dc2a5e4 100644
--- a/packages/locale/locales/tr/mes.po
+++ b/packages/locale/locales/tr/mes.po
@@ -25,14 +25,28 @@ msgstr "{0} Aktif"
msgid "{0} ago"
msgstr "{0} önce"
+#. placeholder {0}: batchFacts.customers.length
+msgid "{0} customers"
+msgstr ""
+
+#. placeholder {0}: unplanned .map( (m) => (m.job as { jobId?: string | null } | null)?.jobId ) .filter(Boolean) .join(", ")
+msgid "{0} has no lot number. Set it on the batch or job in Carbon, then complete."
+msgstr "{0} Lot numarasına sahip değil. Bunu Carbon'da Partide veya İş emrinde ayarla, sonra Tamamla."
+
+#. placeholder {0}: batchFacts.items.length
+msgid "{0} items"
+msgstr ""
+
#. placeholder {0}: (batch.operations ?? []).length
msgid "{0} jobs"
msgstr "{0} iş emri"
+#. placeholder {0}: issuedLines.length
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
#. placeholder {1}: operation.targetQuantity
+#. placeholder {1}: trackedLines.length
msgid "{0} of {1}"
msgstr "{0} adet {1}"
@@ -54,16 +68,28 @@ msgstr "{0} kuyrukta"
msgid "{0} running"
msgstr "{0} çalışıyor"
+#. placeholder {0}: operation.jobReadableId
+#. placeholder {1}: batch.readableId
+msgid "{0} runs in batch {1}"
+msgstr ""
+
#. placeholder {0}: item.quantityScrapped
msgid "{0} Scrapped"
msgstr "{0} Hurdaya Çıkarılmış"
+msgid "{completed} of {quantity}"
+msgstr "{completed} / {quantity}"
+
msgid "{completions} passed unit(s) will be completed."
msgstr "{completions} geçti birim(ler) tamamlanacak."
msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
msgstr "{fails} örnek hata(ları) kaydedildi ve tamamlanmayacak — bunları işlemler menüsünden çözün."
+#. placeholder {0}: step.perMember.length
+msgid "{recorded}/{0} jobs"
+msgstr ""
+
msgid "+{overflow} more"
msgstr "+{overflow} daha fazla"
@@ -88,6 +114,10 @@ msgstr "Hesap Ayarları"
msgid "Acknowledge & finish"
msgstr "Onayla ve bitir"
+#. placeholder {0}: members.length
+msgid "across {0} jobs"
+msgstr "{0} İş emri arasında"
+
msgid "Active"
msgstr "Aktif"
@@ -118,6 +148,13 @@ msgstr "Tümü"
msgid "All clear"
msgstr "Tamamen temiz"
+msgid "All jobs"
+msgstr "Tüm iş emirleri"
+
+#. placeholder {0}: batch.outputLotNumber
+msgid "All output goes to lot <0>{0}</0>"
+msgstr "Tüm çıktı Lot <0>{0}</0>'a gider"
+
msgid "All rework"
msgstr "Tümünü yeniden işle"
@@ -166,6 +203,9 @@ msgstr "kullanılabilir"
msgid "Available"
msgstr "Kullanılabilir"
+msgid "Back to batch"
+msgstr ""
+
msgid "Batch"
msgstr "Parti"
@@ -179,12 +219,21 @@ msgstr "Lot Numarası {0}"
msgid "Batch number is required"
msgstr "Lot numarası zorunludur"
-msgid "Batched jobs"
-msgstr "Toplu iş emirleri"
+msgid "Batch quantity"
+msgstr "Parti miktarı"
+
+msgid "batch total"
+msgstr "parti toplamı"
msgid "Behind target by {daysBehindTarget} day(s)"
msgstr "Hedeften {daysBehindTarget} gün geride"
+#. placeholder {0}: step.minValue
+#. placeholder {1}: step.maxValue
+#. placeholder {2}: step.unitOfMeasureCode ?? ""
+msgid "Between {0} and {1} {2}"
+msgstr ""
+
#. placeholder {0}: column.blockingDispatchReadableId
msgid "Blocked by {0}"
msgstr "Engelli edildi: {0}"
@@ -222,6 +271,9 @@ msgstr "Sohbet"
msgid "Check your email"
msgstr "E-postanızı kontrol edin"
+msgid "Choose a job"
+msgstr ""
+
msgid "Clear"
msgstr "Temizle"
@@ -249,6 +301,9 @@ msgstr "Kapat"
msgid "Collapse features table"
msgstr "Özellikler tablosunu daralt"
+msgid "Collapse panel"
+msgstr "Paneli daralt"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -278,6 +333,9 @@ msgstr "Tamamla"
msgid "Complete All"
msgstr "Tümünü Tamamla"
+msgid "Complete batch"
+msgstr ""
+
msgid "Complete Batch"
msgstr "Partiyi Tamamla"
@@ -377,6 +435,9 @@ msgstr "Görüntüleme"
msgid "Displays"
msgstr "Ekranlar"
+msgid "Done"
+msgstr ""
+
msgid "Down"
msgstr "Düşük"
@@ -409,9 +470,12 @@ msgstr "Çizimi ve özellikleri yeniden boyutlandırmak için sürükleyin"
msgid "Dragging {0} cancelled."
msgstr "Taşıma {0} iptal edildi."
+msgid "Due"
+msgstr ""
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
msgid "Due {0}"
msgstr "Süresi dolacak {0}"
@@ -434,6 +498,9 @@ msgstr "Çoğaltılmış seri numarası"
msgid "Duration"
msgstr "Süre"
+msgid "Each job's output is its own lot — keep each job's parts apart."
+msgstr ""
+
msgid "Edit"
msgstr "Düzenle"
@@ -449,6 +516,9 @@ msgstr "Boş iş merkezleri"
msgid "End Operations"
msgstr "Operasyonları Sonlandır"
+msgid "Enter each job's value, or fill every job at once from the first row. Empty rows are skipped."
+msgstr ""
+
#. placeholder {0}: selectedPerson.name
msgid "Enter PIN for {0}"
msgstr "PIN'i {0} için girin"
@@ -465,12 +535,18 @@ msgstr "Hata"
msgid "Estimated"
msgstr "Tahmini"
+msgid "Every job in the batch follows these steps. Record a step for all of them at once."
+msgstr ""
+
msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
msgstr "Her birim için bir karar verildi: {passes} geçti ve {fails} başarısız oldu. Lot, her birim kendi sonucuna yönlendirilmek üzere kapanır."
msgid "Expand features table"
msgstr "Özellikler tablosunu genişlet"
+msgid "Expand panel"
+msgstr "Paneli genişlet"
+
msgid "Expired"
msgstr "Süresi doldu"
@@ -511,6 +587,10 @@ msgstr "Ölçüm kaydedilemedi"
msgid "Failed to save result"
msgstr "Sonuç kaydedilemedi"
+#. placeholder {0}: file.name
+msgid "Failed to upload {0}"
+msgstr ""
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "Dosyayı yüklemede başarısız oldu: {0}"
@@ -555,6 +635,10 @@ msgstr "Hesabınızı ayarlamayı tamamlayın"
msgid "Finish with material unpicked?"
msgstr "Malzeme seçilmeden bitir?"
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(batchFacts.dueDate) )
+msgid "First due {0}"
+msgstr ""
+
msgid "Forgot to Clock Out?"
msgstr "İş bitişini unutmuş musunuz?"
@@ -567,6 +651,9 @@ msgstr "İşleme geri dön"
msgid "Go to onboarding"
msgstr "Başlangıç adımına git"
+msgid "Hide description"
+msgstr ""
+
msgid "How many were actually picked?"
msgstr "Gerçekte kaç tane alındı?"
@@ -631,6 +718,9 @@ msgstr "Malzeme Çıkart"
msgid "Issue Type"
msgstr "Sorun Türü"
+msgid "Issued"
+msgstr "Verilen"
+
msgid "Issued {issuedQuantity} of {lotLabel}"
msgstr "Çıkış Yapılan {issuedQuantity} / {lotLabel}"
@@ -688,6 +778,9 @@ msgstr "satırlar"
msgid "List view"
msgstr "Liste görünümü"
+msgid "Load list"
+msgstr ""
+
msgid "Loading item details..."
msgstr "Ürün detayları yükleniyor..."
@@ -700,6 +793,9 @@ msgstr "Yerel"
msgid "Location"
msgstr "Konum"
+msgid "Log completed"
+msgstr ""
+
msgid "Log Completed"
msgstr "Tamamlandı Olarak Kaydet"
@@ -727,6 +823,12 @@ msgstr "Giriş Yap"
msgid "Lot"
msgstr "Lot"
+msgid "Lot numbers missing"
+msgstr "Lot numaraları eksik"
+
+msgid "Lot tracked"
+msgstr ""
+
msgid "Machine"
msgstr "Makine"
@@ -763,6 +865,9 @@ msgstr "eşleşir"
msgid "Materials"
msgstr "Malzemeler"
+msgid "Materials issued"
+msgstr "Verilen Malzemeler"
+
msgid "Maximum number of records reached"
msgstr "Maksimum kayıt sayısına ulaşıldı"
@@ -866,6 +971,9 @@ msgstr "Eşleşme yok. Bir tane oluşturmak için yazın."
msgid "No materials"
msgstr "Malzeme yok"
+msgid "No materials on this batch."
+msgstr "Bu Partide Malzeme yok."
+
msgid "No open jobs"
msgstr "Açık iş emirleri yok"
@@ -959,9 +1067,22 @@ msgstr "OEE Etkisi"
msgid "OEM Required"
msgstr "OEM Gerekli"
+#. placeholder {0}: m.operationQuantity ?? 0
+msgid "of {0}"
+msgstr ""
+
msgid "Oldest first"
msgstr "En eski önce"
+msgid "one combined lot · planned"
+msgstr "bir birleştirilmiş Lot · planlandı"
+
+msgid "one per job · planned"
+msgstr "İş emri başına bir · planlandı"
+
+msgid "One pick covers the whole batch — it is shared out to the jobs automatically."
+msgstr ""
+
#. placeholder {0}: batch.quantity
msgid "Only {0} available"
msgstr "Sadece {0} kullanılabilir"
@@ -975,6 +1096,9 @@ msgstr "Açık"
msgid "Open a display on the screen mounted at the work center and leave it running. Each board refreshes on its own."
msgstr "İş merkezine yerleştirilmiş ekranda bir ekran açın ve çalışır durumda bırakın. Her pano kendi kendine yenilenir."
+msgid "Open a job in this batch"
+msgstr ""
+
msgid "Open an NCR for MRB disposition"
msgstr "MRB kararı için NCR aç"
@@ -999,6 +1123,9 @@ msgstr "İsteğe bağlı"
msgid "or"
msgstr "veya"
+msgid "Output lot"
+msgstr "Çıktı Lotu"
+
msgid "Overall result"
msgstr "Genel sonuç"
@@ -1017,6 +1144,9 @@ msgstr "Kısmi"
msgid "Partial Disposition"
msgstr "Kısmi Karar"
+msgid "Passed inspection"
+msgstr ""
+
msgid "Passed Inspection"
msgstr "Muayenede Geçti"
@@ -1029,6 +1159,10 @@ msgstr "Duraklat"
msgid "Pick"
msgstr "Topla"
+#. placeholder {0}: m.required - m.issued
+msgid "Pick {0}"
+msgstr "Toplama {0}"
+
msgid "Pick tracked item"
msgstr "Takip edilen öğeyi seç"
@@ -1098,6 +1232,9 @@ msgstr "Prosedür"
msgid "Process"
msgstr "Süreç"
+msgid "Process parameters"
+msgstr "Proses parametreleri"
+
msgid "Process Parameters"
msgstr "İşlem Parametreleri"
@@ -1140,18 +1277,28 @@ msgstr "Kaydet"
msgid "Record {0}"
msgstr "Kayıt {0}"
+#. placeholder {0}: changed.length
+msgid "Record {0} jobs"
+msgstr ""
+
msgid "Record only"
msgstr "Yalnızca kaydet"
msgid "Record Partial"
msgstr "Kısmi Kaydı"
+msgid "Recorded"
+msgstr ""
+
msgid "Reject"
msgstr "Reddet"
msgid "Reject Lot"
msgstr "Lotu Reddet"
+msgid "Released"
+msgstr ""
+
msgid "Remove"
msgstr "Kaldır"
@@ -1167,6 +1314,9 @@ msgstr "Parçayı kaldır"
msgid "Reopen the subassembly and create a replacement unit"
msgstr "Alt montajı yeniden aç ve bir yedek birim oluştur"
+msgid "Required"
+msgstr "Gerekli"
+
msgid "Result"
msgstr "Sonuç"
@@ -1188,6 +1338,9 @@ msgstr "Çalışıyor"
msgid "Sales Order"
msgstr "Satış Siparişi"
+msgid "Same for every job"
+msgstr ""
+
msgid "Save"
msgstr "Kaydet"
@@ -1307,6 +1460,9 @@ msgstr "Gönder"
msgid "Send to Carbon"
msgstr "Carbon'a Gönder"
+msgid "Separate lots"
+msgstr "Ayrı Lotlar"
+
msgid "Serial"
msgstr "Seri"
@@ -1326,6 +1482,9 @@ msgstr "Seri numaraları"
msgid "Serial Numbers"
msgstr "Seri Numaraları"
+msgid "Serialized"
+msgstr ""
+
msgid "Session locked"
msgstr "Oturum kilitlendi"
@@ -1338,6 +1497,9 @@ msgstr "Çıkış zamanını ayarla"
msgid "Set up in Carbon"
msgstr "Carbon'da ayarla"
+msgid "Set when the batch was planned."
+msgstr "Parti planlandığında ayarlandı."
+
msgid "Setup"
msgstr "Kurulum"
@@ -1350,6 +1512,9 @@ msgstr "Azalt"
msgid "Short pick {itemName}"
msgstr "Kısmi toplama {itemName}"
+msgid "Show description"
+msgstr ""
+
msgid "Show this overlay"
msgstr "Bu katmanı göster"
@@ -1389,6 +1554,10 @@ msgstr "Kullanılan Yedek Parçalar"
msgid "Start"
msgstr "Başlat"
+#. placeholder {0}: workTypeLabels[ eventType.toLowerCase() as keyof typeof workTypeLabels ].toLowerCase()
+msgid "Start {0}"
+msgstr ""
+
msgid "Start or pause the operation"
msgstr "Operasyonu başlat veya duraklat"
@@ -1438,12 +1607,22 @@ msgstr "Etiket"
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "Bu işlem için tamamlanan miktar, gerekli miktar olan {targetQuantity}'dan azdır."
+msgid "The jobs and parts that make up this run."
+msgstr ""
+
+msgid "The jobs make different items — keep each job's parts apart."
+msgstr ""
+
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "Lot Geçti olarak işaretlenecek ve {remaining} kalan birim bu operasyonda tamamlanacak."
msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "Lot yine de işleme tabi tutulacak, ancak en az bir Sorun Türü yapılandırılana kadar bir NCR oluşturulamaz."
+#. placeholder {0}: (batch.operations ?? []).length
+msgid "The timer and completion are shared by all {0} jobs. Steps, materials and files here are this job's own."
+msgstr ""
+
msgid "There are no available or consumed tracked parts for this material."
msgstr "Bu malzeme için hiçbir kullanılabilir veya tüketilmiş izlenmiş parça yoktur."
@@ -1453,6 +1632,9 @@ msgstr "Malzeme listesindeki seri veya parti takipli malzemeler tam olarak veril
msgid "These items still have material to pick. Finishing now marks the list Partial."
msgstr "Bu öğelerin hala seçilecek malzemesi var. Şimdi bitirmek listeyi Kısmi olarak işaretler."
+msgid "This batch has no work instructions."
+msgstr ""
+
msgid "This lot is expired and can't be picked."
msgstr "Bu lot'un süresi doldu ve toplanamaz."
@@ -1468,6 +1650,9 @@ msgstr "Bu birim kalıcı olarak hurdaya çıkarılacak ve yedek bir seri numara
msgid "Thumbnail"
msgstr "Küçük Resim"
+msgid "Tick the jobs this was done for."
+msgstr ""
+
msgid "Time and cost split across jobs proportionally to quantity."
msgstr "Zaman ve maliyet, miktar ile orantılı olarak iş emirleri arasında bölünür."
@@ -1478,6 +1663,12 @@ msgstr "Zaman Girişleri"
msgid "Time Worked: {0}"
msgstr "Çalışma Süresi: {0}"
+msgid "To pick"
+msgstr ""
+
+msgid "To run"
+msgstr ""
+
msgid "Today"
msgstr "Bugün"
@@ -1487,6 +1678,9 @@ msgstr "Kenar çubuğunu aç/kapat"
msgid "Tools"
msgstr "Araçlar"
+msgid "Total"
+msgstr ""
+
msgid "Total Quantity"
msgstr "Toplam Miktar"
@@ -1501,6 +1695,9 @@ msgstr "Toplam: {0}"
msgid "Tracked Entity"
msgstr "İzlenen Varlık"
+msgid "tracked lines"
+msgstr "izlenen Satırlar"
+
msgid "Tracking"
msgstr "Takip"
@@ -1572,6 +1769,12 @@ msgstr "Yükleniyor {0}"
msgid "Use a different account"
msgstr "Farklı bir hesap kullan"
+msgid "Used automatically at completion"
+msgstr ""
+
+msgid "Value"
+msgstr ""
+
msgid "Verify"
msgstr "Doğrula"
@@ -1584,6 +1787,9 @@ msgstr "Hesabınıza giriş yapmak için size bir sihirli bağlantı gönderdik.
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm} nedir?"
+msgid "Whole batch"
+msgstr "Tüm Parti"
+
msgid "WIP"
msgstr "Yarı Mamul"
@@ -1593,6 +1799,9 @@ msgstr "İş Merkezi"
msgid "Work Center Displays"
msgstr "İş Merkezi Ekranları"
+msgid "Work instructions"
+msgstr "İş talimatları"
+
msgid "Yes"
msgstr "Evet"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index c280d2a296..635997c97d 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -111,6 +111,10 @@ msgstr "{0} 已成功删除"
msgid "{0} draft journal entries"
msgstr "{0}个草稿凭证"
+#. placeholder {0}: op.description
+msgid "{0} has no supplier"
+msgstr ""
+
#. placeholder {0}: formatter.format(onHand)
#. placeholder {1}: formatter.format(assembliesInStock)
#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
@@ -141,6 +145,10 @@ msgstr "{0} / {1} 个过账科目已映射"
msgid "{0} of {maxSlots} provider slots used"
msgstr "{0} / {maxSlots} 个提供商插槽已使用"
+#. placeholder {0}: pendingJobs.length
+msgid "{0} of {memberCount} member jobs are not completed yet — their output stays out of stock until each job is completed."
+msgstr "{memberCount}个工单中{0}个尚未完成——其产出将一直缺货,直到每个工单都完成。"
+
#. placeholder {0}: selected.length
msgid "{0} operations · {totalQuantity} parts"
msgstr "{0} 工序 · {totalQuantity} 零件"
@@ -1652,6 +1660,10 @@ msgstr "所有物料"
msgid "All Locations"
msgstr "所有位置"
+#. placeholder {0}: tracked[0]?.itemReadableId ?? ""
+msgid "all make {0}"
+msgstr "全部自制 {0}"
+
msgid "All members of selected groups and selected individuals will be able to approve requests"
msgstr "所选组的所有成员和所选个人都将能够审批请求"
@@ -3550,6 +3562,9 @@ msgstr "检查您的电子邮件"
msgid "Checking Stripe for this customer…"
msgstr "正在为此客户检查Stripe…"
+msgid "Checking the batch's jobs..."
+msgstr "正在检查生产批次的工单..."
+
msgid "Checkpoint ·"
msgstr "检查点 ·"
@@ -3574,6 +3589,10 @@ msgstr "选择左侧的行以查看其库存可能来自何处。"
msgid "Choose a serial number"
msgstr "选择序列号"
+#. placeholder {0}: op.description
+msgid "choose a supplier for {0} on the job"
+msgstr ""
+
msgid "Choose another file"
msgstr "选择另一个文件"
@@ -3736,6 +3755,9 @@ msgstr "列"
msgid "Combine filters"
msgstr "合并筛选"
+msgid "Combine output into one lot"
+msgstr "将输出合并为一个批次"
+
msgid "Coming soon"
msgstr "即将推出"
@@ -4526,6 +4548,9 @@ msgstr "创建 {0} 个值"
msgid "Create & Release"
msgstr "创建并下达"
+msgid "Create & release batch"
+msgstr "创建并下达生产批次"
+
msgid "Create & Snapshot"
msgstr "创建并快照"
@@ -4598,6 +4623,9 @@ msgstr "创建工单"
msgid "Create Kanban"
msgstr "创建看板"
+msgid "Create New"
+msgstr "新建"
+
msgid "Create new rule"
msgstr "创建新规则"
@@ -6269,6 +6297,12 @@ msgstr "例如 Zebra 2x1"
msgid "Each cell is the people assigned against the people the day's work needs."
msgstr "每个单元格显示分配的人员与该天工作所需的人员对比。"
+msgid "Each job keeps its own lot. The shop floor can't change these."
+msgstr "每个工单保留自己的批次。车间无法更改这些。"
+
+msgid "Each job needs its own lot number — or combine them into one lot."
+msgstr "每个工单需要自己的批次号 — 或将它们合并为一个批次。"
+
msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."
msgstr "每一行都是从该公司的数据链接到它不拥有的一行。包含这些行的备份永远无法恢复。"
@@ -6281,6 +6315,9 @@ msgstr "每个工序的未使用原材料在工序完成后立即退回。"
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "每个物理件获得其自己的追踪实体和唯一编号——一个实体,一个件。"
+msgid "Each supplier's outside operations from every job go on one new purchase order, or on an existing draft you choose."
+msgstr "每个供应商的外协工序从每个工单转至一份新采购订单,或转至您选择的现有草稿。"
+
msgid "Each, lb, ft…"
msgstr "每个、磅、英尺…"
@@ -7027,6 +7064,9 @@ msgstr "其他所有内容"
msgid "Everything else covers people, imports, integrations and the API — anything that is not one of your workflows."
msgstr "其他所有内容涵盖人员、导入、集成和 API — 任何不属于您的工作流的内容。"
+msgid "Everything this run makes lands in one lot. The shop floor can't change it."
+msgstr "这次运行生产的所有产品都进入一个批次。车间无法更改它。"
+
msgid "Exceeds {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB total — remove some attachments to send."
msgstr "超过 {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB 总限制 — 删除一些附件进行发送。"
@@ -7804,6 +7844,9 @@ msgstr "缩放到适应"
msgid "Fix the problems with this workflow before testing it"
msgstr "在测试之前修复此工作流的问题"
+msgid "Fix these jobs before releasing"
+msgstr "在下达前修复这些工单"
+
msgid "Fixed"
msgstr "固定"
@@ -9610,7 +9653,7 @@ msgid "Lines"
msgstr "行"
msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."
-msgstr "采购订单收货已过账后,此处显示行项目(仅限尚未在其他供应商退货上授权的数量)。如需盲目退货,请使用\"添加行项目\"。"
+msgstr "采购订单收货已过账后,行将显示在此处,并且仅限于尚未在另一个供应商退货中授权的数量。使用添加行项目进行盲退货。"
msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."
msgstr "销售订单发货已过账后,行将显示在此处,仅适用于尚未在另一个RMA中授权的数量。对于盲目退货,请使用添加行项目。"
@@ -9806,6 +9849,9 @@ msgstr "丢单"
msgid "Lot"
msgstr "批次"
+msgid "Lot number"
+msgstr "批次号"
+
msgid "Lot size"
msgstr "批量大小"
@@ -9986,6 +10032,9 @@ msgstr "制造商零件号"
msgid "Manufacturing"
msgstr "制造"
+msgid "manufacturing is blocked"
+msgstr "生产受阻"
+
msgid "Map accounts"
msgstr "映射科目"
@@ -10275,6 +10324,13 @@ msgstr "备忘录 ID"
msgid "Merchant"
msgstr "商家"
+#. placeholder {0}: getItemReadableId(items, itemId) ?? itemId
+msgid "Merge {0} lots"
+msgstr ""
+
+msgid "Merge output lots"
+msgstr "合并输出批次"
+
msgid "MES"
msgstr "MES"
@@ -11264,6 +11320,10 @@ msgstr "没有未结销售订单行"
msgid "No operations found."
msgstr "未找到工序。"
+#. placeholder {0}: job.missingAssemblies .map((m) => m.description) .join(", ")
+msgid "no operations on {0}"
+msgstr "{0}上没有工序"
+
msgid "No operations require picking at this location"
msgstr "此地点没有工序需要拣货"
@@ -13014,6 +13074,12 @@ msgstr "流程"
msgid "Procurement status — needs ordering, planned, on order, or received. The same indicator shown in the BoM tree."
msgstr "采购状态——需要订购、已计划、已订购或已收货。与 BoM 树中显示的指示器相同。"
+msgid "produced item"
+msgstr "生产物料"
+
+msgid "Produced item"
+msgstr "生产物料"
+
msgid "Product issues during hypercare"
msgstr "超级护理期间的产品问题"
@@ -13923,6 +13989,11 @@ msgstr "下达{0}个生产批次"
msgid "Release Batch"
msgstr "下达生产批次"
+#. placeholder {0}: batch.readableId
+#. placeholder {0}: releaseTarget.readableId
+msgid "Release batch {0}"
+msgstr "下达生产批次{0}"
+
msgid "Release change notice"
msgstr "下达变更通知"
@@ -13951,6 +14022,9 @@ msgstr "已下达修订版"
msgid "Released revision is locked"
msgstr "已下达修订版已锁定"
+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
+msgstr "下达生产批次会下达其工单,每个工单都必须为车间做好准备。"
+
msgid "Remaining"
msgstr "剩余"
@@ -15324,7 +15398,7 @@ msgid "Select operations"
msgstr "选择工序"
msgid "Select posted receipt lines from this supplier to return."
-msgstr "选择来自此供应商的已过账收货行以退货。"
+msgstr "选择从此供应商的已过账收货行以退货。"
msgid "Select posted shipment lines to this customer to return."
msgstr "从该客户的已过账发货行中选择要退货的"
@@ -15523,7 +15597,7 @@ msgid "Session locked"
msgstr "会话已锁定"
msgid "Set a customer on this return to add from a shipment."
-msgstr "在此退货上设置客户以从发货添加。"
+msgstr "在此退货中设置客户以从发货添加。"
msgid "Set a supplier on this return to add from a receipt."
msgstr "为此退货指定供应商以从其收货中添加"
@@ -15822,6 +15896,10 @@ msgstr "快捷键"
msgid "Show"
msgstr "显示"
+#. placeholder {0}: overflow.length
+msgid "Show {0} more"
+msgstr ""
+
msgid "Show a readable Customer ID column on the customer list, customer forms, and dropdowns. Customers are still identified internally either way."
msgstr "在客户列表、客户表单和下拉菜单上显示可读的客户ID列。无论哪种方式,客户在内部仍然可以被识别。"
@@ -15829,7 +15907,7 @@ msgid "Show a readable Supplier ID column on the supplier list, supplier forms,
msgstr "在供应商列表、供应商表单和下拉菜单上显示可读的供应商 ID 列。无论哪种方式,供应商在内部仍然可以被识别。"
msgid "Show available batch numbers"
-msgstr "显示可用批次号"
+msgstr "显示可用的生产批次号"
msgid "Show available tracking numbers"
msgstr "显示可用的跟踪号码"
@@ -16981,6 +17059,9 @@ msgstr "备份工作报告了此错误。"
msgid "The backward-computed date an operation must finish by to keep its job on time, written to the operation's due date. A stable target for measuring progress — never a constraint on placement."
msgstr "为保持其工单按时完成,工序必须完成的反向计算日期,写入工序的到期日。测量进度的稳定目标 — 永远不是放置约束。"
+msgid "The batch goes to the shop floor. Its jobs are already released."
+msgstr "生产批次送往车间。其工单已下达。"
+
msgid "The batch runs at its most urgent member's time — the others are pulled early"
msgstr "批次按最紧急成员的时间运行——其余成员将被提前"
@@ -17266,6 +17347,9 @@ msgstr "发货过账时确认的库存管理成本,按物料的成本核算方
msgid "The IRS recovery-period class for this asset under MACRS (3, 5, 7, 10, 15, 20, 27.5, 39-year)."
msgstr "根据MACRS,该资产的国税局回收期类别(3、5、7、10、15、20、27.5、39年)。"
+msgid "The item each job produces — require it to match to merge output lots"
+msgstr "每个工单生产的物料 — 要求其匹配以合并输出批次"
+
msgid "the job hours due that day (a due-date basis, not the day the work runs), with overdue work in Past due."
msgstr "该天到期的任务小时数(以截止日期为基础,而不是工作运行的日期),逾期工作在逾期中。"
@@ -17800,6 +17884,11 @@ msgstr "这些行链接到公司外的数据,因此无法恢复它们。其他
msgid "this ability"
msgstr "此能力"
+#. placeholder {0}: jobIds.length
+#. placeholder {1}: jobIds.join(", ")
+msgid "This also releases {0} jobs ({1}). They become available to the shop floor and drive purchasing and production."
+msgstr "这也下达了{0}个工单({1})。它们对车间可用,并驱动采购和生产。"
+
msgid "This backup could not be completed."
msgstr "无法完成此备份。"
diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.po
index e24b6e66f6..4e471b8feb 100644
--- a/packages/locale/locales/zh/mes.po
+++ b/packages/locale/locales/zh/mes.po
@@ -25,14 +25,28 @@ msgstr "{0} 启用"
msgid "{0} ago"
msgstr "{0} 前"
+#. placeholder {0}: batchFacts.customers.length
+msgid "{0} customers"
+msgstr ""
+
+#. placeholder {0}: unplanned .map( (m) => (m.job as { jobId?: string | null } | null)?.jobId ) .filter(Boolean) .join(", ")
+msgid "{0} has no lot number. Set it on the batch or job in Carbon, then complete."
+msgstr "{0}没有批次号。在Carbon中的生产批次或工单上设置,然后完成。"
+
+#. placeholder {0}: batchFacts.items.length
+msgid "{0} items"
+msgstr ""
+
#. placeholder {0}: (batch.operations ?? []).length
msgid "{0} jobs"
msgstr "{0} 个工作"
+#. placeholder {0}: issuedLines.length
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
#. placeholder {1}: operation.targetQuantity
+#. placeholder {1}: trackedLines.length
msgid "{0} of {1}"
msgstr "{0} / {1}"
@@ -54,16 +68,28 @@ msgstr "{0} 排队中"
msgid "{0} running"
msgstr "运行中 {0} 个"
+#. placeholder {0}: operation.jobReadableId
+#. placeholder {1}: batch.readableId
+msgid "{0} runs in batch {1}"
+msgstr ""
+
#. placeholder {0}: item.quantityScrapped
msgid "{0} Scrapped"
msgstr "{0} 已报废"
+msgid "{completed} of {quantity}"
+msgstr "{completed} 的 {quantity}"
+
msgid "{completions} passed unit(s) will be completed."
msgstr "{completions} 个已通过的件将被完成。"
msgid "{fails} sampled failure(s) are recorded and will NOT be completed — resolve them from the actions menu."
msgstr "{fails} 个抽样不合格已被记录,将不会被完成 — 从操作菜单解决它们。"
+#. placeholder {0}: step.perMember.length
+msgid "{recorded}/{0} jobs"
+msgstr ""
+
msgid "+{overflow} more"
msgstr "还有 +{overflow} 个"
@@ -88,6 +114,10 @@ msgstr "账户设置"
msgid "Acknowledge & finish"
msgstr "确认并完成"
+#. placeholder {0}: members.length
+msgid "across {0} jobs"
+msgstr "跨越 {0} 工单"
+
msgid "Active"
msgstr "启用"
@@ -118,6 +148,13 @@ msgstr "全部"
msgid "All clear"
msgstr "一切正常"
+msgid "All jobs"
+msgstr "所有工单"
+
+#. placeholder {0}: batch.outputLotNumber
+msgid "All output goes to lot <0>{0}</0>"
+msgstr "所有输出都进入批次 <0>{0}</0>"
+
msgid "All rework"
msgstr "全部返工"
@@ -166,6 +203,9 @@ msgstr "可用"
msgid "Available"
msgstr "可用"
+msgid "Back to batch"
+msgstr ""
+
msgid "Batch"
msgstr "批次"
@@ -179,12 +219,21 @@ msgstr "批次号 {0}"
msgid "Batch number is required"
msgstr "批次号为必填项"
-msgid "Batched jobs"
-msgstr "批量工作"
+msgid "Batch quantity"
+msgstr "批次数量"
+
+msgid "batch total"
+msgstr "生产批次总计"
msgid "Behind target by {daysBehindTarget} day(s)"
msgstr "落后于目标 {daysBehindTarget} 天"
+#. placeholder {0}: step.minValue
+#. placeholder {1}: step.maxValue
+#. placeholder {2}: step.unitOfMeasureCode ?? ""
+msgid "Between {0} and {1} {2}"
+msgstr ""
+
#. placeholder {0}: column.blockingDispatchReadableId
msgid "Blocked by {0}"
msgstr "被 {0} 阻塞"
@@ -222,6 +271,9 @@ msgstr "聊天"
msgid "Check your email"
msgstr "请查收邮件"
+msgid "Choose a job"
+msgstr ""
+
msgid "Clear"
msgstr "清除"
@@ -249,6 +301,9 @@ msgstr "关闭"
msgid "Collapse features table"
msgstr "折叠功能表"
+msgid "Collapse panel"
+msgstr "折叠面板"
+
#. placeholder {0}: active.data.current.column.title
#. placeholder {1}: overColumnPosition + 1
#. placeholder {2}: columnOrder.length
@@ -278,6 +333,9 @@ msgstr "完成"
msgid "Complete All"
msgstr "全部完成"
+msgid "Complete batch"
+msgstr ""
+
msgid "Complete Batch"
msgstr "完成批次"
@@ -377,6 +435,9 @@ msgstr "显示"
msgid "Displays"
msgstr "显示屏"
+msgid "Done"
+msgstr ""
+
msgid "Down"
msgstr "停机"
@@ -409,9 +470,12 @@ msgstr "拖动以调整绘图和功能的大小"
msgid "Dragging {0} cancelled."
msgstr "拖拽 {0} 已取消。"
+msgid "Due"
+msgstr ""
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
msgid "Due {0}"
msgstr "截止 {0}"
@@ -434,6 +498,9 @@ msgstr "序列号重复"
msgid "Duration"
msgstr "时长"
+msgid "Each job's output is its own lot — keep each job's parts apart."
+msgstr ""
+
msgid "Edit"
msgstr "编辑"
@@ -449,6 +516,9 @@ msgstr "空的工作中心"
msgid "End Operations"
msgstr "结束工序"
+msgid "Enter each job's value, or fill every job at once from the first row. Empty rows are skipped."
+msgstr ""
+
#. placeholder {0}: selectedPerson.name
msgid "Enter PIN for {0}"
msgstr "输入 {0} 的 PIN 码"
@@ -465,12 +535,18 @@ msgstr "错误"
msgid "Estimated"
msgstr "估计"
+msgid "Every job in the batch follows these steps. Record a step for all of them at once."
+msgstr ""
+
msgid "Every unit has a verdict: {passes} passed and {fails} failed. The lot closes with each unit routed to its own outcome."
msgstr "每件都有一个结果:{passes} 个已通过,{fails} 个不合格。批次随着每件分配到其结果而关闭。"
msgid "Expand features table"
msgstr "展开功能表"
+msgid "Expand panel"
+msgstr "展开面板"
+
msgid "Expired"
msgstr "已过期"
@@ -511,6 +587,10 @@ msgstr "无法保存测量"
msgid "Failed to save result"
msgstr "无法保存结果"
+#. placeholder {0}: file.name
+msgid "Failed to upload {0}"
+msgstr ""
+
#. placeholder {0}: fileUpload.name
msgid "Failed to upload file: {0}"
msgstr "文件上传失败:{0}"
@@ -555,6 +635,10 @@ msgstr "完成账户设置"
msgid "Finish with material unpicked?"
msgstr "物料未拣货的情况下要完成吗?"
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(batchFacts.dueDate) )
+msgid "First due {0}"
+msgstr ""
+
msgid "Forgot to Clock Out?"
msgstr "忘记收工了吗?"
@@ -567,6 +651,9 @@ msgstr "返回操作"
msgid "Go to onboarding"
msgstr "前往入门"
+msgid "Hide description"
+msgstr ""
+
msgid "How many were actually picked?"
msgstr "实际拣了多少?"
@@ -631,6 +718,9 @@ msgstr "领料"
msgid "Issue Type"
msgstr "问题类型"
+msgid "Issued"
+msgstr "已发出"
+
msgid "Issued {issuedQuantity} of {lotLabel}"
msgstr "已发放 {issuedQuantity} 个 {lotLabel}"
@@ -688,6 +778,9 @@ msgstr "行"
msgid "List view"
msgstr "列表视图"
+msgid "Load list"
+msgstr ""
+
msgid "Loading item details..."
msgstr "正在加载物料详情..."
@@ -700,6 +793,9 @@ msgstr "本地"
msgid "Location"
msgstr "位置"
+msgid "Log completed"
+msgstr ""
+
msgid "Log Completed"
msgstr "记录完成数量"
@@ -727,6 +823,12 @@ msgstr "登录"
msgid "Lot"
msgstr "批次"
+msgid "Lot numbers missing"
+msgstr "缺少批次号"
+
+msgid "Lot tracked"
+msgstr ""
+
msgid "Machine"
msgstr "机器"
@@ -763,6 +865,9 @@ msgstr "匹配"
msgid "Materials"
msgstr "原材料"
+msgid "Materials issued"
+msgstr "已发出原材料"
+
msgid "Maximum number of records reached"
msgstr "已达到最大记录数"
@@ -866,6 +971,9 @@ msgstr "没有匹配项。输入以创建一个。"
msgid "No materials"
msgstr "没有原材料"
+msgid "No materials on this batch."
+msgstr "此生产批次上没有物料。"
+
msgid "No open jobs"
msgstr "没有未结的工单"
@@ -959,9 +1067,22 @@ msgstr "OEE 影响"
msgid "OEM Required"
msgstr "需要 OEM"
+#. placeholder {0}: m.operationQuantity ?? 0
+msgid "of {0}"
+msgstr ""
+
msgid "Oldest first"
msgstr "最早优先"
+msgid "one combined lot · planned"
+msgstr "一个组合批次 · 已计划"
+
+msgid "one per job · planned"
+msgstr "每个工单一个 · 已计划"
+
+msgid "One pick covers the whole batch — it is shared out to the jobs automatically."
+msgstr ""
+
#. placeholder {0}: batch.quantity
msgid "Only {0} available"
msgstr "仅 {0} 可用"
@@ -975,6 +1096,9 @@ msgstr "未结"
msgid "Open a display on the screen mounted at the work center and leave it running. Each board refreshes on its own."
msgstr "在安装于工作中心的屏幕上打开显示屏并保持其运行。每个看板自动刷新。"
+msgid "Open a job in this batch"
+msgstr ""
+
msgid "Open an NCR for MRB disposition"
msgstr "为MRB处置打开NCR"
@@ -999,6 +1123,9 @@ msgstr "可选"
msgid "or"
msgstr "或"
+msgid "Output lot"
+msgstr "输出批次"
+
msgid "Overall result"
msgstr "总体结果"
@@ -1017,6 +1144,9 @@ msgstr "部分"
msgid "Partial Disposition"
msgstr "部分处置"
+msgid "Passed inspection"
+msgstr ""
+
msgid "Passed Inspection"
msgstr "已通过检验"
@@ -1029,6 +1159,10 @@ msgstr "暂停"
msgid "Pick"
msgstr "拣货"
+#. placeholder {0}: m.required - m.issued
+msgid "Pick {0}"
+msgstr "拣货 {0}"
+
msgid "Pick tracked item"
msgstr "拣货追踪物料"
@@ -1098,6 +1232,9 @@ msgstr "程序文件"
msgid "Process"
msgstr "工艺"
+msgid "Process parameters"
+msgstr "工艺参数"
+
msgid "Process Parameters"
msgstr "工艺参数"
@@ -1140,18 +1277,28 @@ msgstr "记录"
msgid "Record {0}"
msgstr "记录 {0}"
+#. placeholder {0}: changed.length
+msgid "Record {0} jobs"
+msgstr ""
+
msgid "Record only"
msgstr "仅记录"
msgid "Record Partial"
msgstr "记录部分"
+msgid "Recorded"
+msgstr ""
+
msgid "Reject"
msgstr "拒绝"
msgid "Reject Lot"
msgstr "拒绝批次"
+msgid "Released"
+msgstr ""
+
msgid "Remove"
msgstr "移除"
@@ -1167,6 +1314,9 @@ msgstr "移除零件"
msgid "Reopen the subassembly and create a replacement unit"
msgstr "重新打开子装配件并创建替代件"
+msgid "Required"
+msgstr "必填"
+
msgid "Result"
msgstr "结果"
@@ -1188,6 +1338,9 @@ msgstr "运行中"
msgid "Sales Order"
msgstr "销售订单"
+msgid "Same for every job"
+msgstr ""
+
msgid "Save"
msgstr "保存"
@@ -1307,6 +1460,9 @@ msgstr "发送"
msgid "Send to Carbon"
msgstr "发送至 Carbon"
+msgid "Separate lots"
+msgstr "单独批次"
+
msgid "Serial"
msgstr "序列号"
@@ -1326,6 +1482,9 @@ msgstr "序列号"
msgid "Serial Numbers"
msgstr "序列号"
+msgid "Serialized"
+msgstr ""
+
msgid "Session locked"
msgstr "会话已锁定"
@@ -1338,6 +1497,9 @@ msgstr "设置下班打卡时间"
msgid "Set up in Carbon"
msgstr "在 Carbon 中设置"
+msgid "Set when the batch was planned."
+msgstr "在规划生产批次时设置。"
+
msgid "Setup"
msgstr "换型"
@@ -1350,6 +1512,9 @@ msgstr "缺货"
msgid "Short pick {itemName}"
msgstr "短缺拣货 {itemName}"
+msgid "Show description"
+msgstr ""
+
msgid "Show this overlay"
msgstr "显示此覆盖层"
@@ -1389,6 +1554,10 @@ msgstr "已使用备件"
msgid "Start"
msgstr "开始"
+#. placeholder {0}: workTypeLabels[ eventType.toLowerCase() as keyof typeof workTypeLabels ].toLowerCase()
+msgid "Start {0}"
+msgstr ""
+
msgid "Start or pause the operation"
msgstr "开始或暂停工序"
@@ -1438,12 +1607,22 @@ msgstr "标签"
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "此工序的完成数量小于所需数量 {targetQuantity}。"
+msgid "The jobs and parts that make up this run."
+msgstr ""
+
+msgid "The jobs make different items — keep each job's parts apart."
+msgstr ""
+
msgid "The lot will be marked Passed and {remaining} remaining unit(s) will be completed at this operation."
msgstr "批次将标记为已通过,{remaining} 个剩余件将在此工序完成。"
msgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."
msgstr "该批次仍将进行处置,但在至少配置一个问题类型之前,无法创建NCR。"
+#. placeholder {0}: (batch.operations ?? []).length
+msgid "The timer and completion are shared by all {0} jobs. Steps, materials and files here are this job's own."
+msgstr ""
+
msgid "There are no available or consumed tracked parts for this material."
msgstr "此原材料没有可用或已消耗的受追踪零件。"
@@ -1453,6 +1632,9 @@ msgstr "物料清单中有序列号或生产批次追踪的物料尚未完全领
msgid "These items still have material to pick. Finishing now marks the list Partial."
msgstr "这些物料仍有原材料需要拣货。现在完成将标记列表为部分。"
+msgid "This batch has no work instructions."
+msgstr ""
+
msgid "This lot is expired and can't be picked."
msgstr "此批次已过期,无法拣货。"
@@ -1468,6 +1650,9 @@ msgstr "此单元将被永久报废,并将创建替换序列号。"
msgid "Thumbnail"
msgstr "缩略图"
+msgid "Tick the jobs this was done for."
+msgstr ""
+
msgid "Time and cost split across jobs proportionally to quantity."
msgstr "时间和成本按数量比例分配到各个工作中。"
@@ -1478,6 +1663,12 @@ msgstr "工时记录"
msgid "Time Worked: {0}"
msgstr "工作时间:{0}"
+msgid "To pick"
+msgstr ""
+
+msgid "To run"
+msgstr ""
+
msgid "Today"
msgstr "今天"
@@ -1487,6 +1678,9 @@ msgstr "切换侧栏"
msgid "Tools"
msgstr "工具"
+msgid "Total"
+msgstr ""
+
msgid "Total Quantity"
msgstr "总数量"
@@ -1501,6 +1695,9 @@ msgstr "总计:{0}"
msgid "Tracked Entity"
msgstr "追踪实体"
+msgid "tracked lines"
+msgstr "已跟踪行"
+
msgid "Tracking"
msgstr "追踪"
@@ -1572,6 +1769,12 @@ msgstr "正在上传 {0}"
msgid "Use a different account"
msgstr "使用不同的帐户"
+msgid "Used automatically at completion"
+msgstr ""
+
+msgid "Value"
+msgstr ""
+
msgid "Verify"
msgstr "验证"
@@ -1584,6 +1787,9 @@ msgstr "我们已向您发送了登录链接,请查收。"
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm}是什么?"
+msgid "Whole batch"
+msgstr "整个生产批次"
+
msgid "WIP"
msgstr "在制品"
@@ -1593,6 +1799,9 @@ msgstr "工作中心"
msgid "Work Center Displays"
msgstr "工作中心显示屏"
+msgid "Work instructions"
+msgstr "作业指导书"
+
msgid "Yes"
msgstr "是"
diff --git a/packages/react/src/CodeBlock.tsx b/packages/react/src/CodeBlock.tsx
index 36f206c5ae..24a741870f 100644
--- a/packages/react/src/CodeBlock.tsx
+++ b/packages/react/src/CodeBlock.tsx
@@ -1,87 +1,29 @@
-import type { ShikiTransformer } from "@shikijs/types";
import type { PropsWithChildren } from "react";
-import { useEffect, useState } from "react";
-import ShikiHighlighter, {
- createHighlighterCore,
- createJavaScriptRegexEngine
-} from "react-shiki/core";
-import { Button } from "./Button";
+import { lazy, Suspense } from "react";
-// ─── Highlighter Setup ───────────────────────────────────────────────────────
+// Lazy so react-shiki loads only where a code block renders. On import it
+// injects an unlayered `.relative { position: relative }` stylesheet, which
+// beats Tailwind's layered utilities and silently cancels every responsive
+// `relative lg:absolute` pairing on the page — and the highlighter itself is
+// created with a top-level await on import.
+const CodeBlockHighlighted = lazy(() => import("./CodeBlockHighlighted"));
-const highlighter = await createHighlighterCore({
- themes: [import("@shikijs/themes/github-dark-default")],
- langs: [
- import("@shikijs/langs/bash"),
- import("@shikijs/langs/javascript"),
- import("@shikijs/langs/tsx")
- ],
- engine: createJavaScriptRegexEngine()
-});
-
-const removeItalics: ShikiTransformer = {
- name: "remove-italics",
- span(node) {
- const style = node.properties?.style;
- if (typeof style === "string" && style.includes("font-style")) {
- node.properties.style = style.replace(/font-style:\s*italic;?/g, "");
- }
- }
-};
-
-// ─── Component ───────────────────────────────────────────────────────────────
-
-interface CodeBlockProps {
+export interface CodeBlockProps {
parentClassName?: string;
className?: string;
showCopy?: boolean;
}
-const CodeBlock = ({
- children,
- parentClassName,
- className: languageClassName,
- showCopy = true
-}: PropsWithChildren<CodeBlockProps>) => {
- const [showCopied, setShowCopied] = useState(false);
-
- useEffect(() => {
- if (!showCopied) return;
- const timer = setTimeout(() => setShowCopied(false), 2000);
- return () => clearTimeout(timer);
- }, [showCopied]);
-
- const language = languageClassName?.replace(/language-/, "") || "typescript";
- const code = (children as string)?.trim() ?? "";
-
- const handleCopyCode = () => {
- window.navigator.clipboard.writeText(code);
- setShowCopied(true);
- };
-
- return (
- <div className={`Code codeBlockWrapper group ${parentClassName ?? ""}`}>
- <ShikiHighlighter
- highlighter={highlighter}
- language={language}
- theme={"github-dark-default"}
- showLanguage={false}
- addDefaultStyles={true}
- className="codeBlock"
- transformers={[removeItalics]}
- >
- {code}
- </ShikiHighlighter>
-
- {showCopy && (
- <div className="invisible absolute right-0 top-0 opacity-0 transition-opacity group-hover:visible group-hover:opacity-100">
- <Button size="sm" onClick={handleCopyCode}>
- {showCopied ? "Copied" : "Copy"}
- </Button>
- </div>
- )}
- </div>
- );
-};
+const CodeBlock = (props: PropsWithChildren<CodeBlockProps>) => (
+ <Suspense
+ fallback={
+ <pre className={props.parentClassName}>
+ {(props.children as string)?.trim()}
+ </pre>
+ }
+ >
+ <CodeBlockHighlighted {...props} />
+ </Suspense>
+);
export { CodeBlock };
diff --git a/packages/react/src/CodeBlockHighlighted.tsx b/packages/react/src/CodeBlockHighlighted.tsx
new file mode 100644
index 0000000000..6ebbf9d3bc
--- /dev/null
+++ b/packages/react/src/CodeBlockHighlighted.tsx
@@ -0,0 +1,82 @@
+import type { ShikiTransformer } from "@shikijs/types";
+import type { PropsWithChildren } from "react";
+import { useEffect, useState } from "react";
+import ShikiHighlighter, {
+ createHighlighterCore,
+ createJavaScriptRegexEngine
+} from "react-shiki/core";
+import { Button } from "./Button";
+import type { CodeBlockProps } from "./CodeBlock";
+
+// ─── Highlighter Setup ───────────────────────────────────────────────────────
+
+const highlighter = await createHighlighterCore({
+ themes: [import("@shikijs/themes/github-dark-default")],
+ langs: [
+ import("@shikijs/langs/bash"),
+ import("@shikijs/langs/javascript"),
+ import("@shikijs/langs/tsx")
+ ],
+ engine: createJavaScriptRegexEngine()
+});
+
+const removeItalics: ShikiTransformer = {
+ name: "remove-italics",
+ span(node) {
+ const style = node.properties?.style;
+ if (typeof style === "string" && style.includes("font-style")) {
+ node.properties.style = style.replace(/font-style:\s*italic;?/g, "");
+ }
+ }
+};
+
+// ─── Component ───────────────────────────────────────────────────────────────
+
+const CodeBlockHighlighted = ({
+ children,
+ parentClassName,
+ className: languageClassName,
+ showCopy = true
+}: PropsWithChildren<CodeBlockProps>) => {
+ const [showCopied, setShowCopied] = useState(false);
+
+ useEffect(() => {
+ if (!showCopied) return;
+ const timer = setTimeout(() => setShowCopied(false), 2000);
+ return () => clearTimeout(timer);
+ }, [showCopied]);
+
+ const language = languageClassName?.replace(/language-/, "") || "typescript";
+ const code = (children as string)?.trim() ?? "";
+
+ const handleCopyCode = () => {
+ window.navigator.clipboard.writeText(code);
+ setShowCopied(true);
+ };
+
+ return (
+ <div className={`Code codeBlockWrapper group ${parentClassName ?? ""}`}>
+ <ShikiHighlighter
+ highlighter={highlighter}
+ language={language}
+ theme={"github-dark-default"}
+ showLanguage={false}
+ addDefaultStyles={true}
+ className="codeBlock"
+ transformers={[removeItalics]}
+ >
+ {code}
+ </ShikiHighlighter>
+
+ {showCopy && (
+ <div className="invisible absolute right-0 top-0 opacity-0 transition-opacity group-hover:visible group-hover:opacity-100">
+ <Button size="sm" onClick={handleCopyCode}>
+ {showCopied ? "Copied" : "Copy"}
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default CodeBlockHighlighted;
diff --git a/packages/utils/src/batch-compatibility.test.ts b/packages/utils/src/batch-compatibility.test.ts
index d42abe931f..ae6329dae5 100644
--- a/packages/utils/src/batch-compatibility.test.ts
+++ b/packages/utils/src/batch-compatibility.test.ts
@@ -17,7 +17,8 @@ describe("resolveBatchRules", () => {
grade: "guide",
dimension: "guide",
form: "ignore",
- finish: "ignore"
+ finish: "ignore",
+ producedItem: "ignore"
});
});
@@ -33,7 +34,8 @@ describe("resolveBatchRules", () => {
grade: "guide",
dimension: "guide",
form: "ignore",
- finish: "must"
+ finish: "must",
+ producedItem: "ignore"
});
});
@@ -122,6 +124,21 @@ describe("mustViolations", () => {
expect(mustViolations(guideRules, members)).toEqual([]);
});
+ it("producedItem must refuses members producing different items", () => {
+ const produced = resolveBatchRules({ producedItem: "must" });
+ const members: MemberValueSets[] = [
+ { producedItem: ["SALAD-01"] },
+ { producedItem: ["SALAD-02"] }
+ ];
+ expect(mustViolations(produced, members)).toEqual(["producedItem"]);
+ expect(
+ mustViolations(produced, [
+ { producedItem: ["SALAD-01"] },
+ { producedItem: ["SALAD-01"] }
+ ])
+ ).toEqual([]);
+ });
+
it("reports multiple violated must-dimensions together", () => {
const multi = resolveBatchRules({ finish: "must", grade: "must" });
const members: MemberValueSets[] = [
diff --git a/packages/utils/src/batch-pick-split.test.ts b/packages/utils/src/batch-pick-split.test.ts
new file mode 100644
index 0000000000..4084d805a3
--- /dev/null
+++ b/packages/utils/src/batch-pick-split.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from "vitest";
+import { splitPickAcrossMembers } from "./batch-pick-split";
+
+const sum = (shares: { quantity: number }[]) =>
+ shares.reduce((acc, s) => acc + s.quantity, 0);
+
+describe("splitPickAcrossMembers", () => {
+ it("splits pro-rata by remaining requirement, summing exactly", () => {
+ const shares = splitPickAcrossMembers(
+ [
+ { jobOperationId: "a", remaining: 4000 },
+ { jobOperationId: "b", remaining: 2500 }
+ ],
+ 6500
+ );
+ expect(shares).toEqual([
+ { jobOperationId: "a", quantity: 4000 },
+ { jobOperationId: "b", quantity: 2500 }
+ ]);
+ });
+
+ it("a two-lot pick sequence converges on exact per-member totals", () => {
+ // Pick 1: 4,000 of the 6,500 total → pro-rata across both members.
+ const first = splitPickAcrossMembers(
+ [
+ { jobOperationId: "a", remaining: 4000 },
+ { jobOperationId: "b", remaining: 2500 }
+ ],
+ 4000
+ );
+ expect(sum(first)).toBe(4000);
+ // Pick 2: the rest, weighted by what each member still needs.
+ const remainingA = 4000 - first[0]!.quantity;
+ const remainingB = 2500 - first[1]!.quantity;
+ const second = splitPickAcrossMembers(
+ [
+ { jobOperationId: "a", remaining: remainingA },
+ { jobOperationId: "b", remaining: remainingB }
+ ],
+ 2500
+ );
+ expect(first[0]!.quantity + second[0]!.quantity).toBe(4000);
+ expect(first[1]!.quantity + second[1]!.quantity).toBe(2500);
+ // Both members drew from both picks (pro-rata, not sequential fill).
+ expect(first[1]!.quantity).toBeGreaterThan(0);
+ expect(second[0]!.quantity).toBeGreaterThan(0);
+ });
+
+ it("holds exact sums at 5-decimal quantities", () => {
+ const shares = splitPickAcrossMembers(
+ [
+ { jobOperationId: "a", remaining: 0.00125 },
+ { jobOperationId: "b", remaining: 0.00375 },
+ { jobOperationId: "c", remaining: 0.005 }
+ ],
+ 0.01
+ );
+ expect(sum(shares)).toBeCloseTo(0.01, 10);
+ expect(shares.map((s) => s.quantity)).toEqual([0.00125, 0.00375, 0.005]);
+ });
+
+ it("skips members with nothing remaining", () => {
+ const shares = splitPickAcrossMembers(
+ [
+ { jobOperationId: "done", remaining: 0 },
+ { jobOperationId: "open", remaining: 10 }
+ ],
+ 10
+ );
+ expect(shares).toEqual([{ jobOperationId: "open", quantity: 10 }]);
+ });
+
+ it("handles a single open member", () => {
+ expect(
+ splitPickAcrossMembers([{ jobOperationId: "a", remaining: 7 }], 3)
+ ).toEqual([{ jobOperationId: "a", quantity: 3 }]);
+ });
+
+ it("rejects a pick exceeding the total remaining", () => {
+ expect(() =>
+ splitPickAcrossMembers(
+ [
+ { jobOperationId: "a", remaining: 4 },
+ { jobOperationId: "b", remaining: 2 }
+ ],
+ 7
+ )
+ ).toThrow(/exceeds the batch's remaining requirement/);
+ });
+
+ it("rejects when no member has a remaining requirement", () => {
+ expect(() =>
+ splitPickAcrossMembers([{ jobOperationId: "a", remaining: 0 }], 1)
+ ).toThrow(/No member operation still requires this item/);
+ });
+
+ it("rejects a non-positive pick quantity", () => {
+ expect(() =>
+ splitPickAcrossMembers([{ jobOperationId: "a", remaining: 5 }], 0)
+ ).toThrow(/greater than zero/);
+ });
+});
diff --git a/packages/utils/src/batch-pick-split.ts b/packages/utils/src/batch-pick-split.ts
new file mode 100644
index 0000000000..c6a8a4b945
--- /dev/null
+++ b/packages/utils/src/batch-pick-split.ts
@@ -0,0 +1,4 @@
+// Node-side re-export of the edge-runtime batch-pick-split module (same
+// pattern as precision.ts / batch-time-split.ts). The source lives under
+// supabase/functions/ because the edge runtime only mounts that tree.
+export * from "../../database/supabase/functions/shared/batch-pick-split.ts";
diff --git a/packages/utils/src/types.ts b/packages/utils/src/types.ts
index e713c1d2c2..693196f540 100644
--- a/packages/utils/src/types.ts
+++ b/packages/utils/src/types.ts
@@ -50,6 +50,7 @@ export interface TrackedEntityAttributes {
Shipment?: string;
"Split Entity ID"?: string;
"Split From Entity ID"?: string;
+ "Merged From Entity IDs"?: string[];
"Stock Transfer Line"?: string;
"Stock Transfer"?: string;
expirationDate?: string;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e97c547ec3..32e7246e6e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1369,6 +1369,9 @@ importers:
remix-flat-routes:
specifier: 'catalog:'
version: 0.8.5
+ sonner:
+ specifier: 2.0.7
sst:
specifier: 'catalog:'
version: 4.6.9