Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(scrap): scrap & unscrap flow — MES serial/subcomponent scrap, ERP stock scrap/unscrap, scrap-reason dimension (#1355)
Brad Barbin17934a054539
diff --git a/.ai/plans/2026-08-07-scrap-unscrap-flow.md b/.ai/plans/2026-08-07-scrap-unscrap-flow.mdnew file mode 100644index 0000000000..3d42474efb--- /dev/null+++ b/.ai/plans/2026-08-07-scrap-unscrap-flow.md@@ -0,0 +1,398 @@+# Scrap & Unscrap Flow — implementation plan++**Spec:** .ai/specs/2026-08-06-scrap-unscrap-flow.md+**Research:** .ai/research/scrap-unscrap-flow.md+**Branch:** mes-scrap-serial-rework-flow++## Progress+- [x] Task 1: Migration A — scrap enums + itemLedger.scrapReasonId+- [x] Task 2: Migration B — Done-predicate fix (RPC exclusions verified unnecessary — see task note)+- [x] Task 3: Apply migrations and regenerate types+- [x] Task 4: Extend the shared adjustment posting core (dimensions, scrapReasonId, fixed-cost override)+- [x] Task 5: post-inventory-adjustment — Scrap and Unscrap adjustment types+- [x] Task 6: issue — jobOperationScrap case (serial/batch/untracked WIP scrap + spawn + reopen). Deviation: `issueJobOperationMaterials` returns `{ totalMaterialCost }` (additive) — a local COGS recompute would double-relieve layers.+- [x] Task 7: issue — rework scrapTrackedEntity (reason, methodType branches, replacement). Deviations: `rework.trackedEntityId` column no longer exists (`20260531084723`) — omitted from the rework insert; route scraps the WHOLE staged entity (no partial-quantity payload exists on this route), so batch partial scrap lives only in the ERP path.+- [x] Task 8: MES routes + validators for the new scrap paths+- [x] Task 9: MES UI — QuantityModal serial confirmation + entity-scrap modal fields+- [x] Task 10: ERP models/service/route for Scrap + Unscrap+- [x] Task 11: ERP UI — Scrap adjustment type + Scrapped filter + Unscrap action+- [x] Task 12: Sweep app-side predicate mirrors + serial-navigation helpers+- [x] Task 13: Update rules docs (traceability, inventory, MES)+- [~] Task 14: Browser verification — ERP surfaces render clean (tracked-entities loads, no errors); full behavioral e2e (serial scrap→spawn, MTO replacement, ERP scrap/unscrap with accounting fixtures) PENDING: needs seeded fixtures + MES here uses magic-link auth (no DEV_BYPASS), blocking MES browser drive++## Dependencies+- Task 2 needs Task 1 (enum values must be committed before function bodies reference `'Scrapped'`)+- Task 3 needs Tasks 1–2. Every later task needs Task 3 (generated types)+- Task 5 needs Task 4; Task 6 needs Task 4; Task 7 needs Task 6 (shared replacement helper)+- Task 8 needs Tasks 6–7; Task 9 needs Task 8+- Task 10 needs Task 5; Task 11 needs Task 10+- Task 12 needs only Task 3 — independent of Tasks 4–11 (parallelizable)+- Tasks 13–14 last; Task 14 needs everything++---++## Task 1: Migration A — scrap enums + itemLedger.scrapReasonId++**Depends on:** none+**Files:**+- Create: `packages/database/supabase/migrations/<timestamp>_scrap-unscrap-enums.sql` (via `pnpm db:migrate:new scrap-unscrap-enums` — never hand-pick the timestamp; HHMMSS must not be `000000`)++**Steps:**+1. Run `pnpm db:migrate:new scrap-unscrap-enums` from the repo root.+2. Write exactly this SQL (idempotent; enum values only — NO function bodies may reference the new values in this file, Postgres forbids using an enum value added in the same transaction):++```sql+-- Terminal scrap status for tracked entities (Epicor SCRAPPED / SAP ME precedent).+-- Recoverable via ERP Unscrap, unlike 'Consumed'.+ALTER TYPE "trackedEntityStatus" ADD VALUE IF NOT EXISTS 'Scrapped';++-- Scrap movement identity on the two document-type enums. These are DIFFERENT+-- enums with overlapping value sets — both need the value.+ALTER TYPE "itemLedgerDocumentType" ADD VALUE IF NOT EXISTS 'Scrap';+ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Scrap';++-- Scrap reason as a journal dimension (single scrapAccount + dimension slicing;+-- valueId on journalLineDimension is polymorphic → scrapReason.id).+ALTER TYPE "dimensionEntityType" ADD VALUE IF NOT EXISTS 'ScrapReason';++-- Reason lands on stock scrap/unscrap movements (MES production scrap keeps its+-- reason on productionQuantity.scrapReasonId).+ALTER TABLE "itemLedger" ADD COLUMN IF NOT EXISTS "scrapReasonId" TEXT;+ALTER TABLE "itemLedger" DROP CONSTRAINT IF EXISTS "itemLedger_scrapReasonId_fkey";+ALTER TABLE "itemLedger" ADD CONSTRAINT "itemLedger_scrapReasonId_fkey"+ FOREIGN KEY ("scrapReasonId") REFERENCES "scrapReason"("id") ON DELETE SET NULL;+CREATE INDEX IF NOT EXISTS "itemLedger_scrapReasonId_idx"+ ON "itemLedger"("scrapReasonId") WHERE "scrapReasonId" IS NOT NULL;+```++**Verify:**+```bash+ls packages/database/supabase/migrations/ | tail -3+# Expected: the new *_scrap-unscrap-enums.sql file with a timestamp NEWER than+# every existing migration, HHMMSS not 000000+```++**Out of scope:** function redefinitions (Task 2), seed data (no seeded dimension rows — dimensions are user-configured per company group).++## Task 2: Migration B — Done-predicate fix + Scrapped exclusions in status-aware RPCs++**Depends on:** Task 1+**Files:**+- Create: `packages/database/supabase/migrations/<timestamp>_scrap-unscrap-functions.sql` (via `pnpm db:migrate:new scrap-unscrap-functions`)++**Steps:**+1. Run `pnpm db:migrate:new scrap-unscrap-functions`.+2. For EACH function below, list every migration that touches it and fork the NEWEST body verbatim (sibling-branch lesson — a missed intermediate redefinition silently drops branches):+ ```bash+ grep -l "sync_update_job_operation_quantities" packages/database/supabase/migrations/*.sql | sort+ grep -l "get_inventory_quantities" packages/database/supabase/migrations/*.sql | sort+ grep -l "get_available_tracked_entities" packages/database/supabase/migrations/*.sql | sort+ grep -l "get_picking_list_tracked_available" packages/database/supabase/migrations/*.sql | sort+ ```+ Extract each newest body with `sed -n '<start>,<end>p'` into the new migration, then `diff` your pasted body against the source so the ONLY hunks are the edits below.+3. Edits per function:+ - `sync_update_job_operation_quantities` (newest: `20260706181125_fix-auto-complete-null-user.sql`): change the auto-Done predicate line+ `AND ("quantityComplete" + "quantityReworked" + "quantityScrapped") >= "targetQuantity"`+ to+ `AND ("quantityComplete" + "quantityReworked") >= "targetQuantity"`+ (Brad, 2026-08-07 — `targetQuantity` is the GOOD quantity per `20260119120000`; scrap must not consume it). No other hunk.+ - ~~`get_inventory_quantities`, `get_available_tracked_entities`, `get_picking_list_tracked_available`~~ — **verified unnecessary during execution (2026-08-07):** `itemLedger.trackedEntityStatus` is SYNCED to the entity's current status (`20260420112047` trigger `sync_item_ledger_on_tracked_entity_status_change`), and every scrap path writes a NEGATIVE ledger movement, so a Scrapped entity's rows net to zero in `get_inventory_quantities` with or without a status exclusion (unlike `Rejected`, which keeps positive rows and needs the exclusion). `get_available_tracked_entities` (`20260709125411:104`) and `get_picking_list_tracked_available` (`20260617142853:100`) filter `te."status" = 'Available'` — Scrapped is excluded by construction. No redefinition of the three RPCs.+4. Preserve `SECURITY DEFINER`/language attributes exactly as the newest version has them.++**Verify:**+```bash+pnpm db:migrate+# Expected: both new migrations apply cleanly (no errors)+psql "$(grep -o 'postgresql://[^"]*' .env.local | head -1)" -c "SELECT prosrc FROM pg_proc WHERE proname = 'sync_update_job_operation_quantities';" | grep -c 'quantityScrapped") >= '+# Expected: 0 (the predicate no longer sums quantityScrapped)+```+If `pnpm db:migrate` cannot reach the local DB, STOP and report (never rebuild the DB; wait for the user).++**Out of scope:** `complete_job_to_inventory` (keys on `quantityComplete`, untouched — but confirm by reading its newest body that its serial-entity selection reads `Reserved` status only; if it selects by anything that could match `Scrapped`, STOP and report).++## Task 3: Apply migrations and regenerate types++**Depends on:** Tasks 1–2+**Files:**+- Modify (generated): `packages/database/src/types.ts`, `packages/database/supabase/functions/lib/types.ts`, `packages/database/src/swagger-docs-schema.ts`++**Steps:**+1. `pnpm run generate:types`+2. Commit the regenerated files together with the migrations (types regen is normal and expected).++**Verify:**+```bash+grep -c '"Scrapped"' packages/database/src/types.ts+# Expected: >= 1 (trackedEntityStatus now includes Scrapped)+grep -c 'scrapReasonId' packages/database/supabase/functions/lib/types.ts+# Expected: >= 2 (productionQuantity existing + new itemLedger column)+```++**Out of scope:** hand-editing any generated file.++## Task 4: Extend the shared adjustment posting core++**Depends on:** Task 3+**Files:**+- Modify: `packages/database/supabase/functions/shared/post-adjustment.ts`++**Steps:**+1. Add to the `accounting` arg type (around line 70): `extraDimensions?: Array<{ entityType: string; valueId: string }>` — documented as "additional journalLineDimension tags beyond Item/ItemPostingGroup/Location (ScrapReason / WorkCenter / Employee for scrap postings); entityType must be the dimension's dimensionEntityType, valueId the referenced entity id".+2. In the dimension-tagging block (currently ~lines 354–378, the `dimensionValues` array of `["Item", ...], ["ItemPostingGroup", ...], ["Location", ...]`): append `...(accounting.extraDimensions ?? []).map(d => [d.entityType, d.valueId] as [string, string])` to `dimensionValues` before the `.filter(...)` that drops entries whose entityType has no active dimension.+3. Add to the ledger arg type: `scrapReasonId?: string | null`; pass it through on the `itemLedger` insert (~line 166–184).+4. Add `fixedUnitCost?: number` to the args: when set AND the movement is an increase, the new `costLedger` layer is booked at `fixedUnitCost × quantity` instead of `computeCurrentUnitCost` (used by Unscrap to reverse at the original scrapped cost). Decreases ignore it (they always go through `calculateCOGS`).+5. `'Scrap'` must be added to `JOURNAL_LINE_SAFE_DOCUMENT_TYPES` (~line 93) so scrap ledger rows map to journal `documentType='Scrap'` instead of falling back to `'Inventory Adjustment'`.++**Verify:**+```bash+cd packages/database/supabase/functions && git show HEAD:./shared/post-adjustment.ts > shared/post-adjustment.orig.ts 2>/dev/null; deno check shared/post-adjustment.ts 2>&1 | sed 's/\x1b\[[0-9;]*m//g' | grep -c "post-adjustment.ts:"; deno check shared/post-adjustment.orig.ts 2>&1 | sed 's/\x1b\[[0-9;]*m//g' | grep -c "post-adjustment.orig.ts:"; rm -f shared/post-adjustment.orig.ts+# Expected: the two counts are equal (own-file error delta = 0; deno check is+# never fully clean on the shared graph — gate on the delta, not exit code)+```++**Out of scope:** changing existing callers' behavior — a call site that passes no new args must produce byte-identical writes (no extraDimensions → same tags; no scrapReasonId → NULL; no fixedUnitCost → current-cost math).++## Task 5: post-inventory-adjustment — Scrap and Unscrap adjustment types++**Depends on:** Task 4+**Files:**+- Modify: `packages/database/supabase/functions/post-inventory-adjustment/index.ts`+- Create: `packages/database/supabase/functions/post-inventory-adjustment/resolve-unscrap-cost.ts` (pure module + test)+- Create: `packages/database/supabase/functions/post-inventory-adjustment/resolve-unscrap-cost.test.ts`+- Modify: `packages/database/supabase/functions/shared/batch-split.ts` — widen `childStatus` union with `"Scrapped"` (discovered during execution; additive type change only, callers unaffected)++**Steps:**+1. Extend the zod payload (~line 28): `adjustmentType` enum adds `"Scrap"` and `"Unscrap"`; add `scrapReasonId: z.string().optional()`, `unscrapOfItemLedgerId: z.string().optional()`; `.superRefine` requiring `scrapReasonId` whenever `adjustmentType` is `Scrap` or `Unscrap`.+2. Extend the active-dimension fetch (~line 161): `.in("entityType", ["Item", "ItemPostingGroup", "Location", "ScrapReason", "WorkCenter", "Employee"])`.+3. **Scrap branch** = the existing Negative-Adjmt. resolution path (serial-by-readableId / single-tracked-entity / untracked, `Set Quantity` excluded) with these deltas:+ - `bookAdjustment` called with `documentType: "Scrap"`, `scrapReasonId`, and `accounting.offsetAccount = accountDefault.scrapAccount ?? accountDefault.inventoryAdjustmentVarianceAccount` (the seed's documented runtime fallback).+ - `accounting.extraDimensions = [{ entityType: "ScrapReason", valueId: scrapReasonId }, { entityType: "Employee", valueId: userId }]` (no WorkCenter — no operation context in ERP).+ - Tracked entity: set `status = 'Scrapped'` and KEEP its `quantity` (the record of what was scrapped — today's negative path decrements it; the Scrap branch must not). Insert a `trackedActivity` `type: 'Scrap'` (`sourceDocument: 'Item'`, `sourceDocumentId: itemId`, attributes `{ "Scrap Reason": scrapReasonId }`) + `trackedActivityInput` (entity, quantity).+ - Batch partial scrap (quantity < entity quantity): use `buildBatchSplitRecords` from `../shared/batch-split.ts` — the departing CHILD becomes the `Scrapped` entity, the parent keeps its id and is decremented (identity-flip convention).+4. **Unscrap branch** (tracked): payload carries `trackedEntityId` of a `Scrapped` entity + `unscrapOfItemLedgerId` (the original scrap `itemLedger` row). Steps: verify the entity is `Scrapped` (else throw); set `status = 'Available'`; positive `itemLedger` via `bookAdjustment` (`documentType: "Scrap"`, `correctionOfItemLedgerId: unscrapOfItemLedgerId`, same `storageUnitId` as the original scrap row, `scrapReasonId`, extraDimensions as above) with `fixedUnitCost` = original scrapped unit cost; `trackedActivity` `type: 'Unscrap'` + `trackedActivityOutput`.+5. **Unscrap branch** (untracked): positive adjustment through `bookAdjustment` with the scrap offset + reason, no `fixedUnitCost` (current cost — v1).+6. `resolve-unscrap-cost.ts`: pure function `resolveUnscrapUnitCost(rows: Array<{ quantity: number; cost: number }>): number | null` — given the original scrap movement's `costLedger` rows, return `Math.abs(total cost / total quantity)` or `null` when rows are empty/zero-quantity (caller then falls back to current cost). `deno test` covers: single row, multi-row, empty, zero-quantity.+7. Wire the cost lookup: `costLedger` rows are found by the scrap ledger row's id — check how `costLedger` links to `itemLedger` in this function's existing decrease path (it inserts both; find the linking column, e.g. `itemLedgerId` or `documentId`). If NO queryable link from an `itemLedger` row to its `costLedger` rows exists, STOP and report — do not guess a join.++**Verify:**+```bash+cd packages/database/supabase/functions && deno test post-inventory-adjustment/resolve-unscrap-cost.test.ts+# Expected: all tests pass+# Own-file deno check delta = 0 for index.ts (same baseline method as Task 4)+```++**Out of scope:** `Set Quantity`, storage-unit transfers, `post-inventory-count` (all byte-identical); the MES `AdjustInventory` form (untouched in v1).++## Task 6: issue — jobOperationScrap case++**Depends on:** Task 4+**Files:**+- Modify: `packages/database/supabase/functions/issue/index.ts` — new case+- Create: `packages/database/supabase/functions/issue/scrap-replacement.ts` — shared reopen/top-up/spawn helper (also used by Task 7)+- Copy from (precedent): `issue/index.ts` case `jobOperationSerialComplete` (lines ~1173–1386 pre-change)++**Steps:**+1. New payload member of the discriminated union: `{ type: "jobOperationScrap", id: jobOperationId, quantity, scrapReasonId, notes?, trackedEntityId?, setup/labor/machineProductionEventId?, companyId, userId }`. (The spec names the serial path `jobOperationSerialScrap`; implementation is ONE case discriminated internally by the make method's tracking flags — serial requires `trackedEntityId` and `quantity === 1`; batch/untracked take `quantity`. Note this naming consolidation in the PR description.)+2. In one Kysely transaction, mirroring `jobOperationSerialComplete`'s structure:+ a. Insert `productionQuantity` `{ type: 'Scrap', quantity, scrapReasonId, notes, jobOperationId, companyId, createdBy: userId }` + the event links (the quantity-sync interceptor aggregates `quantityScrapped`; with Task 2's predicate it no longer flips Done).+ b. Backflush the operation's materials for `quantity` units via `issueJobOperationMaterials` (same call the `jobOperation` case makes), **capturing the returned/computed total material cost** for step (e).+ c. Serial only: `trackedActivity` `type: 'Scrap'`, `sourceDocument: 'Job Operation'`, `sourceDocumentId: jobOperationId`, attributes `{ "Scrap Reason": scrapReasonId, ["Operation " + jobOperationId]: <index> }`; `trackedActivityInput` (entity, qty 1); update entity `status: 'Scrapped'` (keep quantity 1). If the entity's status is `Consumed` or already `Scrapped`, throw ("entity is not in progress").+ d. Serial only — spawn the next serial: same `getNextSerialNumbers(trx, { itemId, companyId, count: 1, locationCode, locationName })` + `Reserved`-entity insert (cloned attributes, `readableId` = spawned) as `jobOperationSerialComplete`, spawned when count of the make method's non-`Scrapped` entities < the good quantity still required (`targetQuantity` of the operation). Return `newTrackedEntityId`.+ e. GL (only when `companySettings.accountingEnabled`): one journal, Dr `accountDefault.scrapAccount ?? inventoryAdjustmentVarianceAccount` / Cr `workInProgressAccount`, amount = (b)'s actual current-op backflush cost + estimated prior-op material cost (Σ over the make method's `jobMaterial` rows attached to operations ordered BEFORE this one: `quantityPerParent-equivalent unit quantity × itemCost.unitCost`) × `quantity`. Use the `debit()`/`credit()` helpers, `sourceType` the same value the existing `createMaterialWipEntries` journals use, `documentType: 'Scrap'`, `documentId: jobId`. Dimension tags per the `post-adjustment.ts` mechanism: fetch active dimensions for entityTypes `["Item","ItemPostingGroup","Location","ScrapReason","WorkCenter","Employee"]` (company → `companyGroupId`, precedent `post-inventory-adjustment/index.ts:146-167`) and insert `journalLineDimension` rows for item, item's posting group, job location, `scrapReasonId`, the operation's `workCenterId`, and `userId`.+ f. `scrap-replacement.ts` helper `applyScrapReplacement(trx, { jobMakeMethodId, jobId, quantity, companyId, userId })`: (i) reopen the make method's operations `status = 'Ready'` where `status = 'Done'` (stamp `updatedBy`/`updatedAt` — null-audit lesson); (ii) compute cumulative allowance: root make method → `job.scrapQuantity`; if the job's cumulative actual scrap (Σ `quantityScrapped` of the make method's ops... use the make method's max op `quantityScrapped` + this quantity) exceeds the allowance, bump each op's `operationQuantity` by the excess and, when the make method is the root (`parentMaterialId IS NULL`), bump `job.scrapQuantity` by the excess; (iii) refresh the make method's `jobMaterial.estimatedQuantity`/`quantity` fields to per-unit quantity × new `operationQuantity` (read how those two columns relate on existing rows first; mirror the ratio). **`targetQuantity` is NEVER written.** (iv) invoke the same reschedule the `trigger-rework` function calls (find its invoke near the end of `trigger-rework/index.ts` and replicate).+ g. Call `applyScrapReplacement` for serial and batch parents (untracked too — the reopen/top-up logic is tracking-agnostic).+3. If `issueJobOperationMaterials` does not return per-call cost totals, compute the backflush cost in the case from the same inputs it uses (jobMaterial rows × `itemCost.unitCost`) — do NOT modify `issueJobOperationMaterials`' return type if other callers would be affected; prefer a local computation.++**Verify:**+```bash+# Own-file deno check delta = 0 for issue/index.ts + scrap-replacement.ts (Task 4 baseline method)+cd packages/database/supabase/functions && deno check issue/scrap-replacement.ts 2>&1 | sed 's/\x1b\[[0-9;]*m//g' | grep -c "scrap-replacement.ts:"+# Expected: 0+```++**Out of scope:** `jobOperationSerialComplete` / `jobOperationBatchComplete` (unchanged); the auto-Done predicate (Task 2); labor/overhead in the scrap valuation (stays in WIP → close-job variance, decision 6).++## Task 7: issue — rework scrapTrackedEntity++**Depends on:** Task 6+**Files:**+- Modify: `packages/database/supabase/functions/issue/index.ts` — case `scrapTrackedEntity` (~lines 1682–1871 pre-change)++**Steps:**+1. Payload additions: `scrapReasonId: z.string()` (required), `makeReplacement: z.boolean().optional()`.+2. Common changes (all branches): entity `status: 'Scrapped'` (was `Consumed`); activity `type: 'Scrap'` (was `'Consume'` + `attributes.Scrapped`), attributes gain `{ "Scrap Reason": scrapReasonId }`; keep the `parentTrackedEntityId` output row behavior exactly as today.+3. **Non-Make-to-Order branch** (was: Consumption ledger + `createMaterialWipEntries` + `quantityIssued` bump) becomes:+ - `bookAdjustment` (import from `../shared/post-adjustment.ts`) with: `entryType 'Negative Adjmt.'`, `documentType 'Scrap'`, `documentId: jobId`, `scrapReasonId`, quantity negative, `storageUnitId` from `resolveTrackedEntityBin` (already imported in this file — never `.find(...)?.storageUnitId`), `trackedEntityId`, `accounting.offsetAccount = scrapAccount` fallback chain, `extraDimensions` = ScrapReason + WorkCenter (`material.jobOperationId` → operation's `workCenterId`) + Employee (`userId`).+ - DELETE the `jobMaterial.quantityIssued` bump (deliberate behavior change, spec decision 10 — the requirement stays open so the operator issues a replacement).+ - Batch partial (quantity < entity.quantity): `buildBatchSplitRecords` — departing child is the `Scrapped` entity.+4. **Make-to-Order branch** (was: genealogy only): keep no stock ledger; add the WIP→scrap journal using Task 6's step-(e) shape valued at the subassembly's accumulated material cost (its make method's `jobMaterial` unit estimates × quantity — resolve the subassembly's `jobMakeMethod` via the material's `jobMaterialWithMakeMethodId`/`jobMakeMethod.parentMaterialId` linkage; read `get_job_method`'s join in `20240915192542_job-methods.sql:217-288` for the exact columns). When `makeReplacement` is true: call `applyScrapReplacement` on the subassembly's `jobMakeMethod` + spawn a replacement `Reserved` serial entity when the subassembly requires serial tracking (same spawn as Task 6 step d); insert a `rework` row `{ jobId, triggeredAtJobOperationId: material.jobOperationId, targetJobOperationId: <first op of the subassembly make method by order>, reason: <scrapReason.name>, quantity, trackedEntityId, requestedById: userId, companyId }`.+5. If the material's `methodType` cannot be read where the branch splits (verify the existing `material.methodType !== "Make to Order"` guard at ~line 1820 still exists), STOP and report.++**Verify:**+```bash+# Own-file deno check delta = 0 for issue/index.ts (Task 4 baseline method)+grep -n "quantityIssued" packages/database/supabase/functions/issue/index.ts | wc -l+# Expected: count DECREASED vs git show HEAD (the scrapTrackedEntity bump is gone;+# other cases' quantityIssued writes remain)+```++**Out of scope:** `trackedEntitiesToOperation` / `unconsumeTrackedEntities` (their `.find` bin patterns and status writes are NOT in scope — scoped-fix lesson); `partToOperation`.++## Task 8: MES routes + validators for the new scrap paths++**Depends on:** Tasks 6–7+**Files:**+- Modify: `apps/mes/app/services/models.ts` — extend `scrapQuantityValidator`; add `scrapTrackedEntityValidator`+- Modify: `apps/mes/app/routes/x+/scrap.tsx` — route through the new edge case+- Modify: `apps/mes/app/routes/x+/entity+/$materialId.$trackedEntityId.scrap.tsx` — formData validation + new payload fields++**Steps:**+1. `models.ts`: `scrapQuantityValidator` already carries `jobOperationId`, `quantity`, `scrapReasonId` (required), `notes`, `trackedEntityId`, `trackingType` — no change needed; confirm and leave as-is. Add:+ ```ts+ export const scrapTrackedEntityValidator = z.object({+ scrapReasonId: zfd.text(z.string()),+ makeReplacement: zfd.checkbox(),+ notes: zfd.text(z.string().optional())+ });+ ```+ (Check `zfd.checkbox` exists in this file's zfd usage; if not, use `zfd.text(z.string().optional()).transform(v => v === "true" || v === "on")`.)+2. `x+/scrap.tsx`: replace the `insertScrapQuantity` + `issue type:"jobOperation"` pair with ONE service-role invoke of `issue` `{ type: "jobOperationScrap", id: jobOperationId, quantity, scrapReasonId, notes, trackedEntityId (when trackingType === "Serial"), setup/labor/machineProductionEventId, companyId, userId }`. Surface `{ error }` through the existing flash pattern; return the edge function's `newTrackedEntityId` in the action data so the client can navigate to the spawned serial (mirror how `x+/complete.tsx` returns its result — read that file first and copy its return shape).+3. Entity scrap route: parse `await request.formData()` through `validator(scrapTrackedEntityValidator)`; pass `scrapReasonId` + `makeReplacement` in the `issue` body. Keep `parentId` query-param handling as-is. Change `requirePermissions(request, {})` to `requirePermissions(request, { update: "production" })` on BOTH routes only if the existing MES mutation routes do so — check `x+/complete.tsx` first and match it exactly (do not invent a stricter gate than the app's convention).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: exit 0+```++**Out of scope:** `insertScrapQuantity` in `operations.service.ts` — leave the function in place (the ERP `ProductionQuantityForm` writes `productionQuantity` rows through its own route; only the MES route stops calling it).++## Task 9: MES UI — QuantityModal serial confirmation + entity-scrap modal fields++**Depends on:** Task 8+**Files:**+- Modify: `apps/mes/app/components/JobOperation/components/QuantityModal.tsx` — scrap branch (~lines 289–297)+- Modify: the component that triggers the entity-scrap route (find it: `grep -rn "scrap" apps/mes/app/components --include='*.tsx' -l` then locate the caller of the `$materialId.$trackedEntityId.scrap` path helper — likely in `JobOperation.tsx`'s Materials section or `IssueMaterialModal.tsx`)+- Copy from (precedent): `QuantityModal.tsx` scrap branch itself (ScrapReason + notes composition); `apps/mes/app/components/JobOperation/components/ScrapReason.tsx`++**Steps:**+1. `QuantityModal` scrap branch: when the parent is serial-tracked (the modal already receives tracking context — it submits `trackedEntityId`/`trackingType` hidden fields per `baseQuantityValidator`), render the selected serial's `readableId` above the reason select ("Scrapping serial {readableId}" via Lingui `<Trans>`), and lock the quantity input to 1 (serial units are single). Batch/untracked branches unchanged. All MES components `size="lg"`.+2. On successful scrap of a serial with a spawned replacement (`newTrackedEntityId` in the action response), navigate to the new entity the same way the complete flow advances serials — find the `?trackedEntityId` navigation in `useOperation.tsx`/`AssemblyView.tsx` post-complete handling and reuse that exact mechanism.+3. Entity-scrap trigger: replace the current bare confirm (route invoke with no body) with a small modal: `ScrapReason` (required), notes `TextArea`, and — only when the material's `methodType === "Make to Order"` — a `Checkbox` "Make replacement" defaulting checked. Submit as formData to the same route. `size="lg"`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes && pnpm run lint+# Expected: exit 0 for typecheck; lint clean on touched files+```++**Out of scope:** `AssemblyView.tsx` layout (it consumes the same shared modal + routes — no view-specific code unless the navigation hook from step 2 lives there, in which case touch only the navigation handler); the ERP `ProductionQuantityForm`.++## Task 10: ERP models/service/route for Scrap + Unscrap++**Depends on:** Task 5+**Files:**+- Modify: `apps/erp/app/modules/inventory/inventory.models.ts` — `inventoryAdjustmentValidator` (~line 153)+- Modify: `apps/erp/app/modules/inventory/inventory.service.ts` — `insertManualInventoryAdjustment` passthrough+- Modify: `apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx` — no structural change; confirm passthrough++**Steps:**+1. `inventoryAdjustmentValidator`: change `adjustmentType` to `z.enum([...itemLedgerTypes, "Set Quantity", "Scrap", "Unscrap"])`; add `scrapReasonId: zfd.text(z.string().optional())`, `unscrapOfItemLedgerId: zfd.text(z.string().optional())`; extend the existing `.superRefine` to require `scrapReasonId` when `adjustmentType` is `"Scrap"` or `"Unscrap"` (`.refine` must return boolean / use ctx.addIssue — zod refine lesson).+2. `insertManualInventoryAdjustment`: it forwards the validated payload to the `post-inventory-adjustment` invoke — add the two new fields to its body object (keep the `{ data, error }` signature).+3. The adjustment route action already strips `requiresSerialTracking` and forwards the rest — verify the new fields flow through untouched; the storage-rules evaluation block treats Scrap as a negative (`pick`) movement and Unscrap as positive (`place`) — read how `adjustmentType` maps to the surface today and extend the mapping the same way.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0+```++**Out of scope:** MES `apps/mes/app/services/inventory.service.ts` twin wrapper (the MES AdjustInventory form does not gain Scrap in v1).++## Task 11: ERP UI — Scrap adjustment type + Scrapped filter + Unscrap action++**Depends on:** Task 10+**Files:**+- Modify: `apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx` — the adjustment modal+- Modify: `apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsx` — status filter + row action+- Copy from (precedent): the adjustment modal in `InventoryStorageUnits.tsx` itself (its type select + conditional fields); `apps/erp/app/components/Form/ScrapReason.tsx` for the reason select; existing row-action menus in `TrackedEntitiesTable.tsx`++**Steps:**+1. Adjustment modal: add a "Scrap" option to the adjustment-type select; when selected, render `ScrapReason` (required) and keep the quantity/storage-unit fields of the Negative-Adjmt. branch. Lingui for all new strings. ERP default `size="md"`.+2. `TrackedEntitiesTable`: ensure the status filter options include `Scrapped` (read how the status filter list is built — if it derives from the generated enum type, it may pick up `Scrapped` automatically; verify rather than hardcode). Add a row action "Unscrap" visible only when `row.status === "Scrapped"` and `permissions.can("update", "inventory")`: opens a modal (Drawer/Modal per this table's existing action precedent) with `ScrapReason` + confirm, posting to `path.to.inventoryItemAdjustment(itemId)` with hidden fields `adjustmentType="Unscrap"`, `trackedEntityId`, `quantity` = entity quantity, `locationId`, and `unscrapOfItemLedgerId` = the entity's scrap movement (fetch: the entity's `itemLedger` row with `documentType='Scrap'` and negative quantity, newest — if the table's loader can't provide it cheaply, pass only `trackedEntityId` and resolve the ledger row server-side in the edge function; choose the server-side option if the loader would need a new join).+3. Show scrap reason on Scrapped rows if the table already renders per-row metadata columns (optional — skip if it requires a new join; note the skip in the PR).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp && pnpm run lint+# Expected: exit 0; lint clean on touched files+```++**Out of scope:** the traceability graph view; `tracked-entity.expiry.tsx`; batch subdivision UI.++## Task 12: Sweep app-side predicate mirrors + serial-navigation helpers++**Depends on:** Task 3 (independent of Tasks 4–11 — parallelizable)+**Files:**+- Modify: `apps/mes/app/components/Inspection/InspectionView.tsx` (~line 385)+- Modify: `apps/mes/app/services/operations.service.ts` — `isSerialEntityIncompleteForOperation` (~line 1185), `getNextIncompleteSerialEntity` (~line 1205)++**Steps:**+1. `InspectionView.tsx` `opRemaining`: remove the `- (operation.quantityScrapped ?? 0)` term (scrap no longer reduces remaining good work; keep the `quantityReworked` term).+2. Run `grep -rn "quantityScrapped" apps/mes/app apps/erp/app --include='*.ts' --include='*.tsx'` and inspect every hit: any expression computing REMAINING work or a DONE condition as `target − complete − scrapped` (or `complete + scrapped >= target`) loses the scrap term; display-only usages stay (JobDag badge, the `operationQuantity + quantityScrapped` step-record navigation in `JobOperation.tsx`, kanban card counts, plain headings). List every changed and every deliberately-kept site in the task commit message.+3. `operations.service.ts`: both serial-navigation helpers currently treat `status !== "Consumed"` as incomplete — extend to `!["Consumed", "Scrapped"].includes(status)` (or the equivalent in the existing code shape).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes --filter=erp+# Expected: exit 0+grep -n "quantityScrapped" apps/mes/app/components/Inspection/InspectionView.tsx+# Expected: no hit inside the opRemaining computation+```++**Out of scope:** the DB predicate (Task 2); ERP production dashboards that merely display scrap totals.++## Task 13: Update rules docs++**Depends on:** Tasks 1–12+**Files:**+- Modify: `.claude/rules/traceability-model.md` — `trackedEntityStatus` enum gains `Scrapped`; Scrap/Unscrap activity types; the scrap→spawn flow+- Modify: `.claude/rules/mes-job-operation-ui.md` — scrap route behavior, auto-Done predicate change+- Modify: `.claude/rules/inventory-system.md` — ERP Scrap/Unscrap adjustment types, scrapAccount posting, ScrapReason dimension++**Steps:**+1. Update each rule's affected sections to describe the COMMITTED post-change behavior (document only what landed; cite the new migration filenames). Keep edits surgical — only sections invalidated by this feature.+2. Spec bookkeeping: check off the spec's acceptance criteria that are code-complete, add a changelog line "implemented — see plan .ai/plans/2026-08-07-scrap-unscrap-flow.md".++**Verify:**+```bash+grep -c "Scrapped" .claude/rules/traceability-model.md+# Expected: >= 1+```++**Out of scope:** the `docs/` Fumadocs site (follow-up via /carbon-docs after browser verification confirms final behavior — note it in the PR body).++## Task 14: Browser verification via /test++**Depends on:** all previous+**Files:** none (verification only)++**Steps:**+1. Boot the stack with plain `crbn up` (portless). If the stack cannot boot, the loop is BLOCKED, not done — report.+2. Invoke the `/test` skill against this feature with these scenarios (they mirror the spec's acceptance criteria):+ - Serial job qty 3: scrap the in-progress serial at op 2 from the **operation view** → verify entity `Scrapped`, replacement serial appears and is navigated to, op 1 reopened, `targetQuantity` still 3, `operationQuantity` 4, `job.scrapQuantity` 1 (psql assertions), and the op does not flip Done until 3 good complete.+ - Repeat the scrap from the **assembly view** on a second job → same DB effects.+ - Scrap a picked batch material entity (qty 2 of 5) from the Materials section → split child `Scrapped`, ledger −2 with reason, requirement still open.+ - MTO subassembly scrap with Make Replacement ON → reopened subassembly ops + `rework` row + spawned serial.+ - ERP: scrap an Available serial with reason → gone from on-hand/pickers, listed under Scrapped filter; then Unscrap → restored at original cost (psql: journal amounts equal the original scrap's).+ - Accounting enabled fixture: verify Dr scrapAccount / Cr WIP (or inventory) journal lines exist with ScrapReason/WorkCenter/Employee `journalLineDimension` rows (activate those dimensions in settings first).+ - Planned-scrap job (10 + 20%): 8 good + 2 scrap does NOT auto-Done.+3. Capture screenshots for the PR (net-new UI: ERP Scrap option, Scrapped filter + Unscrap action, MES scrap modal serial confirmation, entity-scrap modal).++**Verify:**+```bash+# /test playbook completes all scenarios; psql assertions return expected values+# Expected: every scenario green; screenshots saved for the PR+```++**Out of scope:** load/perf testing; Xero/QBO sync of scrap journals (follow-up).diff --git a/.ai/research/scrap-unscrap-flow.md b/.ai/research/scrap-unscrap-flow.mdnew file mode 100644index 0000000000..7458274888--- /dev/null+++ b/.ai/research/scrap-unscrap-flow.md@@ -0,0 +1,168 @@+# Scrap & Rework Flow Research: Best Practices Survey++## Summary++Surveyed how SAP (ECC/S4 + SAP ME/DM), Oracle Fusion Cloud Manufacturing, NetSuite+(core WIP + Advanced Manufacturing), Epicor Kinetic, Infor (SyteLine/CSI, LN, M3),+JobBOSS², Plex, and Fulcrum handle: shop-floor scrap of the unit being made,+scrap of already-issued/produced components, serial vs batch tracked scrap,+warehouse scrap/unscrap, and the GL treatment. Strong consensus: scrap is a+distinct reported quantity with a mandatory reason code; the reason code (not the+transaction type) is the standard hook for GL account selection and normal/abnormal+analysis; serialized scrap is a **terminal status** on the serial with replacements+getting **new** serials; no mainstream system auto-inflates order quantity on scrap+(replacement is an explicit action — rework operations on the same order, a rework+order settling to the parent, or MRP-driven new supply); warehouse scrap is an+inventory movement to a scrap expense account with reversal as the mirrored+movement (SAP 551/552, Oracle Return-from-Scrap). Oracle Fusion is the only system+with a first-class **unscrap** ("Return from Scrap") that enforces serial/lot+alignment and reverses at original cost. Nobody auto-creates the next serial when+a serialized WIP unit is scrapped — SAP explicitly leaves the order short and+users complain about it — so Carbon auto-spawning the replacement serial (as it+already does on serial completion) is a genuine differentiator, matching how its+own `jobOperationSerialComplete` already works.++## Competitors Surveyed++- **SAP ECC/S4 + SAP ME/DM** — the enterprise reference: confirmation scrap (CO11N), movement types 551/552, scrap variance calculation, SFC scrap in MES.+- **Oracle Fusion Cloud Manufacturing** — most modern first-class model: Scrap/Return-from-Scrap operation transactions, reason-code-driven accounts.+- **NetSuite (core + Advanced Manufacturing)** — mid-market reference; scrap-by-variance vs first-class scrap modes; scrap account on the item.+- **Epicor Kinetic** — job-shop reference; MES scrap at End Activity, Nonconformance→DMR formal path, SCRAPPED serial status.+- **Infor SyteLine/CSI, LN, M3** — immediate scrap-expense posting at cost-through-operation (SyteLine); quarantine + rework-order disposition (LN).+- **JobBOSS²** — small job shop floor: pieces good / pieces scrapped, split-job replacement.+- **Plex** — container/label-status scrap model (SCRAP status excludes from nettable inventory).+- **Fulcrum** — operator UX benchmark: one-tap scrap with qty + reason from the checkpoint flow, live schedule/inventory effect.++## Key Consensus Patterns++### 1. Scrap is reported as a distinct quantity with a mandatory reason code+- **SAP**: CO11N carries Yield / Scrap / Rework quantities + Reason for Variance codes; only yield can be received to stock.+- **Oracle Fusion**: Scrap transactions *require* a reason code; reason codes are user-defined lookups.+- **Epicor**: scrap qty + mandatory scrap reason on the labor detail; **Infor CSI**: Quantity Complete + Quantity Scrapped per operation with reason; **Fulcrum/Plex/JobBOSS**: qty + reason at point of work.+- **Rationale**: the reason code is the analytic (Pareto/scrap heat map) and accounting hook.++### 2. Reason codes drive the GL account (the modern pattern)+- **Oracle Fusion**: costing uses the scrap reason code to derive the scrap account (SLA mapping).+- **Epicor**: Reason Codes of type Scrap/DMR carry a GL Control Code selecting the expense account.+- **SAP**: movement 551 → OBYC GBB-VNG per valuation class; custom movement copies for different accounts.+- **Rationale**: one scrap transaction type, N accounts by cause; avoids proliferating transaction types.++### 3. Scrap cost: expense at report time (at cost-through-operation) vs wash to variance at close+- **Expense-at-report**: Infor SyteLine removes the full accumulated WIP cost of scrapped units (this op + prior ops) from WIP and debits scrap expense when scrap is reported. Oracle Fusion: Dr scrap account / Cr WIP at cost-accumulated-through-operation (timing configurable: immediately vs at WO close).+- **Variance-at-close**: Epicor MES scrap and NetSuite core leave scrap cost in WIP; it settles to manufacturing/WIP variance at job close. Oracle EBS made the scrap account *optional* — with no account, scrap washes out as variance.+- **Doctrine**: normal scrap = product cost (absorbed via planned scrap % in standards or spread over good units); abnormal scrap = period expense. Mid-market systems do NOT auto-classify; reason codes are the analytic proxy.++### 4. Serialized scrap is a terminal status; replacements get new serials; no auto-spawn anywhere+- **SAP**: no automatic scrapped serial status (recommends user-exit to inactivate); scrapping a serialized WIP unit leaves the order short — users must manually change order qty or create a new order. SAP ME's Scrap SFC sets SFC status **Scrapped** (a Return/unscrap exists in ME).+- **Epicor**: serials get status **SCRAPPED** at DMR reject/labor scrap; blocked from reuse; no auto-replacement.+- **Oracle Fusion**: pick the specific serial when scrapping; Return-from-Scrap must match the original serial.+- **Rationale/Gap**: keeping the order whole is a manual pain point everywhere — auto-creating the next serial (which Carbon already does on serial *completion*) applied to scrap is an improvement on all surveyed systems.++### 5. Batch/lot scrap is a partial-quantity movement against the lot+- **SAP**: 551 posted per batch, supports partial quantity; batch has no "scrapped" status — stock just decrements.+- **NetSuite**: lot adjustments with `LOT#(qty)`; serialized items enumerate serials.+- **SAP ME**: partial scrap of an SFC = split the SFC, scrap the split.++### 6. Component scrap after issue: reverse-or-absorb, then replace explicitly+- **SAP**: reverse issue (262) + scrap from stock (551) + re-issue (261); or leave the 261 (order absorbs cost) and issue extra quantity (shows as input-quantity variance).+- **Epicor**: NonConf→DMR for the formal path; informally issue extra material. "Epicor does not provide any functionality to automate scrap" — replacement qty is a human decision (issue more, Production Yield Recalc → MRP new supply, or split job).+- **Infor LN**: rejects move to quarantine; disposition can create a **rework production order based on the originating order**.+- **SAP rework**: trigger points insert reference (rework) operations into the same order; or CO07 rework order settling costs to the original order.++### 7. Warehouse scrap/unscrap = mirrored inventory movements to/from a scrap account+- **SAP**: 551 scrap (Cr inventory BSX at current cost, Dr GBB-VNG scrap expense) / 552 reversal; 553/555 variants for QI/blocked stock; reason per movement (OMBS).+- **Oracle Fusion**: miscellaneous issue to scrap account; WIP-side **Return from Scrap** reverses at *originally scrapped cost*, reason required, serial/lot must match.+- **NetSuite**: negative inventory adjustment to scrap/expense account; reversal is a positive adjustment at entered/current cost (known audit weakness — original cost not preserved).+- **Plex**: container status → SCRAP excludes it from nettable inventory (status model rather than immediate movement).++### 8. Scrap does not auto-flow into order quantity changes+- **SAP**: confirmed scrap updates expected-yield variance; GR is limited to yield; order qty unchanged unless manually reduced (or underdelivery tolerance).+- **Oracle Fusion**: downstream operation requirements recalc for remaining qty; WO finishes short (completed + scrapped ≤ start).+- **Epicor (opt-in)**: Production Yield Recalculation can decrease job qty and let MRP create replacement supply — the only automated replacement, and it is explicit configuration.++## Answers to Research Questions++1. **Does any system auto-create the next serial when a serialized WIP unit is scrapped?** No (SAP explicitly manual; Epicor manual; Fusion finishes short). Carbon doing so mirrors its own serial-complete spawn and beats the field.+2. **How is scrap of an already-made subassembly handled when it was made-to-order?** Rework order settling to the parent (SAP CO07), rework ops inserted into the same order (SAP trigger points, Carbon's existing `trigger-rework` equivalent), or quarantine→rework order (Infor LN). Quantity replacement is always an explicit action.+3. **What accounts does warehouse scrap post to?** Cr inventory at current cost / Dr scrap expense (SAP GBB-VNG, NetSuite scrap account, Fusion reason-mapped account). Reversal mirrors it; Fusion reverses at original scrapped cost.+4. **WIP scrap valuation?** Cost accumulated through the operation where scrap occurred (Fusion, SyteLine) — materials issued + labor/overhead absorbed to that point. Simpler systems expense at item cost or wash to variance at close.+5. **Is "unscrap" a real pattern?** Only Oracle Fusion has it first-class (Return from Scrap, reason-coded, serial/lot aligned, reverses original cost). Everyone else: opposite movement/adjustment.+6. **Partial batch scrap?** Universal: decrement the lot by the scrapped qty; no lot-level status change unless the whole lot is dispositioned.++## Competitor-Specific Details++### SAP+Planned scrap master data (assembly % on MRP1, component scrap on MRP4/BOM item, operation scrap on routing with Net ID) inflates orders/requirements and bakes normal scrap into standard cost — Carbon's `itemReplenishment.scrapPercentage` → `job.scrapQuantity` is the same idea. Unplanned scrap surfaces via period-end variance calculation (scrap variance category) settling to price-difference accounts; MM scrap (551) is the only path hitting the dedicated scrap expense account.++### Oracle Fusion+Distinguishes **Reject** (park for disposition: rework / return to prior op / accept / scrap) from **Scrap** (terminal). Scrap valuation timing is a cost-profile option. Completion transactions exclude scrapped units' cost — scrap carries its own cost out of WIP.++### NetSuite+Scrap handling modes in Advanced Manufacturing: Do Not Post (metrics only), Post As Scrap, Post As Built and Move (to a Location Scrap Bin — the "scrap is a place" model). "Issue for Scrap" backflushes components for scrapped qty so material cost hits the WO (Carbon's scrap route already backflushes the same way).++### Epicor+Two-tier: cheap path (scrap qty + reason on labor, cost dies in WIP→variance at close) vs formal path (NonConformance → Inspection → DMR with dispositions, interim inspection account, reason-code GL). Serial status SCRAPPED blocks reuse.++### Infor+SyteLine is the cleanest "expense at report" reference: accumulated WIP cost of scrapped units (through the reporting op) → scrap expense immediately. LN's quarantine + "create rework production order from originating order" is the cleanest replacement-flow reference.++### Plex / Fulcrum (UX)+Fulcrum: scrap embedded in the operator checkpoint flow — out-of-tolerance → one tap → qty + reason → supervisor notified; NCR raisable in place. Plex: scrap is a container status change with a physical SCRAP label; quality alerts push recent defect history to the operator.++## Recommended Approach for Carbon++1. **Keep one scrap entry point per view (the existing Scrap action/modal), add tracked-entity awareness**: for the serial unit being made, scrap = terminal status on that entity + auto-spawn of the next serial (extends Carbon's existing `jobOperationSerialComplete` spawn — better than every surveyed system). For batches, partial-quantity scrap against the lot (SAP 551-per-batch pattern; split conventions per Carbon's batch-split spec).+2. **Add a terminal `Scrapped` tracked-entity status** (Epicor SCRAPPED / SAP ME Scrapped SFC precedent) rather than reusing `Consumed` — scrapped ≠ consumed-into-parent, and unscrap needs to find them.+3. **Post scrap at report time**: Dr `scrapAccount` / Cr WIP (WIP scrap, SyteLine/Fusion pattern) or Cr inventory (stock scrap, SAP 551) valued at cost-through-operation for WIP output scrap approximated by materials issued + absorbed labor (or item cost where WIP granularity is impractical). Carbon already has `accountDefault.scrapAccount` and the `bookAdjustment` offset-account mechanism.+4. **Replacement is explicit, never automatic order-qty inflation** (universal consensus): scrapping a made-to-order subassembly offers a rework/make-more action reusing Carbon's existing `trigger-rework` op-quantity-bump machinery; pull-from-inventory components simply re-issue from stock.+5. **ERP scrap/unscrap as a first-class adjustment pair** (SAP 551/552 + Fusion Return-from-Scrap): scrap = negative adjustment offset to `scrapAccount` with reason; unscrap = mirrored positive adjustment restoring the tracked entity, reason required, serial/lot must match the original scrap.+6. **Reason codes stay mandatory on every scrap** (universal). Instead of the Fusion/Epicor per-reason *account* mapping, keep ONE `scrapAccount` and tag scrap journal lines with dimensions (ScrapReason, WorkCenter, Employee, Item) — same analytic power, no account proliferation, per the no-matrix-config rule. (Decided by Brad, 2026-08-07 — see the spec.)++## Sources++### SAP+- https://answers.sap.com/questions/8757007/question-about-co11n.html+- https://community.sap.com/t5/enterprise-resource-planning-q-a/confirmation-co11n-scrap-rework-qty/qaq-p/3201221+- https://community.sap.com/t5/enterprise-resource-planning-q-a/reduce-order-quantity-based-on-confirmed-scrap/qaq-p/7748382+- https://blogs.sap.com/2014/02/26/different-scraps-and-their-effects-in-sap-pp/+- https://community.sap.com/t5/enterprise-resource-planning-q-a/serial-number-after-scrap/qaq-p/9931859+- https://community.sap.com/t5/product-lifecycle-management-q-a/sfc-scrap-capabilities-in-sap-digital-manufacturing/qaq-p/13623366+- https://community.sap.com/t5/enterprise-resource-planning-q-a/partial-sfc-qty-scrap-or-rework/qaq-p/10813526+- https://community.sap.com/t5/enterprise-resource-planning-q-a/how-to-scrap-issued-material/qaq-p/4818231+- https://blogs.sap.com/2020/04/28/setting-up-trigger-point-in-a-production-order/+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-members/create-production-order-without-material-for-rework/ba-p/13316098+- https://answers.sap.com/questions/10058788/account-determination-for-entry-gbb-vng-class-7920.html+- https://erproof.com/pp/sap-pp-training/sap-scrapping-process/+- http://saphelp.ucc.ovgu.de/NW750/EN/d7/efd45398184308e10000000a174cb4/content.htm (Scrap Variance)+- https://help.sap.com/docs/sap-digital-manufacturing/execution/defining-scrap-reason-codes-for-quantity-confirmation++### Oracle / NetSuite+- https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/24b/faumf/how-you-report-operation-transactions.html+- https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/24d/fapma/cost-accounting-for-manufacturing-work-orders.html+- https://docs.oracle.com/en/cloud/saas/readiness/scm/26b/mfg26b/26B-mfg-wn-f43097.htm (Redwood: Report Material Scrap)+- https://docs.oracle.com/cd/E18727-01/doc.121/e13635/T372621T374058.htm (EBS scrap/reverse-scrap entries)+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2339352.html (Work Order Completions)+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/bridgehead_1508351779.html (AM Completion Settings)+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2235043.html (Adjusting Serialized Inventory)++### Epicor / Infor / JobBOSS+- https://www.epiusers.help/t/understanding-scrap-in-kinetic/86276+- https://www.epiusers.help/t/nonconformace-dmr-proper-process/64200+- https://www.epiusers.help/t/dmr-and-inspection-processing-gl-entries/56208+- https://www.epiusers.help/t/reason-codes-type-gl-control-code/81966+- https://docs.infor.com/csi/9.01.x/en-us/csbiolh/lsm1454144795593.html (Recording Job Scrap Transactions)+- https://ipcplt.apptrix.com/syteline/language/en-us/lsm1454144443032.html (How Scrap Affects Job Cost)+- https://docs.infor.com/ln/10.6/en-us/lnolh/help/ti/onlinemanual/000523.html (Rejects of production orders)+- https://docs.infor.com/ln/10.5/en-us/lnolh/help/wh/onlinemanual/000707.html (Quarantine → rework)+- https://www.ecisolutions.com/products/jobboss2/features/mobile-apps/++### Plex / Fulcrum / Tulip+- https://plex.rockwellautomation.com/en-us/products/manufacturing-execution-system.html+- https://nal.com/wp-content/uploads/2025/01/Plex-Inventory-Training-for-Updated.pdf (SCRAP container labels)+- https://fulcrumpro.com/article/job-tracking-in-fulcrum-the-interface-for-the-shop-floor+- https://fulcrumpro.com/manufacturing-software/production-tracking-and-job-costing+- https://support.tulip.co/docs/defect-tracking-template-1++### Accounting doctrine+- https://www.dummies.com/article/business-careers-money/business/accounting/general-accounting/cost-accounting-job-costs-for-spoilage-reworked-products-and-scrap-164765/+- https://mbaknol.com/business-finance/accounting-treatment-for-material-losses-waste-scrap-and-spoilage/diff --git a/.ai/specs/2026-08-06-scrap-unscrap-flow.md b/.ai/specs/2026-08-06-scrap-unscrap-flow.mdnew file mode 100644index 0000000000..ee16978ad9--- /dev/null+++ b/.ai/specs/2026-08-06-scrap-unscrap-flow.md@@ -0,0 +1,526 @@+# Scrap & Unscrap Flow — Tracked-Entity Scrap in MES + ERP Stock Scrap/Unscrap with Full Posting++> Status: draft (autonomous-mode spec — all Open Questions resolved autonomously; review the **Autonomous:** markers before implementation)+> Author: Claude (for Brad Barbin)+> Date: 2026-08-06+> Research: `.ai/research/scrap-unscrap-flow.md` (SAP / Oracle Fusion / NetSuite / Epicor / Infor / JobBOSS / Plex / Fulcrum survey)+> Related: `.ai/specs/2026-07-14-inventory-adjustment-gl-posting.md` (shared posting core), `.ai/specs/2026-08-04-batch-split-identity-flip.md` (split conventions), `.claude/rules/traceability-model.md`, `.claude/rules/mes-job-operation-ui.md`++## TLDR++Scrap in Carbon today is a quantity bucket: MES scrap inserts a+`productionQuantity` `type='Scrap'` row and backflushes materials, but the+scrapped output never touches `trackedEntity` status, `itemLedger`, cost layers,+or the GL — and the operation's auto-Done predicate counts scrap toward+`targetQuantity`, so a scrapped serial silently shorts the job. This spec makes+scrap a first-class inventory/traceability/GL event across three surfaces,+shared by the MES **job operation view and assembly view** (which already share+`QuantityModal`, the scrap route, and the entity-scrap route):++1. **Scrap the serial unit being made** → terminal `Scrapped` status on the+ selected entity, a `Scrap` genealogy activity, materials-backflush kept,+ Dr `scrapAccount` / Cr WIP for the unit's consumed-material cost, and —+ improving on every surveyed competitor — **auto-spawn of the next serial**+ (the existing `jobOperationSerialComplete` spawn). The auto-Done+ predicate stops counting `quantityScrapped`, so the operation stays open+ until **good** quantity reaches `targetQuantity` — no target mutation.+2. **Scrap an already-made BOM part** → *Pull from Inventory*: scrap from stock+ (Dr `scrapAccount` / Cr inventory), requirement stays open so the operator+ pulls a replacement. *Make to Order*: `Scrapped` status + Dr `scrapAccount` /+ Cr WIP, plus an opt-out **replacement flow** that reopens the subassembly's+ Done operations, tops up `operationQuantity` capacity when scrap exceeds+ the planned allowance, and spawns the replacement serial ("made 3,+ scrapped 1 → make 1 more").+3. **Batch parts** → partial-quantity scrap via the batch-split convention+ (child departs `Scrapped`, parent keeps its id).++In the **ERP**, available stock gains first-class **Scrap / Unscrap** actions+(SAP 551/552 + Oracle Return-from-Scrap pattern) built on the existing+`post-inventory-adjustment` → `bookAdjustment` core with+`offsetAccount = accountDefault.scrapAccount` (already seeded), mandatory scrap+reason, `Scrapped` entity status, and unscrap reversing **at the original+scrapped cost** via `correctionOfItemLedgerId`. Every path updates inventory,+`itemLedger`, cost layers, and `journalLine`s atomically.++## Problem Statement++Verified current state (file:line refs from repo @ `new-york`):++1. **Operation-output scrap posts nothing.** `apps/mes/app/routes/x+/scrap.tsx`+ → `insertScrapQuantity` (`operations.service.ts:1516`) inserts+ `productionQuantity` `type='Scrap'`, then backflushes BOM materials via the+ `issue` edge function. No `trackedEntity` change, no `itemLedger`, no+ `costLedger`, no journal. The consumed materials sit in WIP forever (until+ `close-job` washes them to `materialVarianceAccount`).+2. **The scrapped serial still counts as done.** The auto-Done predicate+ (`sync_update_job_operation_quantities`, newest `20260706181125:91`) is+ `(quantityComplete + quantityReworked + quantityScrapped) >= targetQuantity`+ — but `targetQuantity` is defined as the **good** quantity before scrap+ (`20260119120000` column comment; `get-method` sets `operationQuantity` =+ target + planned scrap allowance). So scrap consumes good-target capacity:+ "make 3, scrap 1" flips the op Done with 2 good units and no replacement+ serial is ever created — and even *planned* scrap shorts the job (target 10+ good + 2 planned scrap auto-Dones at 8 good + 2 scrap).+3. **The only posting scrap path conflates scrap with consumption.** `issue`+ case `scrapTrackedEntity` (`functions/issue/index.ts:1682-1871`; reached only+ from `x+/entity+/$materialId.$trackedEntityId.scrap.tsx`) sets the entity+ `status='Consumed'`, posts `Consumption`/`Job Consumption` into **WIP**+ (job absorbs the loss into finished-goods cost), bumps+ `jobMaterial.quantityIssued` (so the requirement looks satisfied and no+ replacement is prompted), takes **no scrap reason**, and posts **nothing**+ for Make-to-Order materials.+4. **No terminal scrap state, no scrap ledger identity.** `trackedEntityStatus`+ = `Available|Reserved|On Hold|Consumed|Rejected` — no `Scrapped`. No `Scrap`+ value in `itemLedgerDocumentType`/`journalLineDocumentType`. Scrap is+ invisible to traceability queries and indistinguishable in the GL.+5. **No ERP stock scrap/unscrap.** The quantities page offers only+ Positive/Negative Adjmt./Set Quantity with the generic+ `inventoryAdjustmentVarianceAccount` offset; scrapping a damaged shelf part+ is indistinguishable from count shrinkage, and there is no way to restore a+ wrongly-scrapped entity.+6. **The building blocks already exist**: `accountDefault.scrapAccount`+ (`20260726012013`, seeded with fallback to+ `inventoryAdjustmentVarianceAccount`); `bookAdjustment` in+ `functions/shared/post-adjustment.ts` already accepts an `offsetAccount`+ (the header comment names scrapAccount; `post-nonconformance` uses it);+ the serial-spawn logic (`jobOperationSerialComplete`,+ `issue/index.ts:1301-1367`); the batch-split builder+ (`shared/batch-split.ts`); rework machinery (`rework` table,+ `trigger-rework` op-quantity pattern); `calculateCOGS`;+ `correctionOfItemLedgerId`; scrap reasons (`scrapReason` table ++ `productionQuantity.scrapReasonId`).++## Proposed Solution++### 0. Shared vocabulary (migration)++- `trackedEntityStatus` += **`'Scrapped'`** — terminal. Excluded everywhere+ `Rejected` is excluded (`get_inventory_quantities`,+ `get_available_tracked_entities`, `get_picking_list_tracked_available`,+ picker RPCs). Unlike `Consumed`, a `Scrapped` entity is recoverable via+ Unscrap (ERP) and is queryable for scrap analysis.+- `itemLedgerDocumentType` += **`'Scrap'`** — stamped on scrap and unscrap+ movements (unscrap = positive quantity, same documentType, linked via+ `correctionOfItemLedgerId`).+- `journalLineDocumentType` += **`'Scrap'`** (separate enum — the+ journal/ledger enums are different; lesson `journalLineDocumentType…`).+- `itemLedger.scrapReasonId` TEXT NULL, FK → `scrapReason` — reason lands on+ the movement for stock scrap (MES production scrap keeps its reason on+ `productionQuantity.scrapReasonId`).+- `trackedActivity.type` values `'Scrap'` / `'Unscrap'` (TEXT column — no enum+ change).++### 1. MES: scrap the tracked unit being made (use case 1)++New `issue` edge-function case **`jobOperationSerialScrap`** (mirror of+`jobOperationSerialComplete`, one Kysely transaction), invoked from the+existing scrap route when the parent make method is serial-tracked. The+`QuantityModal` scrap branch and `x+/scrap.tsx` are shared by+`JobOperation.tsx` and `AssemblyView.tsx`, so **both views get this by+construction** — the modal gains the selected serial's `readableId`+confirmation, keeps `ScrapReason` (required) + notes.++Transaction steps:++1. `productionQuantity` `type='Scrap'`, `scrapReasonId`, notes (unchanged+ shape; the quantity-sync interceptor keeps aggregating `quantityScrapped`).+2. Backflush the unit's BOM for the current operation+ (`issueJobOperationMaterials`) — **kept**: material cost enters WIP exactly+ as today (NetSuite "Issue for Scrap" pattern).+3. `trackedActivity` `type='Scrap'`, `sourceDocument='Job Operation'`, with+ `trackedActivityInput` (entity, qty 1); entity `status='Scrapped'`,+ attributes stamped (`Operation ${jobOperationId}`, `Scrap Reason`). The+ entity's consumed-material genealogy is preserved — the scrapped unit keeps+ its full input tree.+4. **GL** (when `accountingEnabled`): Dr `scrapAccount` / Cr+ `workInProgressAccount` for the unit's **accumulated consumed-material+ cost**: the current-op backflush cost (computed in-transaction) plus the+ cost of prior consumption ledger rows reachable from the entity's genealogy+ inputs. Labor/overhead already absorbed stay in WIP and settle via+ `close-job` variance (v1 — see Design Decision 6). `sourceType`+ `'Job Consumption'`-family journal with `documentType='Scrap'`,+ `documentId=jobId`. **Dimension tags** (Brad, 2026-08-07): every scrap+ journal line carries `journalLineDimension` rows for whichever of these+ dimensions are active on the company group — Item, ItemPostingGroup,+ Location (the adjustment precedent) **plus ScrapReason (new+ `dimensionEntityType` value, valueId = `scrapReason.id`), WorkCenter (the+ operation's `workCenterId`), and Employee (the scrapping user)** — so one+ flat `scrapAccount` slices by reason/work center/operator/item in+ reporting instead of ever needing multiple scrap accounts.+5. **Spawn the next serial** (the user-visible headline): same+ `getNextSerialNumbers` + `Reserved`-entity insert as+ `jobOperationSerialComplete:1301-1367`, spawned whenever good (non-Scrapped)+ entities for the make method < the good quantity still required. Return+ `newTrackedEntityId`; the client navigates to it exactly as the complete+ flow does.+6. **Auto-Done predicate fix + reopen** (Brad, 2026-08-07): the migration+ redefines `sync_update_job_operation_quantities` (fork the **newest** body,+ `20260706181125`) so the Done predicate becomes+ `(quantityComplete + quantityReworked) >= targetQuantity` — scrap no longer+ counts toward the good target. `targetQuantity` is already the good+ quantity (`20260119120000`), so an operation now stays open until the good+ units are actually made; no `targetQuantity` mutation on scrap, ever.+ In the scrap transaction itself:+ - Reopen `status='Done'` operations of the affected `jobMakeMethod` to+ `'Ready'` — the replacement unit must pass through **all** operations,+ not just the current one. (A reopened op re-flips Done via the+ interceptor as soon as the replacement's quantities are recorded.)+ - **Capacity top-up only beyond plan**: when cumulative actual scrap+ exceeds the planned allowance (`operationQuantity − targetQuantity`),+ bump `operationQuantity` by the excess, bump `job.scrapQuantity`+ likewise when the make method is the root (keeps the generated+ `job.productionQuantity` and serial planning coherent), and refresh the+ make method's `jobMaterial` estimated quantities+ (`quantityPerParent × new operationQuantity` — mirroring+ `recalculateJobRequirements` math, which is ERP-side and unavailable in+ Deno). Within the allowance, capacity already exists — no writes.+ - Reschedule via the same invoke `trigger-rework` uses.++**Batch parent being made**: scrap quantity `q` is recorded as+`productionQuantity` `type='Scrap'` (as today) + the same WIP→scrap GL leg for+`q` units' material cost; the in-progress lot's `trackedEntity.quantity` only+ever receives good quantity at `jobOperationBatchComplete`, so no entity write+is needed pre-completion; the §1.6 reopen/top-up applies identically (no+serial spawn — the lot absorbs the replacement quantity).++### 2. MES: scrap an already-made BOM part (use case 2)++Rework of `issue` case **`scrapTrackedEntity`** (route+`x+/entity+/$materialId.$trackedEntityId.scrap.tsx`, reachable from the+Materials section of both views). Payload gains required `scrapReasonId` and+`makeReplacement: boolean`. Branches by `jobMaterial.methodType`:++- **Pull from Inventory / Purchase to Order** (the part physically came from+ stock): the part is scrapped **from stock**, not consumed into the job:+ - `itemLedger` `entryType='Negative Adjmt.'`, `documentType='Scrap'`,+ `scrapReasonId`, negative quantity at the entity's actual on-hand bin+ (`resolveTrackedEntityBin` — lesson: never `.find(...)?.storageUnitId`).+ - Cost layers via `calculateCOGS`; GL Dr `scrapAccount` / Cr inventory+ (`resolveInventoryAccount`) through the shared `bookAdjustment` core.+ - Entity `status='Scrapped'`; `trackedActivity` `type='Scrap'` with the+ entity as input (and `parentTrackedEntityId` output when passed, as today).+ - **`jobMaterial.quantityIssued` is NOT bumped** (behavior change — today it+ is): the requirement stays open, so the operator issues a replacement from+ stock ("just scrap the part" + pull another). Batch partial scrap uses+ `buildBatchSplitRecords` — the departing child becomes the `Scrapped`+ entity; the parent keeps its id (spec `2026-08-04`).+- **Make to Order** (a subassembly made inside this job — never in inventory):+ - No stock ledger row (correct today, kept — its cost is already in WIP).+ - Entity `status='Scrapped'` + `Scrap` activity (today: `Consumed` ++ attribute).+ - GL: Dr `scrapAccount` / Cr WIP at the subassembly's accumulated+ consumed-material cost (same valuation rule as §1.4 — it *is* a unit being+ made, one level down).+ - **Replacement flow** when `makeReplacement` (modal checkbox, default ON —+ "made 3, scrapped 1 → make 1 more"): apply §1.6's reopen/top-up to the+ subassembly's `jobMakeMethod` (reopen its Done ops; bump+ `operationQuantity` + material estimates only for scrap beyond the planned+ allowance — `targetQuantity` untouched) and spawn the replacement+ `Reserved` serial entity (serial) — batch lots need only the reopen. The+ subassembly's ops won't re-flip Done until the replacement's good quantity+ reaches their target (§1.6 predicate). Record a+ `rework` row (`triggeredAtJobOperationId` = the operation the scrap came+ from, `targetJobOperationId` = the subassembly's first operation,+ `reason` = scrap reason name) so the existing rework surfaces show it.++### 3. ERP: scrap / unscrap available stock++Extends `post-inventory-adjustment` + `shared/post-adjustment.ts` (no new+edge function):++- Payload `adjustmentType` gains **`'Scrap'`** and **`'Unscrap'`**;+ `scrapReasonId` required for **Scrap only** — Unscrap inherits the reason from+ the original scrap movement it reverses (falls back to any supplied reason,+ then null), so the operator never re-enters it; `unscrapOfItemLedgerId`+ optional (set by the Unscrap UI).+- **Scrap** = the existing negative-adjustment machinery with:+ `offsetAccount = accountDefault.scrapAccount` (runtime fallback to+ `inventoryAdjustmentVarianceAccount`, per the seed comment),+ `documentType='Scrap'`, `scrapReasonId` on the ledger row; tracked entity →+ `status='Scrapped'` keeping its `quantity` (the record of what was+ scrapped), `trackedActivity` `type='Scrap'`. Serial = whole entity; batch =+ partial via the split convention (departing child is `Scrapped`). Journal+ lines carry the §1.4 dimension set minus WorkCenter (no operation context);+ Employee = the adjusting user.+- **Unscrap** (Oracle Return-from-Scrap pattern) = mirrored positive movement:+ - Tracked: select a `Scrapped` entity → `status='Available'`, positive+ `itemLedger` (`documentType='Scrap'`,+ `correctionOfItemLedgerId` = the original scrap row, same bin), cost layer+ + journal (Dr inventory / Cr `scrapAccount`) **at the original scrapped+ cost** read from the linked scrap movement's `costLedger` — not current+ cost (Fusion precedent; avoids P&L leakage on round-trips).+ - Untracked: positive adjustment with `scrapAccount` offset at current cost+ (v1 — no original-movement linkage to reverse against).+- **UI** (copy the adjustment-drawer precedent,+ `x+/inventory+/quantities+/$itemId.adjustment.tsx`):+ - The adjustment form's type select gains **Scrap** (shows required+ `ScrapReason` + notes).+ - The item's tracking view gains a **Scrapped** filter listing `Scrapped`+ entities with an **Unscrap** row action (optional comment + confirm; the+ reason is inherited from the original scrap movement, not re-entered).+ - Detail overlays follow the Drawer convention. All new strings through+ Lingui. Permission: `inventory_update` (same as adjustments today);+ MES scrap routes stay `production_update`-gated.++### 4. Ripple updates++- Status-aware readers: add `'Scrapped'` to every exclusion that lists+ `'Rejected'` (`get_inventory_quantities`, availability/picking RPCs,+ `TrackedEntityPicker` filters). Grep for `'Rejected'` in migrations + app+ code; redefine touched SQL functions by forking the **newest** body+ (grep-all-migrations lesson).+- `complete_job_to_inventory` is untouched: it keys on `quantityComplete`+ (good units only) and its serial loop reads `Reserved` entities — a+ `Scrapped` entity never reaches Assembly Output. Verify the serial-selection+ predicate excludes `Scrapped` explicitly.+- MES `getNextIncompleteSerialEntity` / `isSerialEntityIncompleteForOperation`+ treat `Scrapped` like `Consumed` (skip).+- App-side mirrors of the Done predicate: `InspectionView.tsx:385` computes+ `opRemaining = target − complete − scrapped − reworked` — drop the+ `quantityScrapped` term to match the new predicate; sweep every+ `quantityScrapped` usage in remaining/progress/Done math across MES + ERP+ (display-only usages like the JobDag badge and step-record navigation+ `operationQuantity + quantityScrapped` stay).+- Docs: `docs/` production + inventory pages; `.claude/rules/`+ traceability-model + inventory-system + mes-job-operation-ui updates; ERP+ `ProductionQuantityForm` (the ERP mirror of the MES modal) keeps working —+ it writes `productionQuantity` only and is out of scope for entity effects.++### Design Decisions++| # | Decision | Choice | Rationale |+|---|----------|--------|-----------|+| 1 | Multi-tenancy (heuristic 1) | No new tables. Every write carries `companyId` + audit fields; edge-function payloads require `userId` (zod) | House convention; null-audit-column lesson |+| 2 | Service shape (heuristic 2) | Posting logic in `issue` cases + `shared/post-adjustment.ts`; ERP/MES services stay thin `{data,error}` wrappers | Matches `post-*` family + adjustment-spec precedent |+| 3 | RLS (heuristic 3) | N/A — no new tables; new column/enum values inherit existing policies | — |+| 4 | Permissions (heuristic 4) | MES scrap: `production_update` (existing routes); ERP scrap/unscrap: `inventory_update` | Scrapping stock is an inventory action; shop-floor scrap is production |+| 5 | Forms (heuristic 5) | Extend `QuantityModal` scrap branch, entity-scrap modal, ERP adjustment form — `ValidatedForm` + zod validators, `scrapReasonId` required on every scrap | Fulcrum one-tap UX; reason mandatory is universal consensus |+| 6 | WIP scrap valuation | Materials-only at report time (Dr scrap / Cr WIP for consumed-material cost from genealogy); labor/overhead stay in WIP → `close-job` variance. Full cost-through-operation (SyteLine) deferred | Deterministic and implementable now; Carbon already has close-variance machinery; avoids per-unit labor attribution |+| 7 | Terminal status | New `Scrapped` status, not `Consumed`/`Rejected` reuse | Scrapped ≠ consumed-into-parent; unscrap must find them; Epicor SCRAPPED / SAP ME precedent |+| 8 | Replacement is explicit, effects are in-txn | Serial-being-made: spawn always (the user's ask; beats all competitors). MTO subassembly: `makeReplacement` checkbox default ON. Capacity writes only when scrap exceeds the planned allowance (`operationQuantity` + `job.scrapQuantity` top-up) | Universal "no auto-inflation" consensus, adapted — the operator action IS the explicit trigger |+| 9 | Reopen ops vs clone ops | Reopen Done ops on the same routing; `targetQuantity` never mutated; `operationQuantity` topped up only beyond the planned allowance | `trigger-rework`'s cloned path is for re-work of existing units; a replacement is new work on the same method |+| 10 | Stock-component scrap accounting | Dr `scrapAccount` / Cr inventory (not through WIP); `quantityIssued` not bumped | "Just scrap the part" + pull another; scrap loss is cost-of-quality, not product cost; SAP reverse-and-scrap pattern collapsed to one movement |+| 11 | Unscrap cost | Original scrapped cost via `correctionOfItemLedgerId` linkage (tracked); current cost (untracked v1) | Fusion Return-from-Scrap; NetSuite's current-cost reversal is a documented audit weakness |+| 12 | Scrap offset account | ONE flat `accountDefault.scrapAccount` (by id), both directions; analysis via `journalLineDimension` tags (ScrapReason / WorkCenter / Employee / Item / ItemPostingGroup / Location) — per-reason account mapping **rejected**, not deferred (Brad, 2026-08-07) | Account exists (`20260726012013`); no-matrix-config rule; dimensions give Fusion-grade reporting without account proliferation |+| 13 | Ledger identity | `documentType='Scrap'` + `itemLedger.scrapReasonId`; entry types stay `Positive/Negative Adjmt.` (no new `itemLedgerType`) | Additive; keeps every on-hand/valuation reader working unchanged |+| 14 | Backward compat (heuristic 7) | Additive enums/column; TWO deliberate behavior changes: (a) `scrapTrackedEntity` stops bumping `quantityIssued` and posts to scrap instead of WIP; (b) the auto-Done predicate drops `quantityScrapped` (Brad, 2026-08-07) — in-flight ops that would have auto-Done via scrap now stay open until good qty reaches target (manual Finish still available) | `targetQuantity` is already defined as the good quantity — counting scrap against it was shorting jobs even within planned scrap |+| 15 | Module layout (heuristic 6) | Additions live in existing `inventory.service.ts` / `production.service.ts` / MES services; no new modules | One service/models file per module |++## Data Model Changes++No new tables. One migration (`pnpm db:migrate:new scrap-unscrap-flow`,+HHMMSS randomized, idempotent, enum ADD VALUE outside dependent statements):++```sql+ALTER TYPE "trackedEntityStatus" ADD VALUE IF NOT EXISTS 'Scrapped';+ALTER TYPE "itemLedgerDocumentType" ADD VALUE IF NOT EXISTS 'Scrap';+ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Scrap';+ALTER TYPE "dimensionEntityType" ADD VALUE IF NOT EXISTS 'ScrapReason';++ALTER TABLE "itemLedger" ADD COLUMN IF NOT EXISTS "scrapReasonId" TEXT;+ALTER TABLE "itemLedger" DROP CONSTRAINT IF EXISTS "itemLedger_scrapReasonId_fkey";+ALTER TABLE "itemLedger" ADD CONSTRAINT "itemLedger_scrapReasonId_fkey"+ FOREIGN KEY ("scrapReasonId") REFERENCES "scrapReason"("id") ON DELETE SET NULL;+```++Follow-up statements (same migration, forked from **newest** bodies): (a)+redefine `sync_update_job_operation_quantities` (newest: `20260706181125`)+with the Done predicate+`("quantityComplete" + "quantityReworked") >= "targetQuantity"` — scrap+removed (Brad, 2026-08-07); (b) add `'Scrapped'` to the `'Rejected'`+exclusions in `get_inventory_quantities`, `get_available_tracked_entities`,+`get_picking_list_tracked_available` (list every migration touching each+function first — sibling-branch lesson). Then+`pnpm run generate:types` before typechecking. `config.toml` unchanged (no new+functions).++## API / Service Changes++- `issue` edge function: new case `jobOperationSerialScrap`; reworked case+ `scrapTrackedEntity` (reason required, `makeReplacement`, methodType+ branches per §2); shared capacity-bump helper used by both.+- `post-inventory-adjustment`: `adjustmentType` `'Scrap'`/`'Unscrap'`,+ `scrapReasonId`, `unscrapOfItemLedgerId`; `bookAdjustment` gains+ `scrapReasonId` passthrough + fixed-cost override for unscrap reversal. The+ Unscrap branch reads `scrapReasonId` off the resolved original scrap movement+ and books the ledger row, `trackedActivity`, and ScrapReason journal+ dimension with that inherited value.+- MES `x+/scrap.tsx`: routes serial-tracked parents to+ `jobOperationSerialScrap`; batch/untracked path adds the WIP→scrap GL leg.+- Entity-scrap route action: validator gains `scrapReasonId` (required) ++ `makeReplacement`.+- ERP `inventory.service.ts`: wrapper params for scrap/unscrap;+ `getTrackedEntities` filter for `Scrapped`.+- No Inngest changes. Reschedule via the existing schedule invoke.++## UI Changes++- MES `QuantityModal` (shared by both views): scrap branch shows the selected+ serial `readableId` when serial-tracked; reason already required.+- MES entity-scrap modal (Materials section, both views): adds `ScrapReason`+ (required), notes, and the `makeReplacement` checkbox (MTO only, default ON).+- ERP adjustment drawer: `Scrap` type option with reason; tracking view gains+ `Scrapped` filter + `Unscrap` row action (Drawer overlay convention,+ `size="md"`; MES additions `size="lg"`). All strings through Lingui.++## Acceptance Criteria++- [ ] **Serial WIP scrap + spawn.** Serial job qty 3 (no planned scrap): scrap+ the in-progress serial at op 2 with reason → entity `Scrapped`,+ `productionQuantity` Scrap row, a `Scrap` activity with the entity as input,+ op 1 (Done) reopens to Ready, `targetQuantity` stays 3 on every op,+ `operationQuantity` 3→4 and `job.scrapQuantity` 0→1 (scrap exceeded the+ zero planned allowance), a new `Reserved` serial exists and the view+ navigates to it; no op flips Done until its good quantity reaches 3; job+ completion receives exactly 3 to inventory.+- [ ] **Planned-scrap allowance.** Job qty 10 with 20% planned scrap+ (`targetQuantity` 10, `operationQuantity` 12): completing 8 good + scrapping+ 2 does NOT auto-Done the op (today it does); no capacity writes occur+ (within allowance); the op flips Done when good quantity reaches 10.+- [ ] **Serial WIP scrap GL + dimensions.** With accounting enabled and $40 of+ materials backflushed into the scrapped unit across ops: one balanced+ journal Dr scrapAccount $40 / Cr WIP $40, `documentType='Scrap'`; with+ Item, ScrapReason, WorkCenter, and Employee dimensions active on the+ company group, every line carries `journalLineDimension` tags for the+ item, the chosen scrap reason, the operation's work center, and the+ operator; with accounting disabled: identical ledger writes, zero journals.+- [ ] **Assembly view parity.** The same scrap (serial + entity scrap) driven+ from `/x/assembly/:id` produces byte-identical DB effects to the operation+ view.+- [ ] **Stock component scrap.** Scrap a picked (Available) batch entity qty 2+ of 5 from lineside: split per the identity-flip (parent keeps id, qty 5→3;+ child qty 2 `Scrapped`), `itemLedger` −2 `Negative Adjmt.`/`Scrap` with+ `scrapReasonId` at the lineside bin, layers consumed via `calculateCOGS`,+ Dr scrapAccount / Cr inventory at that cost, `quantityIssued` unchanged, and+ the material's issue requirement still shows the outstanding quantity.+- [ ] **MTO subassembly scrap + replacement.** Subassembly make method built 3+ serials, scrap 1 with Make Replacement ON: entity `Scrapped`, Dr scrap / Cr+ WIP at its consumed-material cost, no stock ledger row, subassembly Done ops+ reopened (`targetQuantity` unchanged; `operationQuantity` topped up only+ past the allowance), replacement `Reserved` serial spawned, a `rework` row+ recorded; with Make Replacement OFF only the scrap effects occur.+- [ ] **ERP scrap.** Scrap an Available serial entity from the quantities page+ with reason: status `Scrapped`, `itemLedger` −1 `documentType='Scrap'` ++ `scrapReasonId`, Dr scrapAccount / Cr inventory at COGS cost; entity+ disappears from on-hand, availability, and picker RPCs but appears under the+ Scrapped filter.+- [ ] **ERP unscrap at original cost.** Item cost moves $10→$12 after+ scrapping at $10: Unscrap restores the entity to `Available` at its original+ bin, positive ledger linked via `correctionOfItemLedgerId`, Dr inventory /+ Cr scrapAccount at **$10**, and a subsequent shipment consumes the restored+ layer at $10.+- [ ] **Untracked scrap/unscrap.** Untracked item: Scrap −5 with reason posts+ the scrapAccount pair; Unscrap +5 posts the mirror at current cost.+- [ ] **Batch WIP scrap.** Batch parent op `targetQuantity` 10 (no planned+ scrap): scrap 2 pre-completion → Scrap productionQuantity row, WIP→scrap GL+ for 2 units' material cost, `operationQuantity` 10→12, target stays 10, the+ op stays open until 10 good complete, lot completes with good quantity only.+- [ ] **No regressions**: a plain Negative Adjmt. still offsets to+ `inventoryAdjustmentVarianceAccount` with NULL documentType (byte-identical);+ `complete_job_to_inventory` output rows never reference `Scrapped` entities;+ picking/return sweeps ignore `Scrapped` entities.+- [ ] `pnpm run generate:types` then+ `pnpm exec turbo run typecheck --filter=erp --filter=mes` green; migration+ re-runs safely; edge-function own-file `deno check` error delta = 0.++## Risks++| Risk | Severity | Mitigation |+|------|----------|------------|+| Predicate change strands in-flight ops (good < target after scrap already counted) or fights reopened ops (premature re-flip when good already ≥ target) | High | Operator Finish still force-Dones any op; predicate only fires on productionQuantity changes (no retroactive flips); acceptance criteria pin the reopen→re-flip flow; test the last-op case (job already Completed → serial scrap blocked, entity is then stock — use ERP scrap) |+| Pre-`20260120` ops were backfilled `targetQuantity = operationQuantity` (includes planned scrap allowance) — with scrap excluded they auto-Done only at good = target-with-allowance | Med | Acceptable strictness (manual Finish covers); optional backfill for open ops (`targetQuantity = operationQuantity − plannedScrapShare`) evaluated at plan time |+| Genealogy-derived material cost is incomplete (untracked components consumed without entity linkage) | Med | Fall back to current-op backflush cost + `jobMaterial` unit estimates for prior ops; state valuation basis in the journal description; labor already excluded by decision 6 |+| Behavior change on `scrapTrackedEntity` (no `quantityIssued` bump, scrap-not-WIP posting) surprises existing users | Med | Flagged as decision 10/14 for Brad's veto; release note; the old absorb-into-job semantics remain available by issuing normally |+| `Scrapped` exclusion missed in one status-aware reader → phantom on-hand | Med | Single grep sweep for `'Rejected'` across migrations + app; fork newest function bodies; tie-out panel verifies subledger↔GL after scrap |+| Unscrap original-cost reversal when the layer was partially consumed since | Low | Reversal creates a NEW layer at original unit cost (no resurrection of the old layer); `correctionOfItemLedgerId` keeps the audit chain |+| Enum ADD VALUE + same-migration usage (Postgres restriction) | Low | ADD VALUE statements first, function redefinitions second; migration validated in a rolled-back psql txn |++## Open Questions++> All resolved autonomously (no human available mid-loop). Each is a veto+> point — review before implementation. **Ask-First flag:** items 1–2 touch+> production-critical table schemas (additive-only); per root AGENTS.md this+> spec does NOT authorize implementation until Brad approves it.++- [x] New terminal status vs reuse `Consumed`/`Rejected`? — **Autonomous:**+ add `'Scrapped'` (decision 7). Reuse would make unscrap and scrap analysis+ impossible to query and conflates distinct physical states.+- [x] Ledger identity: new `itemLedgerType` vs documentType? — **Autonomous:**+ keep `Positive/Negative Adjmt.` entry types; add `'Scrap'` documentType ++ `itemLedger.scrapReasonId` (decision 13). New entry types would ripple+ through every valuation/on-hand reader for zero information gain.+- [x] WIP scrap valuation basis? — **Autonomous:** consumed-material cost+ only, labor to close variance (decision 6). SyteLine-style full+ cost-through-operation deferred until per-unit labor attribution exists.+- [x] Does stock-component scrap absorb into the job (today's behavior) or+ post to scrap? — **Autonomous:** post to scrap, don't bump `quantityIssued`+ (decision 10) — matches the user's "just scrap the part" framing; flagged+ as the one deliberate behavior change.+- [x] Replacement mechanics: reopen + bump vs clone ops vs new job? —+ **Autonomous:** bump quantities + reopen on the same routing (decision 9);+ `trigger-rework` cloning is for reprocessing existing units, a replacement+ is new units of planned work.+- [x] Unscrap cost basis? — **Autonomous:** original scrapped cost for+ tracked, current cost for untracked v1 (decision 11, Fusion precedent).+- [x] Auto-Done predicate: exclude scrap instead of bumping targets? —+ **Answer (Brad, 2026-08-07): exclude `quantityScrapped` from the+ predicate.** Overrides the initial autonomous resolution. Cross-checked+ against the schema: `targetQuantity` is documented as the good quantity+ before scrap (`20260119120000`) and `operationQuantity` carries the planned+ allowance, so the old predicate was shorting jobs even within planned+ scrap. `targetQuantity` is never mutated by scrap; in-flight-op impact+ covered in Risks; `quantityReworked` stays in the predicate (out of scope).+- [x] Per-reason GL account mapping (Fusion/Epicor)? — **Answer (Brad,+ 2026-08-07): rejected permanently — ONE `scrapAccount`, with scrap reason+ as a journal dimension instead.** Add `dimensionEntityType` value+ `'ScrapReason'`; scrap journal lines tag ScrapReason, WorkCenter, and+ Employee alongside the existing Item / ItemPostingGroup / Location, for+ whichever dimensions the company group has active. `valueId` is+ polymorphic by design (no FK), so `scrapReason.id` slots in cleanly.++## Changelog++- 2026-08-07: Subcomponent scrap reworked to be **state-based** (Brad) — the+ original `scrapTrackedEntity` branched on `methodType` and rejected+ `Consumed` entities, but the only UI entry (the Unconsume tab) lists consumed+ subcomponents, so it never worked. Now: entity **state** drives the posting+ (`Available` → scrap from stock; `Consumed` → relieve WIP + decrement+ `jobMaterial.quantityIssued` to reopen the requirement); `methodType` only+ gates the MTO make-replacement flow. UI: a dedicated **Scrap tab** in+ `IssueMaterialModal` (`ScrapTab`) lists Available + Consumed entities for the+ material, replacing the (broken) per-row Scrap button in the Unconsume tab.+ Two judgment calls: state (not methodType) drives accounting; consumed-scrap+ decrements `quantityIssued`.+- 2026-08-07: Implemented on `mes-scrap-serial-rework-flow` — see+ `.ai/plans/2026-08-07-scrap-unscrap-flow.md`. Notable deviations from the+ plan: (1) the status-aware RPCs needed no `Scrapped` exclusion — scrap posts+ negative ledger movements and availability RPCs already filter+ `status='Available'`; (2) the serial/batch/untracked scrap consolidated into+ ONE `issue` case `jobOperationScrap`; (3) the entity-scrap route had **no UI+ caller** before this — added `ScrapEntityModal` + a Scrap action in the+ IssueMaterialModal unconsume tab; (4) `rework.trackedEntityId` no longer+ exists so it was omitted from the rework insert; (5) ERP Unscrap resolves+ location/bin/cost server-side from the scrap movement (a Scrapped+ tracked-entity row carries no location), so `locationId` is optional for+ Unscrap. Browser verification pending (Task 14).++- 2026-08-07: Auto-Done predicate now excludes `quantityScrapped` (Brad) —+ `targetQuantity` is already the good-quantity target, so ops stay open+ until good units are made; replaced the target-bump design with reopen ++ `operationQuantity` top-up beyond the planned allowance. Ripple: app-side+ predicate mirrors (`InspectionView.opRemaining`) swept; new planned-scrap+ acceptance criterion; in-flight-op risk rows added.+- 2026-08-07: Single scrap account + dimensions (Brad) — per-reason account+ mapping rejected permanently; scrap journal lines carry ScrapReason (new+ `dimensionEntityType`), WorkCenter, and Employee dimensions alongside+ Item / ItemPostingGroup / Location.+- 2026-08-06: Created (autonomous mode). Grounded in: competitor research+ (`.ai/research/scrap-unscrap-flow.md`, 4-track survey), code exploration of+ the scrap/completion/adjustment/rework machinery (`issue` cases+ `jobOperationSerialComplete:1173`/`scrapTrackedEntity:1682`,+ `sync_update_job_operation_quantities` auto-Done predicate+ `20260706181125:91`, `bookAdjustment` offset-account support,+ `accountDefault.scrapAccount` seed `20260726012013`, `trigger-rework`+ quantity pattern, batch-split identity flip). All Open Questions carry+ **Autonomous:** resolutions pending Brad's review; implementation gated on+ spec approval.diff --git a/.claude/rules/inventory-system.md b/.claude/rules/inventory-system.mdindex b9b4677f72..e1654477b0 100644--- a/.claude/rules/inventory-system.md+++ b/.claude/rules/inventory-system.md@@ -27,7 +27,8 @@ Key service functions (verified):- `getItemLedgerPage` — paginated item-ledger history for an item at a location.- `insertManualInventoryAdjustment` — thin wrapper over the **`post-inventory-adjustment`edge function** (MES has a matching wrapper in `apps/mes/app/services/inventory.service.ts`).- The edge function owns positive/negative/set-quantity resolution, tracked-entity storage-unit+ The edge function owns positive/negative/set-quantity **plus Scrap/Unscrap**+ (`.ai/specs/2026-08-06-scrap-unscrap-flow.md`) resolution, tracked-entity storage-unittransfers, expiry override, batch/serial assignment — and, in one Kysely transaction, maintains`costLedger` layers (consume via `calculateCOGS` on decreases, new layer at current cost onincreases) and posts a journal (Dr/Cr `resolveInventoryAccount` vs@@ -36,6 +37,29 @@ Key service functions (verified):(`functions/shared/post-adjustment.ts`). Storage-unit transfers post no GL. The valuationworkbench tie-out offers a **Reconcile** action (`createInventoryReconciliationJournal`) thatdrafts an adjusting journal for any residual pre-feature variance.+ **Scrap** = a `Negative Adjmt.` movement with `documentType='Scrap'` ++ `itemLedger.scrapReasonId`, offset to `accountDefault.scrapAccount` (fallback+ `inventoryAdjustmentVarianceAccount`), tracked entity → `Scrapped` (keeps its+ quantity; partial batch scrap splits per the identity-flip convention).+ **Unscrap** (Oracle Return-from-Scrap) restores a `Scrapped` entity to+ `Available` at the **original scrapped cost** (resolved from the scrap+ movement's `costLedger` via `resolve-unscrap-cost.ts`) and bin, linked by+ `correctionOfItemLedgerId`; ERP UI = the Unscrap row action on the tracked-+ entities table (`UnscrapModal`, no location and **no scrap reason** submitted —+ both resolved server-side; the reason is inherited from the original scrap+ movement so unscrap can't be mis-classified, and the UI collects only an+ optional comment).+ Scrap journals carry ScrapReason/WorkCenter/Employee dimensions; the single+ `scrapAccount` + dimensions replaces per-reason account mapping by design.+ The **ScrapReason** dimension is seeded active by default (a `dimension` row per+ company group, from `functions/lib/seed.data.ts`; backfilled to existing groups by+ `20260808114732_backfill-scrap-reason-dimension.sql`). Like CustomerType/ItemPostingGroup+ it is entity-backed — its values resolve live from the `scrapReason` table via+ `getEntityDimensionValues`/`getEntityValuesByIds` (accounting.service.ts), so adding a+ scrap reason immediately makes it a selectable/taggable dimension value with no sync step.+ A tag is only written when the entity type has an **active** `dimension` row — a scrap+ posting's ScrapReason `extraDimension` is dropped in `post-adjustment.ts` if the dimension+ was deleted/deactivated for that company group.- `correctStockMovement` — wraps the **`correct-stock-movement` edge function**: fixes anyposted `itemLedger` row by booking ONE opposite (delta) movement linked to the original'scorrection root via `itemLedger.correctionOfItemLedgerId`, carrying the ORIGINAL's@@ -110,8 +134,9 @@ item identity + material props, planning fields, and quantities `quantityOnHand`Aggregates from `itemLedger`, open `purchaseOrder(Line)`, `salesOrder(Line)`, `job`/`jobMaterial`,and `demandForecast`/`demandActual`.-Relevant enums: `itemLedgerType`, `itemLedgerDocumentType`, `trackedEntityStatus`-(`Available`, `Reserved`, `On Hold`, `Consumed`, `Rejected`), `warehouseTransferStatus`,+Relevant enums: `itemLedgerType`, `itemLedgerDocumentType` (includes `Scrap`,+`20260807090400`), `trackedEntityStatus`+(`Available`, `Reserved`, `On Hold`, `Consumed`, `Rejected`, `Scrapped`), `warehouseTransferStatus`,`itemTrackingType`, `itemReplenishmentSystem`, `itemReorderingPolicy`.## Gotchasdiff --git a/.claude/rules/mes-job-operation-ui.md b/.claude/rules/mes-job-operation-ui.mdindex 4a613d09ee..99c6e9f5da 100644--- a/.claude/rules/mes-job-operation-ui.md+++ b/.claude/rules/mes-job-operation-ui.md@@ -34,6 +34,28 @@ redirects kinds it does not serve (no loops).`path.to.endOperation(id)` (`/x/end/:operationId`); rework targets at`path.to.reworkTargets(id)`. Start/end routes write `productionEvent` /`productionQuantity` (end calls `finishJobOperation`).+- **Scrap** (`.ai/specs/2026-08-06-scrap-unscrap-flow.md`): `x+/scrap.tsx` makes+ ONE `issue` `jobOperationScrap` invoke (replacing the old+ `insertScrapQuantity` + backflush pair) — it records the Scrap+ `productionQuantity`, backflushes the unit's BOM, flips the selected serial to+ `Scrapped`, **spawns the replacement serial** (returned as `newTrackedEntityId`+ for client advancement), reopens the make method's Done ops, and posts+ Dr `scrapAccount` / Cr WIP for the consumed-material cost. Scrapping a+ **subcomponent** (serial/batch BOM part) goes through+ `x+/entity+/$materialId.$trackedEntityId.scrap.tsx` → `issue`+ `scrapTrackedEntity`, reached from a dedicated **Scrap tab** in the+ `IssueMaterialModal` (`ScrapTab` lists the material's Available + Consumed+ entities; each opens `ScrapEntityModal`). That case branches on entity+ **state**, not `methodType`: an `Available` (picked/in-stock) part scraps from+ stock (`Negative Adjmt`, Dr scrap / Cr inventory, `quantityIssued` untouched);+ a `Consumed` part relieves WIP (Dr scrap / Cr WIP at the item's unit cost) and+ **decrements `jobMaterial.quantityIssued`** so the requirement reopens for a+ replacement. MTO make-replacement (reopen routing + spawn serial + rework row)+ runs for either state. **The auto-Done predicate no longer counts+ `quantityScrapped`** (`sync_update_job_operation_quantities`, `20260807090629`) —+ scrap doesn't consume the good `targetQuantity`, so app-side remaining/Done+ mirrors (`complete.tsx` `willBeFinished`, `InspectionView`/`quality.server`+ `opRemaining`) also dropped the scrap term.- **`finishJobOperation`** (`operations.service.ts`) flips the op to `Done` (firingthe `sync_finish_job_operation` trigger that completes the job to inventory whenit's the last op). It then runs `returnPickedRemainders`: one `post-picking`diff --git a/.claude/rules/traceability-model.md b/.claude/rules/traceability-model.mdindex bc230213be..3b8ce6257b 100644--- a/.claude/rules/traceability-model.md+++ b/.claude/rules/traceability-model.md@@ -27,7 +27,7 @@ avoid an entity appearing as its own ancestor/descendant within a single activit| --- | --- || `id` TEXT | default `nanoid()` (was `xid()` originally, changed in `20250304230616`) || `quantity` NUMERIC | serial entities = 1 |-| `status` `trackedEntityStatus` | enum `'Available' \| 'Reserved' \| 'On Hold' \| 'Consumed'`, default `Available` |+| `status` `trackedEntityStatus` | enum `'Available' \| 'Reserved' \| 'On Hold' \| 'Consumed' \| 'Rejected' \| 'Scrapped'`, default `Available`. `Scrapped` (`20260807090400`) is terminal but **recoverable** via ERP Unscrap (unlike `Consumed`); excluded from on-hand/availability like `Rejected` || `sourceDocument` TEXT, `sourceDocumentId` TEXT | polymorphic provenance; for batch/serial/job-seed entities it is `'Item'` + the item id || `sourceDocumentReadableId` TEXT | denormalized `item.readableIdWithRevision`; kept in sync by an `item` AFTER-UPDATE interceptor `sync_propagate_item_readable_id_to_tracked_entity` (`20260428100000`) || `readableId` TEXT | the serial OR batch number (promoted out of `attributes` in `20251220013724`/`20251220021403`) |@@ -69,6 +69,21 @@ and MES services — NOT a single `post-production`:`trigger-rework` insert `trackedActivity` + input/output link rows on posting.- MES `startProductionEvent` (`apps/mes/app/services/operations.service.ts`) inserts a`trackedActivity` and a `trackedActivityOutput` for the production event.+- **Scrap** (`.ai/specs/2026-08-06-scrap-unscrap-flow.md`): `issue` case+ `jobOperationScrap` scraps the serial being made — `type: 'Scrap'` activity,+ entity → `Scrapped`, then **spawns the next serial** (same `getNextSerialNumbers`+ path as `jobOperationSerialComplete`) and reopens the make method's Done ops+ (`issue/scrap-replacement.ts`) so the replacement runs the full routing. `issue`+ case `scrapTrackedEntity` scraps a subcomponent, branching on entity **state**:+ an `Available` part posts a `Scrap` (`Negative Adjmt.`) `itemLedger` at its+ on-hand bin (`quantityIssued` untouched); a `Consumed` part posts Dr scrap /+ Cr WIP at the item's unit cost and **decrements `quantityIssued`** to reopen+ the requirement. Make-to-Order can additionally spawn a replacement + `rework`+ row (`makeReplacement`). ERP stock **Scrap/Unscrap** run through+ `post-inventory-adjustment` (`type: 'Unscrap'` activity restores a `Scrapped`+ entity at the original scrapped cost via `correctionOfItemLedgerId`). Every scrap+ journal is offset to `accountDefault.scrapAccount` and tagged with ScrapReason /+ WorkCenter / Employee `journalLineDimension` rows.Pattern: insert `trackedActivity`, then `trackedActivityInput` for each consumed entity and`trackedActivityOutput` for each produced entity; post `itemLedger` rows@@ -94,7 +109,10 @@ Non-strict variants exist but include same-activity siblings — prefer strict.`getTrackedEntitiesByMakeMethodId`, `getTrackedEntitiesByOperationId`,`updateTrackedEntityExpiry`, `getTrackedEntityExpirations`.- MES `operations.service.ts`: `getTrackedEntity`, `getTrackedEntitiesByMakeMethodId`,- `getTrackedInputs` (wraps the strict RPCs), `startProductionEvent`.+ `getTrackedInputs` (wraps the strict RPCs; **filters out `Scrapped` descendants** so a+ scrapped subcomponent no longer appears in the issue modal's Unconsume/Scrap lists — the+ scrap already relieved its WIP and reopened the requirement; the lineage graph still shows+ it), `startProductionEvent`.**Serial sibling clustering (display only).** A serial item at qty N produces Nqty-1 entities by design, so one job fans out into N identical nodes. The graphdiff --git a/apps/academy/app/config.tsx b/apps/academy/app/config.tsxindex e142d0399e..2ed3a80e86 100644--- a/apps/academy/app/config.tsx+++ b/apps/academy/app/config.tsx@@ -532,6 +532,15 @@ export const modules: Config = [description:"Learn how to use engineering change notices to manage and track changes to items, methods, and bills in a controlled, auditable way.",duration: 260+ },+ {+ id: "scrap",+ loomUrl:+ "https://www.loom.com/share/f69fe5573f7b4cdcb79e545ce571679e",+ name: "Scrap",+ description:+ "Learn how to scrap serials, subcomponents, and stock in Carbon, and how scrap flows through production and inventory.",+ duration: 597}],supplemental: []diff --git a/apps/erp/app/components/Icons.tsx b/apps/erp/app/components/Icons.tsxindex 96a93aefd0..c33699f389 100644--- a/apps/erp/app/components/Icons.tsx+++ b/apps/erp/app/components/Icons.tsx@@ -680,6 +680,8 @@ export const DimensionEntityTypeIcon = ({return <LuWrench className={className} />;case "Process":return <LuCog className={className} />;+ case "ScrapReason":+ return <LuTriangleAlert className={className} />;}};diff --git a/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx b/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsxindex 7f3cf14696..c44034fedf 100644--- a/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx+++ b/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx@@ -302,9 +302,6 @@ const NavigationIconLink = forwardRef<ref={ref}to={link.to}{...props}- {...(link.external- ? { target: "_blank", rel: "noopener noreferrer" }- : {})}onClick={onClick}className={cn(classes, props.className)}prefetch={link.external ? "none" : "intent"}diff --git a/apps/erp/app/modules/accounting/accounting.models.ts b/apps/erp/app/modules/accounting/accounting.models.tsindex 25ffc30ac7..1e6eeac0b2 100644--- a/apps/erp/app/modules/accounting/accounting.models.ts+++ b/apps/erp/app/modules/accounting/accounting.models.ts@@ -589,6 +589,7 @@ export const dimensionEntityTypes = ["ItemPostingGroup","Location","Process",+ "ScrapReason","Supplier","SupplierType","WorkCenter"diff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.tsindex ec72b3898c..bd220522f8 100644--- a/apps/erp/app/modules/accounting/accounting.service.ts+++ b/apps/erp/app/modules/accounting/accounting.service.ts@@ -2511,6 +2511,12 @@ function getEntityDimensionValues(.select("id, name").eq("companyId", companyId).order("name");+ case "ScrapReason":+ return client+ .from("scrapReason")+ .select("id, name")+ .eq("companyId", companyId)+ .order("name");// Customer / Supplier / Item are high-cardinality: intentionally NOT// eager-loaded here. The DimensionSelector sources their options lazily// from the client stores (useCustomers / useSuppliers / useItems).@@ -2635,6 +2641,8 @@ function getEntityValuesByIds(return client.from("itemPostingGroup").select("id, name").in("id", ids);case "CostCenter":return client.from("costCenter").select("id, name").in("id", ids);+ case "ScrapReason":+ return client.from("scrapReason").select("id, name").in("id", ids);case "FixedAssetClass":return client.from("fixedAssetClass").select("id, name").in("id", ids);case "Customer":diff --git a/apps/erp/app/modules/accounting/ui/Dimensions/DimensionForm.tsx b/apps/erp/app/modules/accounting/ui/Dimensions/DimensionForm.tsxindex 1e48b7c1eb..260e8ce4f6 100644--- a/apps/erp/app/modules/accounting/ui/Dimensions/DimensionForm.tsx+++ b/apps/erp/app/modules/accounting/ui/Dimensions/DimensionForm.tsx@@ -40,7 +40,8 @@ const entityTypeLabels: Record<string, string> = {FixedAssetClass: "Asset Class",CostCenter: "Cost Center",WorkCenter: "Work Center",- Process: "Process"+ Process: "Process",+ ScrapReason: "Scrap Reason"};const DimensionForm = ({ initialValues, onClose }: DimensionFormProps) => {diff --git a/apps/erp/app/modules/accounting/ui/JournalEntries/DimensionSelector.tsx b/apps/erp/app/modules/accounting/ui/JournalEntries/DimensionSelector.tsxindex acad527a3f..63c79b7920 100644--- a/apps/erp/app/modules/accounting/ui/JournalEntries/DimensionSelector.tsx+++ b/apps/erp/app/modules/accounting/ui/JournalEntries/DimensionSelector.tsx@@ -67,6 +67,8 @@ const entityTypeColors: Record<string, string> = {"bg-teal-100 text-teal-800 dark:bg-teal-500/15 dark:text-teal-400 border-teal-500/20",Process:"bg-cyan-100 text-cyan-800 dark:bg-cyan-500/15 dark:text-cyan-400 border-cyan-500/20",+ ScrapReason:+ "bg-rose-100 text-rose-800 dark:bg-rose-500/15 dark:text-rose-400 border-rose-500/20",Custom: ""};diff --git a/apps/erp/app/modules/agent/kb/docs/reference/inventory.md b/apps/erp/app/modules/agent/kb/docs/reference/inventory.mdindex ecdaa03ad0..bdcbe9df24 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/inventory.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/inventory.md@@ -25,7 +25,7 @@ On hand can go **negative**. Shipping, issuing to a job, and picking all post th## Movements-Two kinds of transfer move stock. A **warehouse transfer** moves it between locations, and is carried out as a shipment out of one and a receipt into the other. A **stock transfer** moves it within a single location, between storage units. A manual **adjustment** posts a positive or negative entry to the ledger, or a *Set Quantity* that books the difference to a target. When accounting is enabled, every adjustment also posts a journal: a loss debits the inventory adjustment account and credits inventory, a gain is the mirror image, valued at the item's current cost. Inventory count variances post the same way. Moving stock between storage units posts no journal, because the value never left the location.+Two kinds of transfer move stock. A **warehouse transfer** moves it between locations, and is carried out as a shipment out of one and a receipt into the other. A **stock transfer** moves it within a single location, between storage units. A manual **adjustment** posts a positive or negative entry to the ledger, or a *Set Quantity* that books the difference to a target. When accounting is enabled, every adjustment also posts a journal: a loss debits the inventory adjustment account and credits inventory, a gain is the mirror image, valued at the item's current cost. Inventory count variances post the same way. Moving stock between storage units posts no journal, because the value never left the location. `docs/reference/scrap` stock is a negative adjustment with a reason, offset to the scrap account instead of the adjustment account.## Correcting a movementdiff --git a/apps/erp/app/modules/agent/kb/docs/reference/jobs.md b/apps/erp/app/modules/agent/kb/docs/reference/jobs.mdindex 7fac0e6f18..3e8b989412 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/jobs.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/jobs.md@@ -62,7 +62,7 @@ The **order** field sets each operation's position, and operation order (*After### Time and output-The floor reports two separate things against an operation. A production event measures *time*, typed **Setup**, **Labor**, or **Machine**, with a start, an end, and the employee. A production quantity measures *units* (**Production**, **Scrap**, or **Rework**) and rolls up automatically into the operation's completed, scrapped, and reworked totals. Logging time implies no output, and reporting output implies no particular time, which is what lets Carbon cost on actual events while measuring yield on actual quantities. Untracked materials are backflushed as output is reported; tracked materials are issued deliberately.+The floor reports two separate things against an operation. A production event measures *time*, typed **Setup**, **Labor**, or **Machine**, with a start, an end, and the employee. A production quantity measures *units* (**Production**, `docs/reference/scrap`, or **Rework**) and rolls up automatically into the operation's completed, scrapped, and reworked totals. Scrapped units don't count toward the target, so the operation keeps going until the good quantity is met. Logging time implies no output, and reporting output implies no particular time, which is what lets Carbon cost on actual events while measuring yield on actual quantities. Untracked materials are backflushed as output is reported; tracked materials are issued deliberately.### Proceduresdiff --git a/apps/erp/app/modules/agent/kb/docs/reference/mes.md b/apps/erp/app/modules/agent/kb/docs/reference/mes.mdindex df3a54d504..77f7127fec 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/mes.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/mes.md@@ -55,7 +55,7 @@ Open an operation and the station panel is where the shift actually happens. A bGood, bad, and reworked units are reported separately, so yield stays honest:- **Log Completed**: Records good units off this operation. **"Complete All"** fills the remaining quantity; **"Total Quantity"** sets it explicitly.- - **Log Scrap**: Records scrapped units against a required **"Scrap Reason"**, so the loss is attributable.+ - **Log Scrap**: Records scrapped units against a required **"Scrap Reason"**, so the loss is attributable. The unit flips to **"Scrapped"**, a replacement is spawned, and the routing reopens — see `docs/reference/scrap`.- **Log Rework**: Records units reworked in place at this operation, without sending them anywhere.Reworking *in place* is different from sending a unit back upstream. **"Create Rework"** does the latter: pick an operation under **"Go back to operation"**, give a **"Reason for rework"**, and Carbon re-runs every operation from that point forward to the current one.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/scrap.md b/apps/erp/app/modules/agent/kb/docs/reference/scrap.mdnew file mode 100644index 0000000000..dbf0c53378--- /dev/null+++ b/apps/erp/app/modules/agent/kb/docs/reference/scrap.md@@ -0,0 +1,55 @@+# Scrap and unscrap++> Writing off defective or lost material, and restoring it if the write-off was a mistake.++Scrap is how Carbon records material you can't recover: a unit ruined at an operation, a subcomponent that failed, or stock lost in the warehouse. Every scrap names a **reason**, moves the value off inventory or out of work-in-process, and (when accounting is on) posts a journal. If you scrapped in error, **Unscrap** puts it back exactly as it was.++There are three places you can scrap, and they behave differently. What they share: the affected tracked entity ends at status **"Scrapped"**, which keeps its quantity as the record of what was lost and, unlike **"Consumed"** or **"Rejected"**, can be reversed.++## Scrapping a unit on the floor++When the unit you're building goes bad, an operator taps **"Log Scrap"** on the operation, enters a quantity, and picks a required **"Scrap Reason"**. For a Serial part the currently selected serial is the one scrapped.++Carbon records a **Scrap** production quantity, backflushes the unit's bill of material into WIP (the material really was consumed making the ruined unit), flips the serial to **"Scrapped"**, and spawns a fresh replacement serial for you to keep working.++A scrapped unit is not treated as output. Its quantity never counts toward the operation's target, completed operations reopen to **"Ready"**, and a replacement serial is spawned automatically, so the job keeps producing until the *good* quantity meets the target. The planned quantity itself is never rewritten; Carbon only tops up the operation's run quantity when cumulative scrap runs past the allowance you planned for.++## Scrapping a subcomponent++A component that was picked or already issued into the unit is scrapped from the **"Scrap"** tab of the issue-material dialog, which lists that material's **Available** and **Consumed** tracked entities. Each row's **"Scrap"** button opens a dialog for the reason and, for a make-to-order component, an optional **"Make a replacement"**.++What posts depends on the entity's *state*, not the item's method:++An **Available** part is scrapped straight out of its bin as a negative adjustment, and the job's issued quantity is left untouched. A **Consumed** part is relieved from the job's WIP at its unit cost, and the material's issued quantity is decremented so the requirement reopens for a replacement. Either way the entity ends at **"Scrapped"**; make-to-order can additionally reopen the subassembly's routing and spawn a replacement with a rework row.++## Scrapping stock++Warehouse stock that never reached a job is scrapped from the storage-unit adjustment form: set the adjustment type to **"Scrap"** and pick a **"Scrap Reason"**. This books a negative movement at the item's cost. A serial flips to **"Scrapped"** and keeps its quantity; scrapping part of a batch splits the lot, and only the scrapped portion becomes **"Scrapped"**.++## Unscrap++Unscrap reverses a scrap. On the tracked-entities table, the **"Unscrap"** action appears on any row at status **"Scrapped"** (filter the status column to **"Scrapped"** to find them). It restores the entity to **"Available"** at the same bin, and asks only for an optional comment.++Unscrap restores the entity at the exact cost it was scrapped from, read back from the original scrap's cost layers, so a scrap-then-unscrap nets to nothing in the ledger. You don't re-enter the reason either; Carbon inherits it from the scrap movement it's reversing, and links the restoring entry back to that movement. (Untracked stock is the one exception: it comes back at current cost and needs a location.)++## Accounting for scrap++Scrap posts to the ledger only when `docs/reference/accounting` is enabled; the stock and cost layers move regardless. Every path debits a single **scrap account** (`accountDefault.scrapAccount`, which falls back to the inventory adjustment variance account). Where the credit lands depends on where the value was:++| Scrap path | Debit | Credit |+| --- | --- | --- |+| Unit on the floor | Scrap | Work-in-process |+| Consumed subcomponent | Scrap | Work-in-process |+| Available subcomponent, or stock | Scrap | Inventory |+| Unscrap | Inventory | Scrap |++Carbon deliberately posts all scrap to one account rather than a per-reason chart of accounts. It tags each scrap journal line with **ScrapReason**, **WorkCenter**, and **Employee** dimensions (work center only where there's an operation behind the scrap), so you slice scrap by reason, cell, or operator in reporting without proliferating accounts. The ScrapReason dimension reads its values live from your scrap-reason list, so a new reason is immediately reportable.++This scrap is distinct from a quality **disposition** of *Scrap*: closing a quality `docs/reference/issues` with a Scrap disposition writes the material off to a cost-of-quality account and flips the entity to **"Rejected"**, not **"Scrapped"**.++## Related++ - Traceability The tracked-entity statuses, including Scrapped, and the Unscrap action.+ - Jobs Production quantities and how scrap is reported against an operation.+ - Inventory The item ledger and manual adjustments scrap posts against.+ - Accounting The journal, the scrap account, and posting dimensions.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/traceability.md b/apps/erp/app/modules/agent/kb/docs/reference/traceability.mdindex d0b6a6d5f7..40c4b9ddc3 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/traceability.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/traceability.md@@ -13,6 +13,7 @@ A **tracked entity** is a tracked quantity of an item. A **Serial** item gets on- **On Hold**: Received but not yet released (awaiting inspection).- **Consumed**: Issued to a job or shipped out.- **Rejected**: Failed inspection.+ - **Scrapped**: Written off as unrecoverable, with a reason. Unlike Consumed and Rejected, it can be reversed with `docs/reference/scrap`.## Where entities come from@@ -32,3 +33,4 @@ Tracked items can carry a **shelf life**: a fixed duration, a date set at receip- Jobs Where entities are consumed and produced as a job runs.- Quality Inspection holds and rejects tracked entities.+ - Scrap and unscrap Writing an entity off to Scrapped, and restoring it.diff --git a/apps/erp/app/modules/agent/kb/guides/job-costing.md b/apps/erp/app/modules/agent/kb/guides/job-costing.mdindex ea0fb24145..58dae129d3 100644--- a/apps/erp/app/modules/agent/kb/guides/job-costing.md+++ b/apps/erp/app/modules/agent/kb/guides/job-costing.md@@ -26,7 +26,7 @@ That material reaches WIP one of two ways, and the difference is *when*. **IssuiThe posting is identical either way (cost out of inventory, into WIP), so the choice is about floor discipline, not accounting. Issue as you go when you need tight control over what's consumed; lean on backflush for the routine material you'd rather not hand-count.-Scrap and rework are recorded as their own production quantities, but scrapping a tracked part posts the same consumption: out of inventory, into the job's WIP. There's no separate scrap account; the cost of what you ruined rides along in the job until it settles at close.+Scrap and rework are recorded as their own production quantities. Scrapping a tracked part relieves its cost from the job: debited to a dedicated scrap account and credited out of WIP (or straight out of inventory, for a part still in stock), tagged with the reason, work center, and operator. The ruined value leaves the job rather than riding along to close, and the scrap reopens the routing so a replacement gets built. See `docs/reference/scrap`.## WIP isn't a tablediff --git a/apps/erp/app/modules/agent/kb/manifest.json b/apps/erp/app/modules/agent/kb/manifest.jsonindex efcca2e51b..befc266d84 100644--- a/apps/erp/app/modules/agent/kb/manifest.json+++ b/apps/erp/app/modules/agent/kb/manifest.json@@ -1314,6 +1314,20 @@"Related"]},+ {+ "slug": "docs/reference/scrap",+ "title": "Scrap and unscrap",+ "description": "Writing off defective or lost material, and restoring it if the write-off was a mistake.",+ "keywords": ["scrap", "and", "unscrap", "docs", "reference"],+ "headings": [+ "Scrapping a unit on the floor",+ "Scrapping a subcomponent",+ "Scrapping stock",+ "Unscrap",+ "Accounting for scrap",+ "Related"+ ]+ },{"slug": "docs/reference/sequences","title": "Numbering sequences",diff --git a/apps/erp/app/modules/inventory/AGENTS.md b/apps/erp/app/modules/inventory/AGENTS.mdindex f034f5d3dd..3cd77ba3bf 100644--- a/apps/erp/app/modules/inventory/AGENTS.md+++ b/apps/erp/app/modules/inventory/AGENTS.md@@ -5,7 +5,7 @@ Tracks item quantities across locations and storage units. Manages receipts, shi## Key Domain Concepts- **Storage Unit** — hierarchical container (bin, shelf, rack, zone) within a location. Tree structure via `parentId`. Renamed from `shelf` in migration `20260417000100`. MUST use `storageUnit` naming, never `shelf`.-- **Tracked Entity** — serial/batch/lot-tracked item instance with `readableId` (serial or batch number), `status` (Available/Reserved/On Hold/Consumed/Rejected), `quantity`, and `expirationDate`. Batch items have `batchProperty` definitions.+- **Tracked Entity** — serial/batch/lot-tracked item instance with `readableId` (serial or batch number), `status` (Available/Reserved/On Hold/Consumed/Rejected/Scrapped), `quantity`, and `expirationDate`. `Scrapped` is terminal but recoverable via the Unscrap adjustment. Batch items have `batchProperty` definitions.- **Item Ledger** — append-only log of every inventory movement (`itemLedger` table). Source of truth for on-hand quantities. MUST never INSERT directly — always go through service functions.- **Receipt** — inbound inventory from POs or production. Lines link to `purchaseOrderLine` or jobs. Posting creates ledger entries and tracked entities.- **Shipment** — outbound inventory to customers. Lines link to sales order lines.diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.tsindex 3bd1608958..94cea2e0a9 100644--- a/apps/erp/app/modules/inventory/inventory.models.ts+++ b/apps/erp/app/modules/inventory/inventory.models.ts@@ -59,7 +59,8 @@ export const trackedEntityStatus = ["Consumed","On Hold","Reserved",- "Rejected"+ "Rejected",+ "Scrapped"] as const;export const replenishmentSystemTypes = [@@ -153,15 +154,31 @@ export const inventoryCountLineValidator = z.object({export const inventoryAdjustmentValidator = z.object({itemId: z.string().min(1, { message: "Item ID is required" }),- locationId: z.string().min(1, { message: "Location is required" }),+ // Required for every adjustment except Unscrap, where the edge function+ // resolves the location from the original scrap movement (a Scrapped+ // tracked-entity row carries no location). Enforced in the refine below.+ locationId: zfd.text(z.string().optional()),storageUnitId: zfd.text(z.string().optional()),originalStorageUnitId: zfd.text(z.string().optional()),- adjustmentType: z.enum([...itemLedgerTypes, "Set Quantity"]),+ adjustmentType: z.enum([+ ...itemLedgerTypes,+ "Set Quantity",+ "Scrap",+ "Unscrap"+ ]),quantity: zfd.numeric(z.number()),trackedEntityId: zfd.text(z.string().optional()),readableId: zfd.text(z.string().optional()),expirationDate: zfd.text(z.string().optional()),comment: zfd.text(z.string().optional()),+ // Required for Scrap (enforced below); lands on the itemLedger row and,+ // when accounting is enabled, as a ScrapReason journal dimension. Unscrap+ // omits it — the edge function inherits the reason from the original scrap+ // movement it reverses.+ scrapReasonId: zfd.text(z.string().optional()),+ // Unscrap: the original scrap movement to reverse against (resolved+ // server-side from the tracked entity when omitted).+ unscrapOfItemLedgerId: zfd.text(z.string().optional()),// Set by serial-tracked forms so the quantity can be capped server-side.requiresSerialTracking: zfd.text(z.string().optional())@@ -177,6 +194,20 @@ export const inventoryAdjustmentValidator = zmessage: "Serial items can only have a quantity of 1"});}+ if (data.adjustmentType === "Scrap" && !data.scrapReasonId) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["scrapReasonId"],+ message: "Scrap reason is required"+ });+ }+ if (data.adjustmentType !== "Unscrap" && !data.locationId) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["locationId"],+ message: "Location is required"+ });+ }});// Corrects a posted stock movement: the user enters the SIGNED quantity thediff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsxindex 4a55755aaa..e5a27548e3 100644--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx@@ -57,6 +57,7 @@ import type { z } from "zod";import { DateTime } from "~/components";import { Enumerable } from "~/components/Enumerable";import { Input, Location, Select, TextArea } from "~/components/Form";+import ScrapReason from "~/components/Form/ScrapReason";import StorageUnit from "~/components/Form/StorageUnit";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";import { usePermissions, usePrinting } from "~/hooks";@@ -171,6 +172,7 @@ const InventoryStorageUnits = ({null);const [isEditingRow, setIsEditingRow] = useState(false);+ const [adjustmentType, setAdjustmentType] = useState<string>("Set Quantity");const isEditing = selectedTrackedEntityId !== null;@@ -208,6 +210,11 @@ const InventoryStorageUnits = ({setSelectedTrackedEntityId(trackedEntityId || null);setSelectedReadableId(readableId || null);setIsEditingRow(storageUnitId !== undefined);+ // A new serial adjustment has no "Set Quantity" option (see the options list+ // below), so default it to a valid choice instead of an unselectable one.+ setAdjustmentType(+ isSerial && !trackedEntityId ? "Positive Adjmt." : "Set Quantity"+ );if (currentQuantity !== undefined) {setQuantity(currentQuantity);}@@ -487,7 +494,8 @@ const InventoryStorageUnits = ({originalStorageUnitId: isEditing? selectedStorageUnitId || undefined: undefined,- adjustmentType: "Set Quantity",+ adjustmentType:+ isSerial && !isEditing ? "Positive Adjmt." : "Set Quantity",trackedEntityId: selectedTrackedEntityId || nanoid(),readableId: selectedReadableId || undefined,expirationDate: defaultExpirationDate@@ -518,6 +526,9 @@ const InventoryStorageUnits = ({name="adjustmentType"label={t`Adjustment Type`}termId="inventory-adjustment-type"+ onChange={(option) =>+ setAdjustmentType(option?.value ?? "Set Quantity")+ }options={isEditing && (isSerial || isBatch)? [@@ -525,7 +536,8 @@ const InventoryStorageUnits = ({{label: t`Negative Adjustment`,value: "Negative Adjmt."- }+ },+ { label: t`Scrap`, value: "Scrap" }]: [...(isSerial@@ -543,10 +555,14 @@ const InventoryStorageUnits = ({{label: t`Negative Adjustment`,value: "Negative Adjmt."- }+ },+ { label: t`Scrap`, value: "Scrap" }]}/>+ {adjustmentType === "Scrap" && (+ <ScrapReason name="scrapReasonId" label={t`Scrap Reason`} />+ )}{(isBatch || isSerial) && (<><Hidden name="trackedEntityId" />diff --git a/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsx b/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsxindex 9e75c0d3f7..d0a8f93f8c 100644--- a/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsx+++ b/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsx@@ -13,6 +13,7 @@ import {LuHash,LuNetwork,LuQrCode,+ LuRotateCcw,LuTriangleAlert} from "react-icons/lu";import { useNavigate } from "react-router";@@ -28,6 +29,7 @@ import { path } from "~/utils/path";import { EditExpiryModal } from "./EditExpiryModal";import { ExpiryTracePopover } from "./ExpiryTracePopover";import TrackedEntityStatus from "./TrackedEntityStatus";+import { UnscrapModal } from "./UnscrapModal";type ShelfLifePolicy = {mode: string;@@ -59,6 +61,7 @@ const TrackedEntitiesTable = memo(// Edit-expiry modal state. Holds the entity being edited so the modal// can pre-fill its form. Lives at table level so the row context-menu// action can open it.+ const [unscrapping, setUnscrapping] = useState<TrackedEntity | null>(null);const [editingExpiry, setEditingExpiry] = useState<TrackedEntity | null>(null);@@ -244,6 +247,17 @@ const TrackedEntitiesTable = memo(<MenuIcon icon={<LuCalendarCog />} /><Trans>Edit Expiry</Trans></MenuItem>+ {row.status === "Scrapped" && (+ <MenuItem+ disabled={+ !permissions.can("update", "inventory") || !row.itemId+ }+ onClick={() => setUnscrapping(row)}+ >+ <MenuIcon icon={<LuRotateCcw />} />+ <Trans>Unscrap</Trans>+ </MenuItem>+ )}</>);},@@ -268,6 +282,23 @@ const TrackedEntitiesTable = memo(label={editingExpiry.sourceDocumentReadableId ?? editingExpiry.id}/>)}+ {unscrapping &&+ unscrapping.itemId &&+ Number.isFinite(Number(unscrapping.quantity)) &&+ Number(unscrapping.quantity) > 0 && (+ <UnscrapModal+ open={!!unscrapping}+ onClose={() => setUnscrapping(null)}+ itemId={unscrapping.itemId}+ trackedEntityId={unscrapping.id}+ quantity={Number(unscrapping.quantity)}+ label={+ unscrapping.readableId ??+ unscrapping.sourceDocumentReadableId ??+ unscrapping.id+ }+ />+ )}</>);}diff --git a/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntityStatus.tsx b/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntityStatus.tsxindex 9715aad579..ee0887f240 100644--- a/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntityStatus.tsx+++ b/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntityStatus.tsx@@ -41,6 +41,12 @@ function TrackedEntityStatus({ status }: TrackedEntityStatusProps) {<Trans>Consumed</Trans></Status>);+ case "Scrapped":+ return (+ <Status color={color}>+ <Trans>Scrapped</Trans>+ </Status>+ );default:return null;}diff --git a/apps/erp/app/modules/inventory/ui/Traceability/UnscrapModal.tsx b/apps/erp/app/modules/inventory/ui/Traceability/UnscrapModal.tsxnew file mode 100644index 0000000000..4093242766--- /dev/null+++ b/apps/erp/app/modules/inventory/ui/Traceability/UnscrapModal.tsx@@ -0,0 +1,92 @@+import { ValidatedForm } from "@carbon/form";+import {+ Button,+ Modal,+ ModalBody,+ ModalContent,+ ModalDescription,+ ModalFooter,+ ModalHeader,+ ModalTitle,+ VStack+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { Hidden, Submit, TextArea } from "~/components/Form";+import { inventoryAdjustmentValidator } from "~/modules/inventory";+import { path } from "~/utils/path";++type UnscrapModalProps = {+ itemId: string;+ trackedEntityId: string;+ quantity: number;+ /** Optional readable label for the entity, shown in the modal header. */+ label?: string | null;+ open: boolean;+ onClose: () => void;+};++/**+ * Restore a Scrapped tracked entity to Available (Oracle Return-from-Scrap).+ * Reuses the manual-adjustment route; the edge function resolves the original+ * scrap movement (location, bin, and original cost) from the entity, so no+ * location is submitted here — a Scrapped tracked-entity row carries none.+ */+export function UnscrapModal({+ itemId,+ trackedEntityId,+ quantity,+ label,+ open,+ onClose+}: UnscrapModalProps) {+ const { t } = useLingui();++ return (+ <Modal open={open} onOpenChange={(v) => !v && onClose()}>+ <ModalContent>+ <ValidatedForm+ method="post"+ action={path.to.inventoryItemAdjustment(itemId)}+ validator={inventoryAdjustmentValidator}+ defaultValues={{+ itemId,+ trackedEntityId,+ adjustmentType: "Unscrap",+ quantity,+ comment: ""+ }}+ onSubmit={onClose}+ >+ <ModalHeader>+ <ModalTitle>+ {label ? <Trans>Unscrap {label}</Trans> : <Trans>Unscrap</Trans>}+ </ModalTitle>+ <ModalDescription>+ <Trans>+ Restore this entity to available stock at the bin and cost it+ was scrapped from.+ </Trans>+ </ModalDescription>+ </ModalHeader>+ <ModalBody>+ <Hidden name="itemId" />+ <Hidden name="trackedEntityId" />+ <Hidden name="adjustmentType" />+ <Hidden name="quantity" />+ <VStack spacing={4}>+ <TextArea name="comment" label={t`Comment`} />+ </VStack>+ </ModalBody>+ <ModalFooter>+ <Button variant="secondary" onClick={onClose}>+ <Trans>Cancel</Trans>+ </Button>+ <Submit withBlocker={false}>+ <Trans>Unscrap</Trans>+ </Submit>+ </ModalFooter>+ </ValidatedForm>+ </ModalContent>+ </Modal>+ );+}diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 3b83eb27cf..e2a378422f 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,5 +1,5 @@{- "generated": "2026-08-07T12:10:07.116Z",+ "generated": "2026-08-08T19:49:36.245Z","totalTools": 1416,"modules": 15,"tools": [diff --git a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsxindex 76590d02ce..e18bbf9e23 100644--- a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx+++ b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx@@ -70,8 +70,10 @@ export async function action({ request, params }: ActionFunctionArgs) {// Pick the bin surface from `adjustmentType` only. `quantity` is a// positive magnitude per `inventoryAdjustmentValidator` — sign-based// direction detection would misclassify `Negative Adjmt.` as `place`.- // Item rules own the `place`/`pick` surfaces.- const isNegative = d.adjustmentType === "Negative Adjmt.";+ // Item rules own the `place`/`pick` surfaces. Scrap removes from a bin+ // (pick); Unscrap restores to a bin (place).+ const isNegative =+ d.adjustmentType === "Negative Adjmt." || d.adjustmentType === "Scrap";const binSurface: "place" | "pick" = isNegative ? "pick" : "place";const binPass = await evaluateLinesForSurface({diff --git a/apps/mes/app/components/AssemblyView.tsx b/apps/mes/app/components/AssemblyView.tsxindex b3ca87d0cd..52c80c4a0d 100644--- a/apps/mes/app/components/AssemblyView.tsx+++ b/apps/mes/app/components/AssemblyView.tsx@@ -2307,6 +2307,7 @@ export function AssemblyView({parentIsSerial={requiresSerialTracking}parentIsBatch={requiresBatchTracking}trackedEntityId={currentEntity?.id ?? ""}+ trackedEntityReadableId={currentEntity?.readableId ?? undefined}setupProductionEvent={openByType("Setup")}laborProductionEvent={openByType("Labor")}machineProductionEvent={openByType("Machine")}@@ -3040,7 +3041,11 @@ function UnitNavigator({}: {units: {index: number;- entity: { id: string; readableId?: string | null } | null;+ entity: {+ id: string;+ readableId?: string | null;+ status?: string | null;+ } | null;}[];currentUnitIndex: number;// Highest unit index the operator may open. For a serial parent this is the last@@ -3106,9 +3111,12 @@ function UnitNavigator({const isCurrent = u.index === currentUnitIndex;const bad = unitHasBadResult(u.index);const recorded = unitIsRecorded(u.index);+ // A scrapped serial is terminal — it can't be worked or selected; show+ // it muted with a Scrapped marker instead.+ const isScrapped = u.entity?.status === "Scrapped";// A serial unit with no minted serial yet can't be opened (nothing to// scan or complete against). Show it as a disabled placeholder.- const navigable = isNavigable(u);+ const navigable = isNavigable(u) && !isScrapped;return (<buttonkey={u.index}@@ -3116,7 +3124,13 @@ function UnitNavigator({ref={isCurrent ? currentRef : undefined}aria-pressed={isCurrent}disabled={!navigable}- title={navigable ? undefined : "Not started yet"}+ title={+ isScrapped+ ? "Scrapped"+ : navigable+ ? undefined+ : "Not started yet"+ }onClick={() => onSelectUnit(u.index)}className={cn("flex w-full items-center gap-2 px-3 py-2 text-left text-xs transition-colors",@@ -3125,13 +3139,14 @@ function UnitNavigator({: navigable? "text-muted-foreground hover:bg-muted/60": "cursor-not-allowed text-muted-foreground/40",- bad && "text-red-500"+ bad && "text-red-500",+ isScrapped && "opacity-50")}><spanclassName={cn("size-1.5 shrink-0 rounded-full",- bad+ bad || isScrapped? "bg-red-500": recorded? "bg-emerald-500"@@ -3141,7 +3156,12 @@ function UnitNavigator({{isEntityLabel(u) && u.entity ? (u.entity.readableId ? (<span className="flex min-w-0 flex-col">- <span className="truncate font-medium">+ <span+ className={cn(+ "truncate font-medium",+ isScrapped && "line-through"+ )}+ >{u.entity.readableId}</span><span className="truncate font-mono text-[10px] text-muted-foreground">@@ -3149,13 +3169,23 @@ function UnitNavigator({</span></span>) : (- <span className="truncate font-mono">+ <span+ className={cn(+ "truncate font-mono",+ isScrapped && "line-through"+ )}+ >{u.entity.id.slice(0, 8)}</span>)) : (<span className="truncate">{`Unit ${u.index + 1}`}</span>)}+ {isScrapped && (+ <span className="ml-auto shrink-0 text-[10px] font-semibold uppercase tracking-wide text-red-500">+ Scrapped+ </span>+ )}</button>);})}diff --git a/apps/mes/app/components/Inspection/InspectionView.tsx b/apps/mes/app/components/Inspection/InspectionView.tsxindex bca0f9257e..34997aee77 100644--- a/apps/mes/app/components/Inspection/InspectionView.tsx+++ b/apps/mes/app/components/Inspection/InspectionView.tsx@@ -354,7 +354,11 @@ export function InspectionView({const opAttrKey = `Operation ${operationId}`;const entityOpenAtOp = useCallback((entity: TrackedEntity) => {- if (entity.status === "Consumed" || entity.status === "Rejected") {+ if (+ entity.status === "Consumed" ||+ entity.status === "Rejected" ||+ entity.status === "Scrapped"+ ) {return false;}const attributes = (entity.attributes ?? {}) as Record<string, unknown>;@@ -383,11 +387,13 @@ export function InspectionView({return ids;}, [samples, sampleStatuses]);+ // Remaining GOOD work: scrap no longer counts toward targetQuantity+ // (20260807090629), so a scrapped unit doesn't reduce what's left to make —+ // its replacement still has to be completed.const opRemaining = Math.max(0,(operation.targetQuantity ?? operation.operationQuantity ?? 0) -(operation.quantityComplete ?? 0) -- (operation.quantityScrapped ?? 0) -(operation.quantityReworked ?? 0));diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsxindex 802f24a222..94da4e51dd 100644--- a/apps/mes/app/components/JobOperation/JobOperation.tsx+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx@@ -1752,7 +1752,10 @@ export const JobOperation = ({trackedEntities?.map((entity) => (<Trkey={`serial-${entity.id}`}- className="[&>td]:py-3"+ className={cn(+ "[&>td]:py-3",+ entity.status === "Scrapped" && "opacity-60"+ )}><Td><div className="flex gap-2 items-center">@@ -1776,6 +1779,11 @@ export const JobOperation = ({<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>@@ -1798,7 +1806,10 @@ export const JobOperation = ({<Buttonvariant="secondary"size="lg"- isDisabled={entity.id === trackedEntityId}+ isDisabled={+ entity.id === trackedEntityId ||+ entity.status === "Scrapped"+ }onClick={() => {const entityIndex =trackedEntities.findIndex(@@ -2545,6 +2556,10 @@ export const JobOperation = ({parentIsBatch={parentIsBatch}setupProductionEvent={setupProductionEvent}trackedEntityId={trackedEntityId}+ trackedEntityReadableId={+ trackedEntities.find((entity) => entity.id === trackedEntityId)+ ?.readableId ?? undefined+ }onClose={scrapModal.onClose}/>)}diff --git a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsxindex 2a91d541d2..04b765ffae 100644--- a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx+++ b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx@@ -49,6 +49,7 @@ import {LuCirclePlus,LuList,LuQrCode,+ LuTrash2,LuUndo2,LuX} from "react-icons/lu";@@ -62,6 +63,9 @@ import { issueValidator } from "~/services/models";import type { JobMaterial, TrackedInput } from "~/services/types";import { useItems } from "~/stores";import { path } from "~/utils/path";+import { ScrapEntityModal } from "./ScrapEntityModal";+import type { ScrappableEntity } from "./ScrapTab";+import { ScrapTab } from "./ScrapTab";type TrackingType = "Serial" | "Batch" | "Inventory" | "Non-Inventory" | null;@@ -287,6 +291,33 @@ export function IssueMaterialModal({}));}, [trackedInputs]);+ // Scrappable entities for this material: available (picked / in stock,+ // pulled from the item's available serials) + already-consumed (trackedInputs).+ const scrappableEntities = useMemo<ScrappableEntity[]>(() => {+ const consumed: ScrappableEntity[] = trackedInputs.map((input) => ({+ id: input.id,+ readableId: input.readableId,+ state: "Consumed" as const+ }));+ const consumedIds = new Set(consumed.map((e) => e.id));+ const availableSource =+ trackingType === "Batch"+ ? (batchNumbers?.data ?? [])+ : (serialNumbers?.data ?? []);+ const available: ScrappableEntity[] = availableSource+ // Batch numbers are not pre-filtered by status at the query, so guard here+ // (serial numbers already come back Available-only) — Reserved/On Hold/+ // Scrapped entities must never appear as scrap-from-stock targets.+ .filter((s) => s.status === "Available")+ .filter((s) => !consumedIds.has(s.id))+ .map((s) => ({+ id: s.id,+ readableId: s.readableId,+ state: "Available" as const+ }));+ return [...available, ...consumed];+ }, [trackedInputs, trackingType, serialNumbers?.data, batchNumbers?.data]);+// Default issue quantity. Serial parents always issue per-unit// (material.quantity is the per-unit requirement and quantityIssued is// scoped to the parent entity). The assembly view issues per-unit for@@ -316,6 +347,10 @@ export function IssueMaterialModal({.map((_, index) => ({ index, id: "" })));const [serialErrors, setSerialErrors] = useState<Record<number, string>>({});+ const [scrapEntityTarget, setScrapEntityTarget] = useState<{+ id: string;+ readableId?: string | null;+ } | null>(null);const [selectedTrackedInputs, setSelectedTrackedInputs] = useState<string[]>([]);@@ -1295,8 +1330,8 @@ export function IssueMaterialModal({<Tabs value={activeTab} onValueChange={setActiveTab}><TabsListclassName={cn(- "grid w-full grid-cols-2 mb-4",- hasTrackedInputs && "grid-cols-3"+ "grid w-full grid-cols-3 mb-4",+ hasTrackedInputs && "grid-cols-4")}><TabsTrigger value="scan">@@ -1307,6 +1342,10 @@ export function IssueMaterialModal({<LuList className="mr-2" />Select</TabsTrigger>+ <TabsTrigger value="scrap">+ <LuTrash2 className="mr-2" />+ Scrap+ </TabsTrigger>{hasTrackedInputs && (<TabsTrigger value="unconsume"><LuUndo2 className="mr-2" />@@ -1315,6 +1354,18 @@ export function IssueMaterialModal({)}</TabsList>+ <TabsContent value="scrap">+ <ScrapTab+ entities={scrappableEntities}+ onScrap={(entity) =>+ setScrapEntityTarget({+ id: entity.id,+ readableId: entity.readableId+ })+ }+ />+ </TabsContent>+<TabsContent value="scan"><div className="flex flex-col gap-4">{selectedSerialNumbers.map((sn, index) => (@@ -1548,8 +1599,8 @@ export function IssueMaterialModal({<Tabs value={activeTab} onValueChange={setActiveTab}><TabsListclassName={cn(- "grid w-full grid-cols-2 mb-4",- hasTrackedInputs && "grid-cols-3"+ "grid w-full grid-cols-3 mb-4",+ hasTrackedInputs && "grid-cols-4")}><TabsTrigger value="scan">@@ -1560,6 +1611,10 @@ export function IssueMaterialModal({<LuList className="mr-2" />Select</TabsTrigger>+ <TabsTrigger value="scrap">+ <LuTrash2 className="mr-2" />+ Scrap+ </TabsTrigger>{hasTrackedInputs && (<TabsTrigger value="unconsume"><LuUndo2 className="mr-2" />@@ -1568,6 +1623,18 @@ export function IssueMaterialModal({)}</TabsList>+ <TabsContent value="scrap">+ <ScrapTab+ entities={scrappableEntities}+ onScrap={(entity) =>+ setScrapEntityTarget({+ id: entity.id,+ readableId: entity.readableId+ })+ }+ />+ </TabsContent>+<TabsContent value="scan"><div className="flex flex-col gap-4">{selectedBatchNumbers.map((batch, index) => (@@ -1886,6 +1953,16 @@ export function IssueMaterialModal({)}</ModalContent></Modal>+ {scrapEntityTarget && (+ <ScrapEntityModal+ materialId={material?.id ?? ""}+ trackedEntityId={scrapEntityTarget.id}+ readableId={scrapEntityTarget.readableId}+ parentId={parentId}+ isMakeToOrder={material?.methodType === "Make to Order"}+ onClose={() => setScrapEntityTarget(null)}+ />+ )}</>);}diff --git a/apps/mes/app/components/JobOperation/components/QuantityModal.tsx b/apps/mes/app/components/JobOperation/components/QuantityModal.tsxindex 94acee1022..12066b9e4e 100644--- a/apps/mes/app/components/JobOperation/components/QuantityModal.tsx+++ b/apps/mes/app/components/JobOperation/components/QuantityModal.tsx@@ -54,6 +54,7 @@ export function QuantityModal({parentIsBatch = false,setupProductionEvent,trackedEntityId,+ trackedEntityReadableId,type,onClose}: {@@ -66,6 +67,9 @@ export function QuantityModal({parentIsBatch?: boolean;setupProductionEvent: ProductionEvent | undefined;trackedEntityId: string;+ // Serial parents: the selected unit's serial number, shown in the scrap+ // confirmation so the operator knows exactly which unit is being scrapped.+ trackedEntityReadableId?: string;type: "scrap" | "rework" | "complete" | "finish";onClose: () => void;}) {@@ -288,6 +292,26 @@ export function QuantityModal({)}{type === "scrap" ? (<>+ {parentIsSerial && (+ <Alert>+ <LuTriangleAlert className="h-4 w-4" />+ <AlertTitle>+ {trackedEntityReadableId ? (+ <Trans>+ Scrapping serial {trackedEntityReadableId}+ </Trans>+ ) : (+ <Trans>Scrapping the selected serial</Trans>+ )}+ </AlertTitle>+ <AlertDescription>+ <Trans>+ This unit will be permanently scrapped and a+ replacement serial number will be created.+ </Trans>+ </AlertDescription>+ </Alert>+ )}<ScrapReasonname="scrapReasonId"label={t`Scrap Reason`}diff --git a/apps/mes/app/components/JobOperation/components/ScrapEntityModal.tsx b/apps/mes/app/components/JobOperation/components/ScrapEntityModal.tsxnew file mode 100644index 0000000000..037b9590c5--- /dev/null+++ b/apps/mes/app/components/JobOperation/components/ScrapEntityModal.tsx@@ -0,0 +1,130 @@+import { Boolean, TextArea, ValidatedForm } from "@carbon/form";+import {+ Button,+ Modal,+ ModalBody,+ ModalContent,+ ModalDescription,+ ModalFooter,+ ModalHeader,+ ModalTitle,+ VStack+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useEffect, useRef } from "react";+import { useFetcher } from "react-router";+import { scrapTrackedEntityValidator } from "~/services/models";+import { path } from "~/utils/path";+import ScrapReason from "./ScrapReason";++// Scrap an already-made / issued BOM entity from the Materials section (both+// the operation and assembly views share this). Pull-from-inventory parts are+// scrapped from stock (requirement stays open for a replacement pull);+// Make-to-Order subassemblies flip to Scrapped and — when makeReplacement is+// checked — reopen their routing and spawn a replacement unit.+export function ScrapEntityModal({+ materialId,+ trackedEntityId,+ readableId,+ parentId,+ isMakeToOrder,+ onClose+}: {+ materialId: string;+ trackedEntityId: string;+ readableId?: string | null;+ parentId?: string;+ isMakeToOrder: boolean;+ onClose: () => void;+}) {+ const { t } = useLingui();+ const fetcher = useFetcher<{ success: boolean; message: string }>();+ const submitted = useRef(false);++ useEffect(() => {+ if (submitted.current && fetcher.state === "idle") {+ onClose();+ }+ }, [fetcher.state, onClose]);++ return (+ <Modal+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ >+ <ModalContent>+ <ValidatedForm+ action={path.to.scrapEntity(materialId, trackedEntityId, parentId)}+ method="post"+ validator={scrapTrackedEntityValidator}+ defaultValues={{+ scrapReasonId: "",+ makeReplacement: isMakeToOrder,+ notes: ""+ }}+ fetcher={fetcher}+ onSubmit={() => {+ submitted.current = true;+ }}+ >+ <ModalHeader>+ <ModalTitle>+ {readableId ? (+ <Trans>Scrap {readableId}</Trans>+ ) : (+ <Trans>Scrap material</Trans>+ )}+ </ModalTitle>+ <ModalDescription>+ {isMakeToOrder ? (+ <Trans>+ This part was made to order. Scrapping it can reopen its+ routing to make a replacement.+ </Trans>+ ) : (+ <Trans>+ This part will be scrapped from stock. Its requirement stays+ open so you can issue a replacement.+ </Trans>+ )}+ </ModalDescription>+ </ModalHeader>+ <ModalBody>+ <VStack spacing={4}>+ <ScrapReason+ name="scrapReasonId"+ label={t`Scrap Reason`}+ size="lg"+ />+ {isMakeToOrder && (+ <Boolean+ name="makeReplacement"+ label={t`Make a replacement`}+ description={t`Reopen the subassembly and create a replacement unit`}+ bordered+ />+ )}+ <TextArea label={t`Notes`} name="notes" size="lg" />+ </VStack>+ </ModalBody>+ <ModalFooter>+ <Button variant="secondary" size="lg" onClick={onClose}>+ <Trans>Cancel</Trans>+ </Button>+ <Button+ variant="destructive"+ size="lg"+ type="submit"+ isLoading={fetcher.state !== "idle"}+ isDisabled={fetcher.state !== "idle"}+ >+ <Trans>Scrap</Trans>+ </Button>+ </ModalFooter>+ </ValidatedForm>+ </ModalContent>+ </Modal>+ );+}diff --git a/apps/mes/app/components/JobOperation/components/ScrapTab.tsx b/apps/mes/app/components/JobOperation/components/ScrapTab.tsxnew file mode 100644index 0000000000..a0e5234b08--- /dev/null+++ b/apps/mes/app/components/JobOperation/components/ScrapTab.tsx@@ -0,0 +1,79 @@+import {+ Alert,+ AlertDescription,+ AlertTitle,+ Badge,+ Button+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { LuTrash2 } from "react-icons/lu";++export type ScrappableEntity = {+ id: string;+ readableId?: string | null;+ state: "Available" | "Consumed";+};++// The material's scrappable tracked entities: available ones (picked / in+// stock, not yet consumed) and already-consumed ones. Each row scraps the+// entity via the shared ScrapEntityModal (opened by onScrap). The edge+// function branches on the entity's state — Available scraps from stock,+// Consumed relieves WIP and reopens the requirement.+export function ScrapTab({+ entities,+ onScrap+}: {+ entities: ScrappableEntity[];+ onScrap: (entity: ScrappableEntity) => void;+}) {+ const { t } = useLingui();++ if (entities.length === 0) {+ return (+ <Alert variant="warning">+ <AlertTitle>+ <Trans>Nothing to scrap</Trans>+ </AlertTitle>+ <AlertDescription>+ <Trans>+ There are no available or consumed tracked parts for this material.+ </Trans>+ </AlertDescription>+ </Alert>+ );+ }++ return (+ <div className="flex flex-col gap-3">+ {entities.map((entity) => (+ <div+ key={`${entity.state}-${entity.id}`}+ className="flex items-center gap-3 rounded-md border p-3"+ >+ <div className="flex-1">+ <div className="text-sm font-medium">+ {entity.readableId ?? entity.id}+ </div>+ <Badge+ variant={entity.state === "Consumed" ? "secondary" : "outline"}+ >+ {entity.state === "Consumed" ? (+ <Trans>Consumed</Trans>+ ) : (+ <Trans>Available</Trans>+ )}+ </Badge>+ </div>+ <Button+ variant="destructive"+ size="lg"+ leftIcon={<LuTrash2 />}+ onClick={() => onScrap(entity)}+ >+ {t`Scrap`}+ </Button>+ </div>+ ))}+ </div>+ );+}diff --git a/apps/mes/app/routes/x+/assembly.$operationId.tsx b/apps/mes/app/routes/x+/assembly.$operationId.tsxindex ca6baf1575..4cfd83d0a9 100644--- a/apps/mes/app/routes/x+/assembly.$operationId.tsx+++ b/apps/mes/app/routes/x+/assembly.$operationId.tsx@@ -215,12 +215,17 @@ export async function loader({ request, params }: LoaderFunctionArgs) {// Is this the first operation in the routing? A serial unit only earns a printed// label when completed at its first operation, so the first op flows unit-by-unit// (auto-select), and later ops scan/select (labels exist). "First" means nothing- // precedes it — no jobOperationDependency row keyed to this operation. `order` is- // only a display/sort field and isn't a reliable precedence signal.+ // precedes it within THIS make method — no jobOperationDependency whose predecessor+ // shares this op's jobMakeMethodId. Cross make-method (subassembly) dependencies are+ // ignored: a parent-assembly op still has no printed label just because a subassembly+ // finished first. `order` is only a display/sort field and isn't a reliable signal.serviceRole.from("jobOperationDependency")- .select("operationId")+ .select(+ "dependsOn:jobOperation!jobOperationDependency_dependsOnId_fk!inner(jobMakeMethodId)"+ ).eq("operationId", operationId)+ .eq("dependsOn.jobMakeMethodId", op.jobMakeMethodId).limit(1).maybeSingle()]);diff --git a/apps/mes/app/routes/x+/complete.tsx b/apps/mes/app/routes/x+/complete.tsxindex d0d3e4a895..096794ee97 100644--- a/apps/mes/app/routes/x+/complete.tsx+++ b/apps/mes/app/routes/x+/complete.tsx@@ -111,10 +111,12 @@ export async function action({ request }: ActionFunctionArgs) {);}+ // Mirror the DB auto-Done predicate (sync_update_job_operation_quantities,+ // 20260807090629): scrap does NOT count toward targetQuantity — the op is+ // finished only once GOOD (+ reworked) quantity reaches the target.const totalAccountedQuantity =(jobOperation.data.quantityComplete ?? 0) +(jobOperation.data.quantityReworked ?? 0) +- (jobOperation.data.quantityScrapped ?? 0) +validation.data.quantity;const willBeFinished =diff --git a/apps/mes/app/routes/x+/entity+/$materialId.$trackedEntityId.scrap.tsx b/apps/mes/app/routes/x+/entity+/$materialId.$trackedEntityId.scrap.tsxindex 4abae36a06..358a5775ba 100644--- a/apps/mes/app/routes/x+/entity+/$materialId.$trackedEntityId.scrap.tsx+++ b/apps/mes/app/routes/x+/entity+/$materialId.$trackedEntityId.scrap.tsx@@ -1,7 +1,9 @@import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";+import { scrapTrackedEntityValidator } from "~/services/models";import { getTrackedEntity } from "~/services/operations.service";export async function action({ request, params }: ActionFunctionArgs) {@@ -15,6 +17,14 @@ export async function action({ request, params }: ActionFunctionArgs) {const url = new URL(request.url);const parentTrackedEntityId = url.searchParams.get("parentId") || undefined;+ const formData = await request.formData();+ const validation = await validator(scrapTrackedEntityValidator).validate(+ formData+ );+ if (validation.error) {+ return validationError(validation.error);+ }+const trackedEntity = await getTrackedEntity(client, trackedEntityId);if (trackedEntity.error) {return data(@@ -30,6 +40,8 @@ export async function action({ request, params }: ActionFunctionArgs) {materialId,parentTrackedEntityId,type: "scrapTrackedEntity",+ scrapReasonId: validation.data.scrapReasonId,+ makeReplacement: validation.data.makeReplacement,companyId,userId}@@ -37,10 +49,10 @@ export async function action({ request, params }: ActionFunctionArgs) {if (issue.error) {return data(- { success: false, message: "Failed to scrape entity" },+ { success: false, message: "Failed to scrap entity" },{ status: 400 });}- return { success: true, message: "Entity scraped successfully" };+ return { success: true, message: "Entity scrapped successfully" };}diff --git a/apps/mes/app/routes/x+/operation.$operationId.tsx b/apps/mes/app/routes/x+/operation.$operationId.tsxindex c4cb8e5f61..a3517eeb6f 100644--- a/apps/mes/app/routes/x+/operation.$operationId.tsx+++ b/apps/mes/app/routes/x+/operation.$operationId.tsx@@ -117,16 +117,20 @@ export async function loader({ request, params }: LoaderFunctionArgs) {// (auto-select here on arrival, and in the client after each completion);// - later operations: every unit already has a label → the operator// scans/selects each unit (no auto-select, here or in the client).- // An operation is "first" when nothing precedes it in the routing — i.e. it has- // no jobOperationDependency (a row means this op depends on / comes after- // another). `order` is only a display/sort field and isn't a reliable- // precedence signal, so it's not used here. A first op has no printed labels- // yet (they print on its completion), so its units are auto-selected; later- // ops already have labels, so the operator scans/selects.+ // An operation is "first" when nothing precedes it in THIS make method's+ // routing — i.e. it has no jobOperationDependency whose predecessor lives in+ // the same jobMakeMethod. Dependencies also model subassembly ordering (a+ // parent-assembly op waits on its child subassembly's ops), and those cross+ // make-method dependencies must NOT count: the parent serial still has no+ // printed label just because a subassembly finished first. `order` is only a+ // display/sort field and isn't a reliable precedence signal, so it's not used.const priorDependency = await serviceRole.from("jobOperationDependency")- .select("operationId")+ .select(+ "dependsOn:jobOperation!jobOperationDependency_dependsOnId_fk!inner(jobMakeMethodId)"+ ).eq("operationId", operationId)+ .eq("dependsOn.jobMakeMethodId", op.jobMakeMethodId).limit(1).maybeSingle();// Fail closed: a query error also returns null data, so treat an errored lookupdiff --git a/apps/mes/app/routes/x+/scrap.tsx b/apps/mes/app/routes/x+/scrap.tsxindex 824c95f52a..0ca34887ec 100644--- a/apps/mes/app/routes/x+/scrap.tsx+++ b/apps/mes/app/routes/x+/scrap.tsx@@ -6,11 +6,10 @@ import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { scrapQuantityValidator } from "~/services/models";-import { insertScrapQuantity } from "~/services/operations.service";export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyId, userId } = await requirePermissions(request, {});+ const { companyId, userId } = await requirePermissions(request, {});const formData = await request.formData();const validation = await validator(scrapQuantityValidator).validate(formData);@@ -19,44 +18,52 @@ export async function action({ request }: ActionFunctionArgs) {return validationError(validation.error);}- // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration- const { trackedEntityId, trackingType, ...d } = validation.data;-- const insertScrap = await insertScrapQuantity(client, {- ...d,- companyId,- createdBy: userId- });-- if (insertScrap.error) {- return data(- {},- await flash(- request,- error(insertScrap.error, "Failed to record scrap quantity")- )- );- }+ const {+ trackedEntityId,+ trackingType,+ jobOperationId,+ quantity,+ scrapReasonId,+ notes,+ setupProductionEventId,+ laborProductionEventId,+ machineProductionEventId+ } = validation.data;+ // One transactional edge-function call: Scrap productionQuantity row, BOM+ // backflush, tracked-entity terminal status + replacement serial spawn+ // (serial parents), Done-operation reopen / capacity top-up beyond the+ // planned allowance, and the WIP→scrap journal.const issue = await getCarbonServiceRole().functions.invoke("issue", {body: {- id: validation.data.jobOperationId,- type: "jobOperation",- quantity: validation.data.quantity,+ type: "jobOperationScrap",+ jobOperationId,+ quantity,+ scrapReasonId,+ notes,+ setupProductionEventId,+ laborProductionEventId,+ machineProductionEventId,+ trackedEntityId: trackingType === "Serial" ? trackedEntityId : undefined,companyId,userId}});if (issue.error) {- throw data(- insertScrap.data,- await flash(request, error(issue.error, "Failed to issue materials"))+ return data(+ {},+ await flash(+ request,+ error(issue.error, "Failed to record scrap quantity")+ ));}+ // The client (useOperation / AssemblyView) advances to the spawned+ // replacement serial the same way the complete flow does.return data(- insertScrap.data,+ { scrapped: true, newTrackedEntityId: issue.data?.newTrackedEntityId },await flash(request, success("Scrap quantity recorded successfully")));}diff --git a/apps/mes/app/services/models.ts b/apps/mes/app/services/models.tsindex c430950c97..9eb07e44b6 100644--- a/apps/mes/app/services/models.ts+++ b/apps/mes/app/services/models.ts@@ -208,6 +208,17 @@ export const scrapQuantityValidator = baseQuantityValidator.extend({notes: zfd.text(z.string().optional())});+// Scrapping an already-made/staged BOM entity from the Materials section.+// makeReplacement (Make-to-Order materials only) reopens the subassembly's+// routing and spawns a replacement unit.+export const scrapTrackedEntityValidator = z.object({+ scrapReasonId: zfd.text(z.string()),+ makeReplacement: zfd+ .text(z.string().optional())+ .transform((v) => v === "true" || v === "on"),+ notes: zfd.text(z.string().optional())+});+export const triggerReworkValidator = z.object({jobId: z.string().min(1),triggeredAtJobOperationId: z.string().min(1),diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex 4a1ae6046f..0c5e2d59dd 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -1187,9 +1187,12 @@ export function isSerialEntityIncompleteForOperation(jobOperationId: string): boolean {const attributes = (entity.attributes ?? {}) as Record<string, unknown>;+ // Scrapped is terminal like Consumed — a scrapped unit is never a work+ // candidate; its replacement is the spawned Reserved entity.return (!(`Operation ${jobOperationId}` in attributes) &&- entity.status !== "Consumed"+ entity.status !== "Consumed" &&+ entity.status !== "Scrapped");}@@ -1206,10 +1209,20 @@ export function getNextIncompleteSerialEntity<T extends SerialEntityForSelection>(entities: T[], jobOperationId: string): T | undefined {if (entities.length === 0) return undefined;+ // Prefer a non-terminal (not Consumed/Scrapped) unit for the end-state+ // fallback so we never seed work onto a scrapped/consumed serial. But keep+ // the guaranteed last-entity fallback for a fully-terminal make method (every+ // unit Consumed on a finished subassembly), preserving the prior behavior of+ // always returning something when entities exist.+ const selectable = entities.filter(+ (entity) => entity.status !== "Consumed" && entity.status !== "Scrapped"+ );return (- entities.find((entity) =>+ selectable.find((entity) =>isSerialEntityIncompleteForOperation(entity, jobOperationId)- ) ?? entities[entities.length - 1]+ ) ??+ selectable[selectable.length - 1] ??+ entities[entities.length - 1]);}@@ -1256,6 +1269,15 @@ export async function getTrackedInputs(})]);+ // A scrapped descendant is no longer a live consumed input — the scrap flow+ // relieved its WIP and reopened the material requirement — so it must not+ // surface in the Unconsume/Scrap lists (which are built from these inputs).+ // Genealogy still sees it via the traceability lineage RPCs; this MES helper+ // intentionally hides it.+ if (inputs.data) {+ inputs.data = inputs.data.filter((input) => input.status !== "Scrapped");+ }+if (outputs.error || outputs.data.length === 0) return inputs;// Handle circular references while keeping only unique entities that appear more times in inputs than outputsdiff --git a/apps/mes/app/services/quality.server.ts b/apps/mes/app/services/quality.server.tsindex a3e958deeb..38652476de 100644--- a/apps/mes/app/services/quality.server.ts+++ b/apps/mes/app/services/quality.server.ts@@ -328,11 +328,11 @@ export async function getInspectionOutcomeState(0);+ // Scrap no longer counts toward targetQuantity (20260807090629), so a+ // scrapped unit doesn't reduce remaining good work.const opTarget = operation.targetQuantity ?? operation.operationQuantity ?? 0;const opAccounted =- (operation.quantityComplete ?? 0) +- (operation.quantityScrapped ?? 0) +- (operation.quantityReworked ?? 0);+ (operation.quantityComplete ?? 0) + (operation.quantityReworked ?? 0);const opRemaining = Math.max(0, opTarget - opAccounted);const entities = (trackedEntities?.data ?? []).map((e) => ({diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.tsindex 64d53cd25e..cae11ae841 100644--- a/apps/mes/app/utils/path.ts+++ b/apps/mes/app/utils/path.ts@@ -185,8 +185,8 @@ export const path = {generatePath(`${x}/rework-targets/${operationId}`),root: "/",scrap: `${x}/scrap`,- scrapEntity: (operationId: string, id: string, parentId?: string) => {- const basePath = generatePath(`${x}/entity/${operationId}/${id}/scrap`);+ scrapEntity: (materialId: string, id: string, parentId?: string) => {+ const basePath = generatePath(`${x}/entity/${materialId}/${id}/scrap`);return parentId ? `${basePath}?parentId=${parentId}` : basePath;},scrapReasons: `${api}/scrap-reasons`,diff --git a/docs/content/docs/reference/inventory.mdx b/docs/content/docs/reference/inventory.mdxindex 3dbb6b18c6..0599dc69f0 100644--- a/docs/content/docs/reference/inventory.mdx+++ b/docs/content/docs/reference/inventory.mdx@@ -30,7 +30,7 @@ On hand can go **negative**. Shipping, issuing to a job, and picking all post th## Movements-Two kinds of transfer move stock. A **warehouse transfer** moves it between locations, and is carried out as a <Term id="shipment">shipment</Term> out of one and a receipt into the other. A **stock transfer** moves it within a single location, between storage units. A manual **adjustment** posts a positive or negative entry to the ledger, or a *Set Quantity* that books the difference to a target. When accounting is enabled, every adjustment also posts a <Term id="journal">journal</Term>: a loss debits the inventory adjustment account and credits inventory, a gain is the mirror image, valued at the item's current cost. Inventory count variances post the same way. Moving stock between storage units posts no journal, because the value never left the location.+Two kinds of transfer move stock. A **warehouse transfer** moves it between locations, and is carried out as a <Term id="shipment">shipment</Term> out of one and a receipt into the other. A **stock transfer** moves it within a single location, between storage units. A manual **adjustment** posts a positive or negative entry to the ledger, or a *Set Quantity* that books the difference to a target. When accounting is enabled, every adjustment also posts a <Term id="journal">journal</Term>: a loss debits the inventory adjustment account and credits inventory, a gain is the mirror image, valued at the item's current cost. Inventory count variances post the same way. Moving stock between storage units posts no journal, because the value never left the location. [Scrapping](/docs/reference/scrap) stock is a negative adjustment with a reason, offset to the scrap account instead of the adjustment account.## Correcting a movementdiff --git a/docs/content/docs/reference/jobs.mdx b/docs/content/docs/reference/jobs.mdxindex acccc80c50..f1a93fd30b 100644--- a/docs/content/docs/reference/jobs.mdx+++ b/docs/content/docs/reference/jobs.mdx@@ -75,7 +75,7 @@ The **order** field sets each operation's position, and operation order (*After### Time and output-The floor reports two separate things against an operation. A <Term id="production-event">production event</Term> measures *time*, typed **Setup**, **Labor**, or **Machine**, with a start, an end, and the employee. A production quantity measures *units* (**Production**, **Scrap**, or **Rework**) and rolls up automatically into the operation's completed, scrapped, and reworked totals. Logging time implies no output, and reporting output implies no particular time, which is what lets Carbon cost on actual events while measuring yield on actual quantities. Untracked materials are <Term id="backflush">backflushed</Term> as output is reported; tracked materials are issued deliberately.+The floor reports two separate things against an operation. A <Term id="production-event">production event</Term> measures *time*, typed **Setup**, **Labor**, or **Machine**, with a start, an end, and the employee. A production quantity measures *units* (**Production**, [**Scrap**](/docs/reference/scrap), or **Rework**) and rolls up automatically into the operation's completed, scrapped, and reworked totals. Scrapped units don't count toward the target, so the operation keeps going until the good quantity is met. Logging time implies no output, and reporting output implies no particular time, which is what lets Carbon cost on actual events while measuring yield on actual quantities. Untracked materials are <Term id="backflush">backflushed</Term> as output is reported; tracked materials are issued deliberately.### Proceduresdiff --git a/docs/content/docs/reference/mes.mdx b/docs/content/docs/reference/mes.mdxindex 8542fbf252..87467bd063 100644--- a/docs/content/docs/reference/mes.mdx+++ b/docs/content/docs/reference/mes.mdx@@ -65,7 +65,7 @@ Good, bad, and reworked units are reported separately, so yield stays honest:<FieldTable><Field name="Log Completed">Records good units off this operation. **"Complete All"** fills the remaining quantity; **"Total Quantity"** sets it explicitly.</Field>- <Field name="Log Scrap">Records scrapped units against a required **"Scrap Reason"**, so the loss is attributable.</Field>+ <Field name="Log Scrap">Records scrapped units against a required **"Scrap Reason"**, so the loss is attributable. The unit flips to **"Scrapped"**, a replacement is spawned, and the routing reopens — see [scrap and unscrap](/docs/reference/scrap).</Field><Field name="Log Rework">Records units reworked in place at this operation, without sending them anywhere.</Field></FieldTable>diff --git a/docs/content/docs/reference/meta.json b/docs/content/docs/reference/meta.jsonindex d5bae347bf..89bf70b5b2 100644--- a/docs/content/docs/reference/meta.json+++ b/docs/content/docs/reference/meta.json@@ -46,6 +46,7 @@"storage-rules","shelf-life","traceability",+ "scrap","company-settings","printing","custom-fields",diff --git a/docs/content/docs/reference/scrap.mdx b/docs/content/docs/reference/scrap.mdxnew file mode 100644index 0000000000..e7b974449b--- /dev/null+++ b/docs/content/docs/reference/scrap.mdx@@ -0,0 +1,74 @@+---+title: Scrap and unscrap+description: Writing off defective or lost material, and restoring it if the write-off was a mistake.+---++<Term id="scrap">Scrap</Term> is how Carbon records material you can't recover: a unit ruined at an operation, a subcomponent that failed, or stock lost in the warehouse. Every scrap names a **reason**, moves the value off inventory or out of <Term id="wip">work-in-process</Term>, and (when accounting is on) posts a journal. If you scrapped in error, **Unscrap** puts it back exactly as it was.++There are three places you can scrap, and they behave differently. What they share: the affected <Term id="tracked-entity">tracked entity</Term> ends at status **"Scrapped"**, which keeps its quantity as the record of what was lost and, unlike **"Consumed"** or **"Rejected"**, can be reversed.++## Scrapping a unit on the floor++When the unit you're building goes bad, an operator taps **"Log Scrap"** on the operation, enters a quantity, and picks a required **"Scrap Reason"**. For a <Term id="serial">Serial</Term> part the currently selected serial is the one scrapped.++Carbon records a **Scrap** production quantity, <Term id="backflush">backflushes</Term> the unit's bill of material into WIP (the material really was consumed making the ruined unit), flips the serial to **"Scrapped"**, and spawns a fresh replacement serial for you to keep working.++<Callout type="info" title="Scrapping reopens the routing instead of counting against the target.">+A scrapped unit is not treated as output. Its quantity never counts toward the operation's target, completed operations reopen to **"Ready"**, and a replacement serial is spawned automatically, so the job keeps producing until the *good* quantity meets the target. The planned quantity itself is never rewritten; Carbon only tops up the operation's run quantity when cumulative scrap runs past the allowance you planned for.+</Callout>++## Scrapping a subcomponent++A component that was picked or already issued into the unit is scrapped from the **"Scrap"** tab of the issue-material dialog, which lists that material's **Available** and **Consumed** tracked entities. Each row's **"Scrap"** button opens a dialog for the reason and, for a <Term id="make-to-order">make-to-order</Term> component, an optional **"Make a replacement"**.++What posts depends on the entity's *state*, not the item's method:++<Callout type="warn" title="State decides the posting: Available scraps from stock, Consumed relieves WIP.">+An **Available** part is scrapped straight out of its bin as a negative adjustment, and the job's issued quantity is left untouched. A **Consumed** part is relieved from the job's WIP at its unit cost, and the material's issued quantity is decremented so the requirement reopens for a replacement. Either way the entity ends at **"Scrapped"**; make-to-order can additionally reopen the subassembly's routing and spawn a replacement with a <Term id="rework">rework</Term> row.+</Callout>++## Scrapping stock++Warehouse stock that never reached a job is scrapped from the storage-unit adjustment form: set the adjustment type to **"Scrap"** and pick a **"Scrap Reason"**. This books a negative movement at the item's cost. A serial flips to **"Scrapped"** and keeps its quantity; scrapping part of a <Term id="batch">batch</Term> splits the lot, and only the scrapped portion becomes **"Scrapped"**.++## Unscrap++Unscrap reverses a scrap. On the tracked-entities table, the **"Unscrap"** action appears on any row at status **"Scrapped"** (filter the status column to **"Scrapped"** to find them). It restores the entity to **"Available"** at the same bin, and asks only for an optional comment.++<Callout type="success" title="Unscrap reverses at the original scrapped cost, and reuses the original reason.">+Unscrap restores the entity at the exact cost it was scrapped from, read back from the original scrap's cost layers, so a scrap-then-unscrap nets to nothing in the ledger. You don't re-enter the reason either; Carbon inherits it from the scrap movement it's reversing, and links the restoring entry back to that movement. (Untracked stock is the one exception: it comes back at current cost and needs a location.)+</Callout>++## Accounting for scrap++Scrap posts to the ledger only when [accounting](/docs/reference/accounting) is enabled; the stock and cost layers move regardless. Every path debits a single **scrap account** (`accountDefault.scrapAccount`, which falls back to the inventory adjustment variance account). Where the credit lands depends on where the value was:++| Scrap path | Debit | Credit |+| --- | --- | --- |+| Unit on the floor | Scrap | Work-in-process |+| Consumed subcomponent | Scrap | Work-in-process |+| Available subcomponent, or stock | Scrap | Inventory |+| Unscrap | Inventory | Scrap |++<Callout type="note" title="There's one scrap account, sliced by dimension tags.">+Carbon deliberately posts all scrap to one account rather than a per-reason chart of accounts. It tags each scrap journal line with **ScrapReason**, **WorkCenter**, and **Employee** <Term id="reporting-dimension">dimensions</Term> (work center only where there's an operation behind the scrap), so you slice scrap by reason, cell, or operator in reporting without proliferating accounts. The ScrapReason dimension reads its values live from your scrap-reason list, so a new reason is immediately reportable.+</Callout>++This scrap is distinct from a quality **disposition** of *Scrap*: closing a quality [issue](/docs/reference/issues) with a Scrap disposition writes the material off to a cost-of-quality account and flips the entity to **"Rejected"**, not **"Scrapped"**.++## Related++<Cards>+ <Card title="Traceability" href="/docs/reference/traceability">+ The tracked-entity statuses, including Scrapped, and the Unscrap action.+ </Card>+ <Card title="Jobs" href="/docs/reference/jobs">+ Production quantities and how scrap is reported against an operation.+ </Card>+ <Card title="Inventory" href="/docs/reference/inventory">+ The item ledger and manual adjustments scrap posts against.+ </Card>+ <Card title="Accounting" href="/docs/reference/accounting">+ The journal, the scrap account, and posting dimensions.+ </Card>+</Cards>diff --git a/docs/content/docs/reference/traceability.mdx b/docs/content/docs/reference/traceability.mdxindex 05495a4541..e6558dc62e 100644--- a/docs/content/docs/reference/traceability.mdx+++ b/docs/content/docs/reference/traceability.mdx@@ -15,6 +15,7 @@ A **tracked entity** is a tracked quantity of an item. A **<Term id="serial">Ser<Status name="On Hold" branch>Received but not yet released (awaiting inspection).</Status><Status name="Consumed" accent>Issued to a job or shipped out.</Status><Status name="Rejected" terminal>Failed inspection.</Status>+ <Status name="Scrapped" terminal>Written off as unrecoverable, with a reason. Unlike Consumed and Rejected, it can be reversed with [Unscrap](/docs/reference/scrap#unscrap).</Status></StatusFlow>## Where entities come from@@ -42,4 +43,7 @@ Tracked items can carry a **shelf life**: a fixed duration, a date set at receip<Card title="Quality" href="/docs/reference/quality">Inspection holds and rejects tracked entities.</Card>+ <Card title="Scrap and unscrap" href="/docs/reference/scrap">+ Writing an entity off to Scrapped, and restoring it.+ </Card></Cards>diff --git a/docs/content/guides/job-costing.mdx b/docs/content/guides/job-costing.mdxindex 850dd05475..351c49272e 100644--- a/docs/content/guides/job-costing.mdx+++ b/docs/content/guides/job-costing.mdx@@ -40,8 +40,8 @@ That material reaches WIP one of two ways, and the difference is *when*. **IssuiThe posting is identical either way (cost out of inventory, into WIP), so the choice is about floor discipline, not accounting. Issue as you go when you need tight control over what's consumed; lean on backflush for the routine material you'd rather not hand-count.-<Callout tone="neutral" badge="SCRAP STAYS IN WIP" title="Scrapped material is consumed cost, too.">-<Term>Scrap</Term> and <Term>rework</Term> are recorded as their own production quantities, but scrapping a tracked part posts the same consumption: out of inventory, into the job's WIP. There's no separate scrap account; the cost of what you ruined rides along in the job until it settles at close.+<Callout tone="neutral" badge="SCRAP LEAVES WIP" title="Ruined cost is relieved to a scrap account, not carried to close.">+<Term>Scrap</Term> and <Term>rework</Term> are recorded as their own production quantities. Scrapping a tracked part relieves its cost from the job: debited to a dedicated scrap account and credited out of WIP (or straight out of inventory, for a part still in stock), tagged with the reason, work center, and operator. The ruined value leaves the job rather than riding along to close, and the scrap reopens the routing so a replacement gets built. See [scrap and unscrap](/docs/reference/scrap).</Callout>## WIP isn't a tablediff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 21cb7864ac..5e65c7e39f 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -19383,6 +19383,9 @@ export default {{$ref: "#/parameters/rowFilter.itemLedger.correctionOfItemLedgerId"},+ {+ $ref: "#/parameters/rowFilter.itemLedger.scrapReasonId"+ },{$ref: "#/parameters/select"},@@ -19502,6 +19505,9 @@ export default {{$ref: "#/parameters/rowFilter.itemLedger.correctionOfItemLedgerId"},+ {+ $ref: "#/parameters/rowFilter.itemLedger.scrapReasonId"+ },{$ref: "#/parameters/preferReturn"}@@ -19575,6 +19581,9 @@ export default {{$ref: "#/parameters/rowFilter.itemLedger.correctionOfItemLedgerId"},+ {+ $ref: "#/parameters/rowFilter.itemLedger.scrapReasonId"+ },{$ref: "#/parameters/body.itemLedger"},@@ -85222,6 +85231,47 @@ export default {tags: ["(rpc) sync_contact_to_parent"]}},+ "/rpc/get_timezone_names": {+ get: {+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_timezone_names"]+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_timezone_names"]+ }+ },"/rpc/sync_insert_quote_line_make_method": {post: {parameters: [@@ -88790,6 +88840,63 @@ export default {tags: ["(rpc) xid_pid"]}},+ "/rpc/is_valid_timezone": {+ get: {+ parameters: [+ {+ format: "text",+ in: "query",+ name: "tz",+ required: true,+ type: "string"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) is_valid_timezone"]+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ tz: {+ format: "text",+ type: "string"+ }+ },+ required: ["tz"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) is_valid_timezone"]+ }+ },"/rpc/upsert_to_search_index": {post: {parameters: [@@ -89155,6 +89262,74 @@ export default {tags: ["(rpc) sync_create_item_related_records"]}},+ "/rpc/location_today": {+ get: {+ parameters: [+ {+ format: "text",+ in: "query",+ name: "p_location_id",+ required: true,+ type: "string"+ },+ {+ format: "text",+ in: "query",+ name: "p_company_id",+ required: true,+ type: "string"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) location_today"]+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string"+ },+ p_location_id: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_location_id", "p_company_id"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) location_today"]+ }+ },"/rpc/get_active_job_count": {post: {parameters: [@@ -98209,7 +98384,8 @@ export default {"FixedAssetClass","Customer","Supplier",- "Item"+ "Item",+ "ScrapReason"],format: 'public."dimensionEntityType"',type: "string"@@ -104244,7 +104420,8 @@ export default {"Maintenance Consumption","Non-Conformance","Inbound Inspection",- "Inventory Count"+ "Inventory Count",+ "Scrap"],format: 'public."itemLedgerDocumentType"',type: "string"@@ -104312,7 +104489,14 @@ export default {type: "string"},trackedEntityStatus: {- enum: ["Available", "Reserved", "On Hold", "Consumed", "Rejected"],+ enum: [+ "Available",+ "Reserved",+ "On Hold",+ "Consumed",+ "Rejected",+ "Scrapped"+ ],format: 'public."trackedEntityStatus"',type: "string"},@@ -104325,6 +104509,12 @@ export default {correctionOfItemLedgerId: {format: "text",type: "string"+ },+ scrapReasonId: {+ description:+ "Note:\nThis is a Foreign Key to `scrapReason.id`.<fk table='scrapReason' column='id'/>",+ format: "text",+ type: "string"}},type: "object"@@ -108989,7 +109179,8 @@ export default {"Maintenance Consumption","Non-Conformance","Inbound Inspection",- "Inventory Count"+ "Inventory Count",+ "Scrap"],format: 'public."itemLedgerDocumentType"',type: "string"@@ -109055,7 +109246,14 @@ export default {type: "string"},trackedEntityStatus: {- enum: ["Available", "Reserved", "On Hold", "Consumed", "Rejected"],+ enum: [+ "Available",+ "Reserved",+ "On Hold",+ "Consumed",+ "Rejected",+ "Scrapped"+ ],format: 'public."trackedEntityStatus"',type: "string"},@@ -109535,7 +109733,8 @@ export default {"Inventory Adjustment","Inventory Count","Non-Conformance",- "Inbound Inspection"+ "Inbound Inspection",+ "Scrap"],format: 'public."journalLineDocumentType"',type: "string"@@ -120181,7 +120380,14 @@ export default {},status: {default: "Available",- enum: ["Available", "Reserved", "On Hold", "Consumed", "Rejected"],+ enum: [+ "Available",+ "Reserved",+ "On Hold",+ "Consumed",+ "Rejected",+ "Scrapped"+ ],format: 'public."trackedEntityStatus"',type: "string"},@@ -121663,7 +121869,8 @@ export default {"Maintenance Consumption","Non-Conformance","Inbound Inspection",- "Inventory Count"+ "Inventory Count",+ "Scrap"],format: 'public."itemLedgerDocumentType"',type: "string"@@ -121869,7 +122076,8 @@ export default {"Inventory Adjustment","Inventory Count","Non-Conformance",- "Inbound Inspection"+ "Inbound Inspection",+ "Scrap"],format: 'public."journalLineDocumentType"',type: "string"@@ -122048,7 +122256,8 @@ export default {"Inventory Adjustment","Inventory Count","Non-Conformance",- "Inbound Inspection"+ "Inbound Inspection",+ "Scrap"],format: 'public."journalLineDocumentType"',type: "string"@@ -123004,7 +123213,8 @@ export default {"FixedAssetClass","Customer","Supplier",- "Item"+ "Item",+ "ScrapReason"],format: 'public."dimensionEntityType"',type: "string"@@ -145866,6 +146076,12 @@ export default {in: "query",type: "string"},+ "rowFilter.itemLedger.scrapReasonId": {+ name: "scrapReasonId",+ required: false,+ in: "query",+ type: "string"+ },"body.shippingTerm": {name: "shippingTerm",description: "shippingTerm",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex f93d3e2bce..851793b9bb 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -19549,6 +19549,7 @@ export type Database = {locationId: string | nullpostingDate: stringquantity: number+ scrapReasonId: string | nullstorageUnitId: string | nulltrackedEntityId: string | nulltrackedEntityStatus:@@ -19575,6 +19576,7 @@ export type Database = {locationId?: string | nullpostingDate?: stringquantity: number+ scrapReasonId?: string | nullstorageUnitId?: string | nulltrackedEntityId?: string | nulltrackedEntityStatus?:@@ -19601,6 +19603,7 @@ export type Database = {locationId?: string | nullpostingDate?: stringquantity?: number+ scrapReasonId?: string | nullstorageUnitId?: string | nulltrackedEntityId?: string | nulltrackedEntityStatus?:@@ -19693,6 +19696,13 @@ export type Database = {referencedRelation: "location"referencedColumns: ["id"]},+ {+ foreignKeyName: "itemLedger_scrapReasonId_fkey"+ columns: ["scrapReasonId"]+ isOneToOne: false+ referencedRelation: "scrapReason"+ referencedColumns: ["id"]+ },{foreignKeyName: "itemLedger_storageUnitId_fkey"columns: ["storageUnitId"]@@ -70160,21 +70170,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -76596,6 +76606,7 @@ export type Database = {| "Customer"| "Supplier"| "Item"+ | "ScrapReason"disposalMethod: "Sale" | "Scrapping"disposition:| "Conditional Acceptance"@@ -76760,6 +76771,7 @@ export type Database = {| "Non-Conformance"| "Inbound Inspection"| "Inventory Count"+ | "Scrap"itemLedgerType:| "Purchase"| "Sale"@@ -76854,6 +76866,7 @@ export type Database = {| "Inventory Count"| "Non-Conformance"| "Inbound Inspection"+ | "Scrap"kanbanOutput: "label" | "qrcode" | "url"macrsConvention: "Half-Year" | "Mid-Quarter"macrsPropertyClass: "3" | "5" | "7" | "10" | "15" | "20" | "27.5" | "39"@@ -77165,6 +77178,7 @@ export type Database = {| "On Hold"| "Consumed"| "Rejected"+ | "Scrapped"trackingSource: "Purchased" | "Manufactured"trainingFrequency: "Once" | "Quarterly" | "Annual"trainingQuestionType:@@ -77956,6 +77970,7 @@ export const Constants = {"Customer","Supplier","Item",+ "ScrapReason",],disposalMethod: ["Sale", "Scrapping"],disposition: [@@ -78134,6 +78149,7 @@ export const Constants = {"Non-Conformance","Inbound Inspection","Inventory Count",+ "Scrap",],itemLedgerType: ["Purchase",@@ -78236,6 +78252,7 @@ export const Constants = {"Inventory Count","Non-Conformance","Inbound Inspection",+ "Scrap",],kanbanOutput: ["label", "qrcode", "url"],macrsConvention: ["Half-Year", "Mid-Quarter"],@@ -78579,6 +78596,7 @@ export const Constants = {"On Hold","Consumed","Rejected",+ "Scrapped",],trackingSource: ["Purchased", "Manufactured"],trainingFrequency: ["Once", "Quarterly", "Annual"],diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.tsindex 63c63f66ef..f60eefbbdd 100644--- a/packages/database/supabase/functions/issue/index.ts+++ b/packages/database/supabase/functions/issue/index.ts@@ -14,11 +14,14 @@ import {} from "../lib/storage-units.ts";import { requirePermissions } from "../lib/supabase.ts";import { Database } from "../lib/types.ts";+import type { Json } from "../lib/types.ts";import { TrackedEntityAttributes, credit, debit, journalReference } from "../lib/utils.ts";import { buildBatchSplitRecords } from "../shared/batch-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";+import { applyScrapReplacement } from "./scrap-replacement.ts";import { getNextSerialNumbers } from "../shared/get-next-serial-number.ts";import {getDefaultPostingGroup,@@ -172,7 +175,7 @@ async function issueJobOperationMaterials(materialsToIssue.push(...materialsToIssueFromKittedChildren);}- if (materialsToIssue.length === 0) return;+ if (materialsToIssue.length === 0) return { totalMaterialCost: 0 };const jobId = materialsToIssue[0].jobId;@@ -318,6 +321,12 @@ async function issueJobOperationMaterials(.execute();}+ // Total material cost this call relieved from inventory into WIP — the+ // jobOperationScrap case posts its WIP→scrap journal from this figure so a+ // second calculateCOGS pass never double-relieves cost layers. 0 when+ // accounting is disabled (no journal needed).+ let totalMaterialCost = 0;+if (itemLedgerInserts.length > 0) {await trx.insertInto("itemLedger").values(itemLedgerInserts).execute();@@ -391,6 +400,7 @@ async function issueJobOperationMaterials(quantity: materialQuantity,companyId,});+ totalMaterialCost += cogsResult.totalCost;const journalLineReference = nanoid();@@ -529,6 +539,8 @@ async function issueJobOperationMaterials(}}}++ return { totalMaterialCost };}async function createMaterialWipEntries(@@ -852,6 +864,19 @@ const payloadValidator = z.discriminatedUnion("type", [inspectionId: z.string().optional(),inspectionSampleId: z.string().optional(),}),+ z.object({+ type: z.literal("jobOperationScrap"),+ jobOperationId: z.string(),+ quantity: z.number().positive(),+ scrapReasonId: z.string(),+ trackedEntityId: z.string().optional(),+ notes: z.string().optional(),+ laborProductionEventId: z.string().optional(),+ machineProductionEventId: z.string().optional(),+ setupProductionEventId: z.string().optional(),+ companyId: z.string(),+ userId: z.string(),+ }),z.object({type: z.literal("partToOperation"),id: z.string(),@@ -874,6 +899,8 @@ const payloadValidator = z.discriminatedUnion("type", [trackedEntityId: z.string(),materialId: z.string(),parentTrackedEntityId: z.string(),+ scrapReasonId: z.string(),+ makeReplacement: z.boolean().optional(),companyId: z.string(),userId: z.string(),}),@@ -1384,6 +1411,481 @@ serve(async (req: Request) => {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",+ });++ 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 [+ 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(),+ ]);+ 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 accountingEnabledScrapOp =+ accountingSettingsScrapOp.data?.accountingEnabled ?? false;+ const accountDefaultsScrapOp = accountingEnabledScrapOp+ ? await getDefaultPostingGroup(client, companyId)+ : null;+ if (+ accountingEnabledScrapOp &&+ (accountDefaultsScrapOp?.error || !accountDefaultsScrapOp?.data)+ ) {+ throw new Error("Error getting account defaults");+ }++ const dimensionsScrapOp = accountingEnabledScrapOp+ ? await client+ .from("dimension")+ .select("id, entityType")+ .eq("companyGroupId", companyRecordScrapOp.data.companyGroupId)+ .eq("active", true)+ .in("entityType", [+ "ItemPostingGroup",+ "Item",+ "Location",+ "ScrapReason",+ "WorkCenter",+ "Employee",+ ])+ : 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 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,+ quantity,+ companyId,+ userId,+ accountingEnabled: accountingEnabledScrapOp,+ accountDefaults: accountDefaultsScrapOp?.data+ ? accountDefaultsScrapOp+ : null,+ dimensionMap: dimensionMapScrapOp,+ 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)+ .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;++ const scrapActivityId = nanoid();+ await trx+ .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,+ createdBy: userId,+ })+ .execute();+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: scrapActivityId,+ trackedEntityId: scrapEntityId,+ 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",+ 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;+ }++ 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 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();++ 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();++ 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();+ }+ }+ }+ });++ // 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) {+ console.error(+ "Failed to trigger reschedule after scrap:",+ rescheduleError+ );+ }++ return jsonResponse({+ success: true,+ newTrackedEntityId: newEntityId,+ });+ }case "partToOperation": {const {id,@@ -1684,18 +2186,28 @@ serve(async (req: Request) => {trackedEntityId,materialId,parentTrackedEntityId,+ scrapReasonId,+ makeReplacement,companyId,userId,} = validatedPayload;- const client = await requirePermissions(req, companyId, userId, { update: "production" });+ 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(),- client.from("jobMaterial").select("*").eq("id", materialId).single(),]);if (!trackedEntity.data) {@@ -1705,6 +2217,9 @@ serve(async (req: Request) => {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 [accountingSettingsScrap, companyRecordScrap] = await Promise.all([client@@ -1730,7 +2245,14 @@ serve(async (req: Request) => {.select("id, entityType").eq("companyGroupId", companyRecordScrap.data.companyGroupId).eq("active", true)- .in("entityType", ["ItemPostingGroup", "Item", "Location"])+ .in("entityType", [+ "ItemPostingGroup",+ "Item",+ "Location",+ "ScrapReason",+ "WorkCenter",+ "Employee",+ ]): null;const dimensionMapScrap = new Map<string, string>();@@ -1740,21 +2262,23 @@ serve(async (req: Request) => {}}+ 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 itemLedger = await trx- .selectFrom("itemLedger")- .where("trackedEntityId", "=", trackedEntityId)- .orderBy("createdAt", "desc")- .selectAll()- .executeTakeFirst();-const job = await trx.selectFrom("job")- .select(["id", "locationId", "itemId"])+ .select(["id", "jobId", "locationId", "itemId"]).where("id", "=", material.jobId!).executeTakeFirst();@@ -1764,12 +2288,14 @@ serve(async (req: Request) => {.select(["readableIdWithRevision"]).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: "Consume",+ type: "Scrap",sourceDocument: "Job Material",sourceDocumentId: materialId,sourceDocumentReadableId: item?.readableIdWithRevision ?? "",@@ -1777,8 +2303,8 @@ serve(async (req: Request) => {Job: job?.id!,"Job Make Method": material.jobMakeMethodId!,"Job Material": material.id!,+ "Scrap Reason": scrapReasonId,Employee: userId,- Scrapped: true,},companyId,createdBy: userId,@@ -1812,60 +2338,351 @@ serve(async (req: Request) => {await trx.updateTable("trackedEntity").set({- status: "Consumed",+ status: "Scrapped",}).where("id", "=", trackedEntityId).execute();- if (material.methodType !== "Make to Order") {- await trx- .insertInto("itemLedger")- .values({- entryType: "Consumption",- documentType: "Job Consumption",- documentId: job?.id!,- companyId,- itemId: entity.sourceDocumentId!,- quantity: -quantity,- locationId: job?.locationId ?? itemLedger?.locationId,- storageUnitId: itemLedger?.storageUnitId,+ 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();+ }+ }++ // 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();+ }- if (accountingEnabledScrap && accountDefaultsScrap?.data) {- await createMaterialWipEntries(trx, {- consumptionLedgers: [{ itemId: entity.sourceDocumentId!, quantity: -quantity }],- jobId: job?.id!,- operationId: material.jobOperationId!,- description: `Scrap — ${item?.readableIdWithRevision ?? ""}`,- wipAccount: accountDefaultsScrap.data.workInProgressAccount,- rawMaterialsAccount: accountDefaultsScrap.data.rawMaterialsAccount,- finishedGoodsAccount: accountDefaultsScrap.data.finishedGoodsAccount,- dimensionMap: dimensionMapScrap,-- jobLocationId: job?.locationId ?? null,- client,- db,+ // 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,});- }- }- const currentQuantityIssued = Number(material.quantityIssued) || 0;- const newQuantityIssued = currentQuantityIssued + 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();+ }- await trx- .updateTable("jobMaterial")- .set({- quantityIssued: newQuantityIssued,- })- .where("id", "=", materialId)- .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) {+ console.error(+ "Failed to trigger reschedule after scrap:",+ rescheduleError+ );+ }+ }+return jsonResponse({success: true,});diff --git a/packages/database/supabase/functions/issue/scrap-replacement.ts b/packages/database/supabase/functions/issue/scrap-replacement.tsnew file mode 100644index 0000000000..622c3d2d7e--- /dev/null+++ b/packages/database/supabase/functions/issue/scrap-replacement.ts@@ -0,0 +1,143 @@+import { Transaction } from "kysely";+import { DB } from "../lib/database.ts";++// Reopen + capacity top-up after scrapping units of a make method, so the+// replacement units can run the FULL routing (spec+// .ai/specs/2026-08-06-scrap-unscrap-flow.md §1.6).+//+// - Done operations reopen to Ready (never Canceled); the quantity-sync+// interceptor re-flips them once good quantity reaches targetQuantity —+// which scrap no longer counts toward (20260807090629).+// - targetQuantity is NEVER written: it is the good quantity to produce.+// - operationQuantity (capacity incl. planned scrap allowance) is topped up+// only when cumulative actual scrap exceeds the allowance:+// needed = targetQuantity + totalScrapped; bump = max(0, needed − current).+// - job.scrapQuantity mirrors the same monotonic rule for the ROOT make+// method so the generated job.productionQuantity stays coherent.+// - jobMaterial estimates grow by their per-parent quantity × the bump so+// backflush caps (estimatedQuantity − quantityIssued) cover the+// replacement units. Make-to-Order children are excluded (their capacity+// is their own make method's).+export async function applyScrapReplacement(+ trx: Transaction<DB>,+ args: {+ jobMakeMethodId: string;+ jobId: string;+ companyId: string;+ userId: string;+ }+): Promise<{ addedQuantity: number }> {+ const { jobMakeMethodId, jobId, companyId, userId } = args;++ const operations = await trx+ .selectFrom("jobOperation")+ .select(["id", "status", "operationQuantity", "targetQuantity"])+ .where("jobMakeMethodId", "=", jobMakeMethodId)+ .where("companyId", "=", companyId)+ .execute();+ if (operations.length === 0) return { addedQuantity: 0 };++ // Cumulative actual scrap for this make method, read from productionQuantity+ // directly so the math is independent of interceptor timing.+ const scrapTotal = await trx+ .selectFrom("productionQuantity")+ .select((eb) => eb.fn.sum("quantity").as("quantity"))+ .where("type", "=", "Scrap")+ .where("companyId", "=", companyId)+ .where(+ "jobOperationId",+ "in",+ operations.map((op) => op.id)+ )+ .executeTakeFirst();+ const totalScrapped = Number(scrapTotal?.quantity ?? 0);++ await trx+ .updateTable("jobOperation")+ .set({+ status: "Ready",+ updatedBy: userId,+ updatedAt: new Date().toISOString(),+ })+ .where("jobMakeMethodId", "=", jobMakeMethodId)+ .where("companyId", "=", companyId)+ .where("status", "=", "Done")+ .execute();++ let addedQuantity = 0;+ for (const operation of operations) {+ const target = Number(operation.targetQuantity ?? 0);+ if (target <= 0) continue;+ const current = Number(operation.operationQuantity ?? 0);+ const needed = target + totalScrapped;+ const bump = Math.max(0, needed - current);+ if (bump <= 0) continue;+ addedQuantity = Math.max(addedQuantity, bump);+ await trx+ .updateTable("jobOperation")+ .set({+ operationQuantity: needed,+ updatedBy: userId,+ updatedAt: new Date().toISOString(),+ })+ .where("id", "=", operation.id)+ .execute();+ }++ if (addedQuantity > 0) {+ // Root make method drives the job header's planned-scrap bucket.+ const makeMethod = await trx+ .selectFrom("jobMakeMethod")+ .select(["parentMaterialId"])+ .where("id", "=", jobMakeMethodId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (makeMethod && makeMethod.parentMaterialId === null) {+ const job = await trx+ .selectFrom("job")+ .select(["scrapQuantity"])+ .where("id", "=", jobId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ const currentScrapQuantity = Number(job?.scrapQuantity ?? 0);+ if (totalScrapped > currentScrapQuantity) {+ await trx+ .updateTable("job")+ .set({+ scrapQuantity: totalScrapped,+ updatedBy: userId,+ updatedAt: new Date().toISOString(),+ })+ .where("id", "=", jobId)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ // Grow material requirements for the replacement units (mirrors+ // recalculateJobRequirements' per-parent math, which is ERP-side and+ // unavailable in Deno).+ const materials = await trx+ .selectFrom("jobMaterial")+ .select(["id", "quantity", "estimatedQuantity"])+ .where("jobMakeMethodId", "=", jobMakeMethodId)+ .where("companyId", "=", companyId)+ .where("methodType", "!=", "Make to Order")+ .execute();+ for (const material of materials) {+ const perParent = Number(material.quantity) || 0;+ if (perParent <= 0) continue;+ await trx+ .updateTable("jobMaterial")+ .set({+ estimatedQuantity:+ Number(material.estimatedQuantity ?? 0) ++ perParent * addedQuantity,+ })+ .where("id", "=", material.id)+ .execute();+ }+ }++ return { addedQuantity };+}diff --git a/packages/database/supabase/functions/lib/seed.data.ts b/packages/database/supabase/functions/lib/seed.data.tsindex 5c780397b5..bf579991ae 100644--- a/packages/database/supabase/functions/lib/seed.data.ts+++ b/packages/database/supabase/functions/lib/seed.data.ts@@ -19,6 +19,7 @@ export const dimensions = [{ name: "Customer", entityType: "Customer" },{ name: "Supplier", entityType: "Supplier" },{ name: "Item", entityType: "Item" },+ { name: "Scrap Reason", entityType: "ScrapReason" },] as const;export const supplierStatuses = [diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex f93d3e2bce..851793b9bb 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -19549,6 +19549,7 @@ export type Database = {locationId: string | nullpostingDate: stringquantity: number+ scrapReasonId: string | nullstorageUnitId: string | nulltrackedEntityId: string | nulltrackedEntityStatus:@@ -19575,6 +19576,7 @@ export type Database = {locationId?: string | nullpostingDate?: stringquantity: number+ scrapReasonId?: string | nullstorageUnitId?: string | nulltrackedEntityId?: string | nulltrackedEntityStatus?:@@ -19601,6 +19603,7 @@ export type Database = {locationId?: string | nullpostingDate?: stringquantity?: number+ scrapReasonId?: string | nullstorageUnitId?: string | nulltrackedEntityId?: string | nulltrackedEntityStatus?:@@ -19693,6 +19696,13 @@ export type Database = {referencedRelation: "location"referencedColumns: ["id"]},+ {+ foreignKeyName: "itemLedger_scrapReasonId_fkey"+ columns: ["scrapReasonId"]+ isOneToOne: false+ referencedRelation: "scrapReason"+ referencedColumns: ["id"]+ },{foreignKeyName: "itemLedger_storageUnitId_fkey"columns: ["storageUnitId"]@@ -70160,21 +70170,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -76596,6 +76606,7 @@ export type Database = {| "Customer"| "Supplier"| "Item"+ | "ScrapReason"disposalMethod: "Sale" | "Scrapping"disposition:| "Conditional Acceptance"@@ -76760,6 +76771,7 @@ export type Database = {| "Non-Conformance"| "Inbound Inspection"| "Inventory Count"+ | "Scrap"itemLedgerType:| "Purchase"| "Sale"@@ -76854,6 +76866,7 @@ export type Database = {| "Inventory Count"| "Non-Conformance"| "Inbound Inspection"+ | "Scrap"kanbanOutput: "label" | "qrcode" | "url"macrsConvention: "Half-Year" | "Mid-Quarter"macrsPropertyClass: "3" | "5" | "7" | "10" | "15" | "20" | "27.5" | "39"@@ -77165,6 +77178,7 @@ export type Database = {| "On Hold"| "Consumed"| "Rejected"+ | "Scrapped"trackingSource: "Purchased" | "Manufactured"trainingFrequency: "Once" | "Quarterly" | "Annual"trainingQuestionType:@@ -77956,6 +77970,7 @@ export const Constants = {"Customer","Supplier","Item",+ "ScrapReason",],disposalMethod: ["Sale", "Scrapping"],disposition: [@@ -78134,6 +78149,7 @@ export const Constants = {"Non-Conformance","Inbound Inspection","Inventory Count",+ "Scrap",],itemLedgerType: ["Purchase",@@ -78236,6 +78252,7 @@ export const Constants = {"Inventory Count","Non-Conformance","Inbound Inspection",+ "Scrap",],kanbanOutput: ["label", "qrcode", "url"],macrsConvention: ["Half-Year", "Mid-Quarter"],@@ -78579,6 +78596,7 @@ export const Constants = {"On Hold","Consumed","Rejected",+ "Scrapped",],trackingSource: ["Purchased", "Manufactured"],trainingFrequency: ["Once", "Quarterly", "Annual"],diff --git a/packages/database/supabase/functions/post-inventory-adjustment/index.ts b/packages/database/supabase/functions/post-inventory-adjustment/index.tsindex 90161ef0c9..e5d104be17 100644--- a/packages/database/supabase/functions/post-inventory-adjustment/index.ts+++ b/packages/database/supabase/functions/post-inventory-adjustment/index.ts@@ -1,7 +1,9 @@import { format } from "https://deno.land/[email protected]/datetime/mod.ts";import { serve } from "https://deno.land/[email protected]/http/server.ts";+import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";import { z } from "https://deno.land/x/[email protected]/mod.ts";import { Transaction } from "kysely";+import { buildBatchSplitRecords } from "../shared/batch-split.ts";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";@@ -11,6 +13,7 @@ import type { Json } from "../lib/types.ts";import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";import { bookAdjustment } from "../shared/post-adjustment.ts";+import { resolveUnscrapUnitCost } from "./resolve-unscrap-cost.ts";const pool = getConnectionPool(1);const db = getDatabaseClient<DB>(pool);@@ -24,22 +27,48 @@ const logger = getFunctionLogger("post-inventory-adjustment");// cost layers + (when companySettings.accountingEnabled) a balanced journal// against the inventory adjustment variance account. Storage-unit transfers// move value-neutral stock and never post to the GL.-const payloadValidator = z.object({- adjustmentType: z.enum(["Positive Adjmt.", "Negative Adjmt.", "Set Quantity"]),- itemId: z.string(),- locationId: z.string(),- storageUnitId: z.string().optional().nullable(),- trackedEntityId: z.string().optional().nullable(),- // 0 is legal for Set Quantity (set to zero); a negative magnitude is never- // valid — direction comes from adjustmentType, not the sign.- quantity: z.number().min(0),- readableId: z.string().optional().nullable(),- originalStorageUnitId: z.string().optional().nullable(),- expirationDate: z.string().optional().nullable(),- comment: z.string().optional().nullable(),- companyId: z.string(),- userId: z.string(),-});+const payloadValidator = z+ .object({+ adjustmentType: z.enum([+ "Positive Adjmt.",+ "Negative Adjmt.",+ "Set Quantity",+ "Scrap",+ "Unscrap",+ ]),+ itemId: z.string(),+ // Optional for Unscrap (resolved from the original scrap movement);+ // required for every other type, enforced by the app-layer validator.+ locationId: z.string().optional().nullable(),+ storageUnitId: z.string().optional().nullable(),+ trackedEntityId: z.string().optional().nullable(),+ // 0 is legal for Set Quantity (set to zero) and for a tracked Scrap/Unscrap+ // (full-entity quantity is resolved server-side); a negative magnitude is+ // never valid — direction comes from adjustmentType, not the sign.+ quantity: z.number().min(0),+ readableId: z.string().optional().nullable(),+ originalStorageUnitId: z.string().optional().nullable(),+ expirationDate: z.string().optional().nullable(),+ comment: z.string().optional().nullable(),+ // Required for Scrap (enforced below) — lands on the itemLedger row and,+ // when accounting is enabled, as a ScrapReason journal dimension. Unscrap+ // omits it: the reason is inherited from the original scrap movement.+ scrapReasonId: z.string().optional().nullable(),+ // Unscrap: the original scrap itemLedger row to reverse against. Optional —+ // resolved server-side from the tracked entity's newest Scrap movement.+ unscrapOfItemLedgerId: z.string().optional().nullable(),+ companyId: z.string(),+ userId: z.string(),+ })+ .superRefine((data, ctx) => {+ if (data.adjustmentType === "Scrap" && !data.scrapReasonId) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["scrapReasonId"],+ message: "Scrap reason is required",+ });+ }+ });// Business-validation failures are 400s with the exact message the app routes// string-match on; everything else is a 500 so real outages surface in@@ -56,7 +85,7 @@ serve(async (req: Request) => {const {adjustmentType,itemId,- locationId,+ locationId: payloadLocationId,storageUnitId,trackedEntityId,quantity,@@ -64,10 +93,16 @@ serve(async (req: Request) => {originalStorageUnitId,expirationDate: providedExpirationDate,comment,+ scrapReasonId,+ unscrapOfItemLedgerId,companyId,userId,} = payloadValidator.parse(payload);+ // Unscrap sends no location (resolved from the scrap movement); every+ // other type carries one (app-layer validator enforces it).+ const locationId: string | null = payloadLocationId ?? null;+const client = await requirePermissions(req, companyId, userId, {update: "inventory",});@@ -85,7 +120,7 @@ serve(async (req: Request) => {client.rpc("get_item_quantities_by_tracking_id", {item_id: itemId,company_id: companyId,- location_id: locationId,+ location_id: locationId ?? "",}),client.from("item")@@ -158,7 +193,14 @@ serve(async (req: Request) => {.select("id, entityType").eq("companyGroupId", companyRecord.data.companyGroupId).eq("active", true)- .in("entityType", ["Item", "ItemPostingGroup", "Location"]);+ .in("entityType", [+ "Item",+ "ItemPostingGroup",+ "Location",+ "ScrapReason",+ "WorkCenter",+ "Employee",+ ]);// Fail closed: journal lines must not silently lose dimension tags.if (dimensions.error) throw new Error("Failed to fetch dimensions");for (const dim of dimensions.data ?? []) {@@ -296,7 +338,422 @@ serve(async (req: Request) => {originalStorageUnitId &&originalStorageUnitId !== storageUnitId;+ // Scrap/Unscrap offset to the company's scrapAccount (fallback per the+ // 20260726012013 seed comment) so cost of quality is separable on the P&L;+ // analysis slices by dimension (ScrapReason / Employee + the standard trio)+ // instead of by account.+ const scrapAccounting = accounting+ ? {+ ...accounting,+ offsetAccount:+ accountDefaults?.data?.scrapAccount ??+ accounting.accountDefaults.inventoryAdjustmentVarianceAccount,+ offsetDescription: "Scrap Account",+ extraDimensions: [+ ...(scrapReasonId+ ? [{ entityType: "ScrapReason", valueId: scrapReasonId }]+ : []),+ { entityType: "Employee", valueId: userId },+ ],+ }+ : null;+await db.transaction().execute(async (trx) => {+ if (adjustmentType === "Scrap") {+ const scrapLedgerBase = {+ ...ledgerBase,+ documentType: "Scrap" as const,+ scrapReasonId,+ entryType: "Negative Adjmt." as const,+ };+ const accountingForScrap = scrapAccounting+ ? {+ ...scrapAccounting,+ description: comment?.trim()+ ? `Scrap — ${comment.trim()}`+ : "Scrap",+ }+ : null;++ if (trackedEntityId) {+ const entity = await trx+ .selectFrom("trackedEntity")+ .select([+ "id",+ "quantity",+ "status",+ "readableId",+ "sourceDocument",+ "sourceDocumentId",+ "sourceDocumentReadableId",+ "itemId",+ "expirationDate",+ "attributes",+ ])+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!entity) throw new ValidationError("Tracked entity not found");+ if (entity.status !== "Available") {+ throw new ValidationError(+ "Only available tracked entities can be scrapped"+ );+ }+ const entityQuantity = Number(entity.quantity) || 0;+ // quantity 0 ⇒ scrap the whole entity (serial UIs don't send a qty)+ const scrapQuantity = quantity > 0 ? quantity : entityQuantity;+ if (scrapQuantity > entityQuantity) {+ throw new ValidationError("Insufficient quantity for scrap");+ }+ const bin =+ currentQuantity?.storageUnitId ?? storageUnitId ?? null;++ let scrappedEntityId = trackedEntityId;+ if (scrapQuantity < entityQuantity) {+ // Partial batch scrap: identity-flip split — the parent keeps its+ // id and is decremented; the departing child is the Scrapped+ // record of what left.+ const split = buildBatchSplitRecords({+ parent: {+ id: entity.id,+ readableId: entity.readableId,+ quantity: entityQuantity,+ sourceDocument: entity.sourceDocument,+ sourceDocumentId: entity.sourceDocumentId,+ sourceDocumentReadableId: entity.sourceDocumentReadableId,+ itemId: entity.itemId,+ expirationDate: entity.expirationDate+ ? String(entity.expirationDate)+ : null,+ attributes:+ (entity.attributes as Record<string, unknown> | null) ?? null,+ },+ drawQuantity: scrapQuantity,+ childId: nanoid(),+ splitActivityId: nanoid(),+ activitySourceDocument: "Item",+ activitySourceDocumentId: itemId,+ bin: { storageUnitId: bin, locationId },+ itemLedgerItemId: itemId,+ companyId,+ userId,+ postingDate: today,+ childStatus: "Scrapped",+ });+ await trx+ .insertInto("trackedEntity")+ .values({+ ...split.childEntityInsert,+ sourceDocument:+ split.childEntityInsert.sourceDocument ?? "Item",+ sourceDocumentId:+ split.childEntityInsert.sourceDocumentId ?? itemId,+ attributes: split.childEntityInsert+ .attributes as unknown as Json,+ })+ .execute();+ await trx+ .updateTable("trackedEntity")+ .set(split.parentUpdate)+ .where("id", "=", entity.id)+ .where("companyId", "=", companyId)+ .execute();+ await trx+ .insertInto("trackedActivity")+ .values({+ ...split.activityInsert,+ attributes: split.activityInsert+ .attributes as unknown as Json,+ })+ .execute();+ await trx+ .insertInto("trackedActivityInput")+ .values(split.activityInputInsert)+ .execute();+ await trx+ .insertInto("trackedActivityOutput")+ .values(split.activityOutputInsert)+ .execute();+ await trx+ .insertInto("itemLedger")+ .values(+ split.ledgerInserts.map((ledgerRow) => ({+ ...ledgerRow,+ itemId: ledgerRow.itemId ?? itemId,+ }))+ )+ .execute();+ scrappedEntityId = split.childEntityInsert.id;+ } else {+ // Full-entity scrap: terminal status flip; the entity KEEPS its+ // quantity as the record of what was scrapped (the negative+ // ledger row below carries the stock decrement).+ await trx+ .updateTable("trackedEntity")+ .set({ status: "Scrapped" })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();+ }++ const scrapActivityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: scrapActivityId,+ type: "Scrap",+ sourceDocument: "Item",+ sourceDocumentId: itemId,+ attributes: {+ "Scrap Reason": scrapReasonId,+ Employee: userId,+ ...(comment?.trim() ? { Notes: comment.trim() } : {}),+ },+ companyId,+ createdBy: userId,+ })+ .execute();+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: scrapActivityId,+ trackedEntityId: scrappedEntityId,+ quantity: scrapQuantity,+ companyId,+ createdBy: userId,+ })+ .execute();++ const booked = await bookAdjustment(trx, {+ ledger: {+ ...scrapLedgerBase,+ trackedEntityId: scrappedEntityId,+ storageUnitId: bin,+ quantity: -Math.abs(scrapQuantity),+ },+ item,+ itemCost,+ accounting: accountingForScrap,+ });+ resultLedgerId = booked.itemLedgerId;+ return;+ }++ // Untracked scrap: negative movement from the bin's untracked stock.+ if (quantity <= 0) {+ throw new ValidationError("Scrap quantity must be greater than zero");+ }+ const untrackedRow = trackingRows.find(+ (q) => q.trackedEntityId == null && q.storageUnitId == storageUnitId+ );+ if ((untrackedRow?.quantity ?? 0) < quantity) {+ throw new ValidationError("Insufficient quantity for scrap");+ }+ const booked = await bookAdjustment(trx, {+ ledger: {+ ...scrapLedgerBase,+ trackedEntityId: null,+ quantity: -Math.abs(quantity),+ },+ item,+ itemCost,+ accounting: accountingForScrap,+ });+ resultLedgerId = booked.itemLedgerId;+ return;+ }++ if (adjustmentType === "Unscrap") {+ const unscrapLedgerBase = {+ ...ledgerBase,+ documentType: "Scrap" as const,+ scrapReasonId,+ entryType: "Positive Adjmt." as const,+ };+ const accountingForUnscrap = scrapAccounting+ ? {+ ...scrapAccounting,+ description: comment?.trim()+ ? `Unscrap — ${comment.trim()}`+ : "Unscrap",+ }+ : null;++ if (trackedEntityId) {+ const entity = await trx+ .selectFrom("trackedEntity")+ .select(["id", "quantity", "status"])+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!entity) throw new ValidationError("Tracked entity not found");+ if (entity.status !== "Scrapped") {+ throw new ValidationError(+ "Only scrapped tracked entities can be unscrapped"+ );+ }+ const entityQuantity = Number(entity.quantity) || 0;+ if (entityQuantity <= 0) {+ throw new ValidationError("Tracked entity has no quantity to restore");+ }++ // The original scrap movement: explicit id from the payload, else+ // the entity's newest negative Scrap row.+ let scrapMovement = unscrapOfItemLedgerId+ ? await trx+ .selectFrom("itemLedger")+ .select(["id", "storageUnitId", "locationId", "scrapReasonId"])+ .where("id", "=", unscrapOfItemLedgerId)+ .where("companyId", "=", companyId)+ // Constrain a caller-supplied id to THIS entity's own negative+ // Scrap movements (same filters as the fallback below) — an+ // unrelated ledger id must not drive the restored bin/cost.+ .where("trackedEntityId", "=", trackedEntityId)+ .where("documentType", "=", "Scrap")+ .where("quantity", "<", 0)+ .executeTakeFirst()+ : undefined;+ if (!scrapMovement) {+ scrapMovement = await trx+ .selectFrom("itemLedger")+ .select(["id", "storageUnitId", "locationId", "scrapReasonId"])+ .where("trackedEntityId", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .where("documentType", "=", "Scrap")+ .where("quantity", "<", 0)+ .orderBy("createdAt", "desc")+ .executeTakeFirst();+ }++ // Inherit the reason from the original scrap movement so an unscrap+ // is never mis-classified — the operator no longer re-enters it. Fall+ // back to any payload reason, then null (untracked/legacy rows).+ const resolvedScrapReasonId =+ scrapMovement?.scrapReasonId ?? scrapReasonId ?? null;+ const accountingForTrackedUnscrap = accountingForUnscrap+ ? {+ ...accountingForUnscrap,+ extraDimensions: [+ ...(resolvedScrapReasonId+ ? [+ {+ entityType: "ScrapReason",+ valueId: resolvedScrapReasonId,+ },+ ]+ : []),+ { entityType: "Employee", valueId: userId },+ ],+ }+ : null;++ // Reverse at the ORIGINAL scrapped cost when the scrap movement's+ // cost rows are resolvable (costLedger.documentId = the scrap+ // itemLedger id — bookAdjustment's linkage); else current cost.+ let fixedUnitCost: number | undefined;+ if (scrapMovement) {+ const costRows = await trx+ .selectFrom("costLedger")+ .select(["quantity", "cost"])+ .where("documentId", "=", scrapMovement.id)+ .where("companyId", "=", companyId)+ .execute();+ const resolved = resolveUnscrapUnitCost(+ costRows.map((r) => ({+ quantity: Number(r.quantity),+ cost: Number(r.cost),+ }))+ );+ if (resolved != null) fixedUnitCost = resolved;+ }++ await trx+ .updateTable("trackedEntity")+ .set({ status: "Available" })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ const unscrapActivityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: unscrapActivityId,+ type: "Unscrap",+ sourceDocument: "Item",+ sourceDocumentId: itemId,+ attributes: {+ "Scrap Reason": resolvedScrapReasonId,+ Employee: userId,+ ...(comment?.trim() ? { Notes: comment.trim() } : {}),+ },+ companyId,+ createdBy: userId,+ })+ .execute();+ await trx+ .insertInto("trackedActivityOutput")+ .values({+ trackedActivityId: unscrapActivityId,+ trackedEntityId,+ quantity: entityQuantity,+ companyId,+ createdBy: userId,+ })+ .execute();++ const booked = await bookAdjustment(trx, {+ ledger: {+ ...unscrapLedgerBase,+ scrapReasonId: resolvedScrapReasonId,+ // A Scrapped tracked-entity row carries no location — restore to+ // the bin/location the scrap movement removed it from.+ locationId:+ scrapMovement?.locationId ?? unscrapLedgerBase.locationId,+ storageUnitId:+ scrapMovement?.storageUnitId ?? storageUnitId ?? null,+ correctionOfItemLedgerId: scrapMovement?.id ?? null,+ quantity: entityQuantity,+ },+ item,+ itemCost,+ accounting: accountingForTrackedUnscrap,+ fixedUnitCost,+ });+ resultLedgerId = booked.itemLedgerId;+ return;+ }++ // Untracked unscrap: positive movement at current cost (no original+ // movement linkage to reverse against — v1).+ if (quantity <= 0) {+ throw new ValidationError(+ "Unscrap quantity must be greater than zero"+ );+ }+ // Unscrap makes locationId optional in the validator (the tracked path+ // recovers it from the scrap movement). The untracked path has no such+ // recovery, so require it — a null-location ledger row is invisible to+ // location-scoped inventory queries.+ if (!locationId) {+ throw new ValidationError(+ "Location is required to unscrap untracked stock"+ );+ }+ const booked = await bookAdjustment(trx, {+ ledger: {+ ...unscrapLedgerBase,+ trackedEntityId: null,+ quantity,+ },+ item,+ itemCost,+ accounting: accountingForUnscrap,+ });+ resultLedgerId = booked.itemLedgerId;+ return;+ }+if (isStorageUnitTransfer) {if (readableId !== undefined && readableId !== null) {await trxdiff --git a/packages/database/supabase/functions/post-inventory-adjustment/resolve-unscrap-cost.test.ts b/packages/database/supabase/functions/post-inventory-adjustment/resolve-unscrap-cost.test.tsnew file mode 100644index 0000000000..3e773e4c32--- /dev/null+++ b/packages/database/supabase/functions/post-inventory-adjustment/resolve-unscrap-cost.test.ts@@ -0,0 +1,24 @@+import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";+import { resolveUnscrapUnitCost } from "./resolve-unscrap-cost.ts";++Deno.test("single negative scrap row resolves its unit cost", () => {+ assertEquals(resolveUnscrapUnitCost([{ quantity: -10, cost: -70 }]), 7);+});++Deno.test("multiple rows resolve the blended unit cost", () => {+ assertEquals(+ resolveUnscrapUnitCost([+ { quantity: -10, cost: -70 },+ { quantity: -5, cost: -50 },+ ]),+ 8+ );+});++Deno.test("empty rows return null (caller falls back to current cost)", () => {+ assertEquals(resolveUnscrapUnitCost([]), null);+});++Deno.test("zero-quantity rows return null instead of dividing by zero", () => {+ assertEquals(resolveUnscrapUnitCost([{ quantity: 0, cost: 100 }]), null);+});diff --git a/packages/database/supabase/functions/post-inventory-adjustment/resolve-unscrap-cost.ts b/packages/database/supabase/functions/post-inventory-adjustment/resolve-unscrap-cost.tsnew file mode 100644index 0000000000..5dcf7200a7--- /dev/null+++ b/packages/database/supabase/functions/post-inventory-adjustment/resolve-unscrap-cost.ts@@ -0,0 +1,20 @@+// Pure cost resolver for Unscrap: given the ORIGINAL scrap movement's+// costLedger rows (linked via costLedger.documentId = the scrap itemLedger id),+// return the unit cost the restored layer must book at so a scrap→unscrap+// round trip nets zero P&L (Oracle Return-from-Scrap precedent). Returns null+// when the rows can't yield a cost — the caller then falls back to current+// cost. No imports so `deno test` type-checks clean.++export function resolveUnscrapUnitCost(+ rows: Array<{ quantity: number; cost: number }>+): number | null {+ if (rows.length === 0) return null;+ let totalQuantity = 0;+ let totalCost = 0;+ for (const row of rows) {+ totalQuantity += Math.abs(Number(row.quantity) || 0);+ totalCost += Math.abs(Number(row.cost) || 0);+ }+ if (totalQuantity === 0) return null;+ return totalCost / totalQuantity;+}diff --git a/packages/database/supabase/functions/shared/batch-split.ts b/packages/database/supabase/functions/shared/batch-split.tsindex 59b785964d..c35cfd6f1b 100644--- a/packages/database/supabase/functions/shared/batch-split.ts+++ b/packages/database/supabase/functions/shared/batch-split.ts@@ -39,7 +39,7 @@ export type BatchSplitInput = {userId: string;/** yyyy-MM-dd */postingDate: string;- childStatus: "Available" | "Consumed";+ childStatus: "Available" | "Consumed" | "Scrapped";extraChildAttributes?: Record<string, unknown>;};@@ -73,7 +73,7 @@ export function buildBatchSplitRecords(input: BatchSplitInput): {sourceDocumentId: string | null;sourceDocumentReadableId: string | null;quantity: number;- status: "Available" | "Consumed";+ status: "Available" | "Consumed" | "Scrapped";attributes: Record<string, unknown>;itemId: string | null;expirationDate: string | null;diff --git a/packages/database/supabase/functions/shared/post-adjustment.ts b/packages/database/supabase/functions/shared/post-adjustment.tsindex 25ee28b6d1..9e971017fd 100644--- a/packages/database/supabase/functions/shared/post-adjustment.ts+++ b/packages/database/supabase/functions/shared/post-adjustment.ts@@ -40,6 +40,10 @@ export interface BookAdjustmentArgs {documentId?: string | null;correctionOfItemLedgerId?: string | null;comment?: string | null;+ // Reason for scrap/unscrap movements (documentType 'Scrap'); NULL for+ // every other adjustment. MES production scrap keeps its reason on+ // productionQuantity.scrapReasonId.+ scrapReasonId?: string | null;companyId: string;createdBy: string;};@@ -74,6 +78,11 @@ export interface BookAdjustmentArgs {// (Item / ItemPostingGroup / Location are consulted) — journal lines get// journalLineDimension tags for whichever are configureddimensions?: Record<string, string>;+ // Additional journalLineDimension tags beyond Item/ItemPostingGroup/+ // Location (ScrapReason / WorkCenter / Employee for scrap postings).+ // entityType must be a dimensionEntityType value present in `dimensions`;+ // valueId is the referenced entity id (polymorphic, no FK).+ extraDimensions?: Array<{ entityType: string; valueId: string }>;// When set, lines append to this shared journal instead of the core// creating one journal per movement — inventory counts post ONE journal// per count with a line pair per variance. Lazy (called only when a@@ -84,6 +93,11 @@ export interface BookAdjustmentArgs {// storage-unit-transfer legs move stock between bins without changing its// value: ledger row only — no cost layers, no journalskipValuation?: boolean;+ // Book an INCREASE's new cost layer at this unit cost instead of+ // computeCurrentUnitCost — Unscrap reverses at the original scrapped cost+ // (Oracle Return-from-Scrap precedent). Ignored for decreases, which always+ // relieve via calculateCOGS.+ fixedUnitCost?: number;}// itemLedgerDocumentType values that also exist on journalLineDocumentType.@@ -102,6 +116,7 @@ const JOURNAL_LINE_SAFE_DOCUMENT_TYPES: ReadonlySet<string> = new Set(["Inventory Count","Non-Conformance","Inbound Inspection",+ "Scrap",]);export interface BookAdjustmentResult {@@ -177,6 +192,7 @@ export async function bookAdjustment(trackedEntityId: ledger.trackedEntityId,quantity: ledger.quantity,comment: ledger.comment ?? null,+ scrapReasonId: ledger.scrapReasonId ?? null,companyId,createdBy: ledger.createdBy,})@@ -221,6 +237,27 @@ export async function bookAdjustment(companyId,}).execute();+ } else if (args.fixedUnitCost != null) {+ // Increase at a caller-fixed unit cost: Unscrap restores stock at the+ // ORIGINAL scrapped cost so a scrap→unscrap round trip nets zero P&L.+ cost = absQuantity * args.fixedUnitCost;++ await trx+ .insertInto("costLedger")+ .values({+ itemLedgerType: ledger.entryType,+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: ledger.documentType ?? null,+ documentId,+ itemId: ledger.itemId,+ quantity: absQuantity,+ cost,+ remainingQuantity: absQuantity,+ postingDate: ledger.postingDate,+ companyId,+ })+ .execute();} else {// Increase: create a layer at the item's current carrying cost. Same// open-layer filters as calculateCOGS so both sides of the math agree.@@ -359,6 +396,9 @@ export async function bookAdjustment(["Item", ledger.itemId],["ItemPostingGroup", item.itemPostingGroupId],["Location", ledger.locationId],+ ...(accounting.extraDimensions ?? []).map(+ (d) => [d.entityType, d.valueId] as [string, string]+ ),];const journalLineDimensionInserts = journalLines.flatMap((line) =>dimensionValuesdiff --git a/packages/database/supabase/migrations/20260807090400_scrap-unscrap-enums.sql b/packages/database/supabase/migrations/20260807090400_scrap-unscrap-enums.sqlnew file mode 100644index 0000000000..6f71aa8c60--- /dev/null+++ b/packages/database/supabase/migrations/20260807090400_scrap-unscrap-enums.sql@@ -0,0 +1,21 @@+-- Terminal scrap status for tracked entities (Epicor SCRAPPED / SAP ME precedent).+-- Recoverable via ERP Unscrap, unlike 'Consumed'.+ALTER TYPE "trackedEntityStatus" ADD VALUE IF NOT EXISTS 'Scrapped';++-- Scrap movement identity on the two document-type enums. These are DIFFERENT+-- enums with overlapping value sets — both need the value.+ALTER TYPE "itemLedgerDocumentType" ADD VALUE IF NOT EXISTS 'Scrap';+ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Scrap';++-- Scrap reason as a journal dimension (single scrapAccount + dimension slicing;+-- valueId on journalLineDimension is polymorphic → scrapReason.id).+ALTER TYPE "dimensionEntityType" ADD VALUE IF NOT EXISTS 'ScrapReason';++-- Reason lands on stock scrap/unscrap movements (MES production scrap keeps its+-- reason on productionQuantity.scrapReasonId).+ALTER TABLE "itemLedger" ADD COLUMN IF NOT EXISTS "scrapReasonId" TEXT;+ALTER TABLE "itemLedger" DROP CONSTRAINT IF EXISTS "itemLedger_scrapReasonId_fkey";+ALTER TABLE "itemLedger" ADD CONSTRAINT "itemLedger_scrapReasonId_fkey"+ FOREIGN KEY ("scrapReasonId") REFERENCES "scrapReason"("id") ON DELETE SET NULL;+CREATE INDEX IF NOT EXISTS "itemLedger_scrapReasonId_idx"+ ON "itemLedger"("scrapReasonId") WHERE "scrapReasonId" IS NOT NULL;diff --git a/packages/database/supabase/migrations/20260807090629_scrap-unscrap-functions.sql b/packages/database/supabase/migrations/20260807090629_scrap-unscrap-functions.sqlnew file mode 100644index 0000000000..b3794352a5--- /dev/null+++ b/packages/database/supabase/migrations/20260807090629_scrap-unscrap-functions.sql@@ -0,0 +1,137 @@+-- Auto-Done predicate: scrap no longer counts toward targetQuantity.+--+-- targetQuantity is the GOOD quantity to produce before scrap+-- (20260119120000); operationQuantity carries the planned-scrap allowance.+-- The old predicate (complete + reworked + scrapped >= target) let scrapped+-- units consume good-target capacity, auto-Done-ing operations short — even+-- within planned scrap. Spec: .ai/specs/2026-08-06-scrap-unscrap-flow.md+-- (Brad, 2026-08-07).+--+-- Forked verbatim from the newest definition+-- (20260706181125_fix-auto-complete-null-user.sql); the ONLY change is the+-- auto-Done predicate line (quantityScrapped removed from the sum).+--+-- NOTE (verified 2026-08-07): get_inventory_quantities /+-- get_available_tracked_entities / get_picking_list_tracked_available need NO+-- 'Scrapped' handling — scrap paths write negative ledger movements and+-- itemLedger.trackedEntityStatus is status-synced (20260420112047), so+-- Scrapped stock nets to zero; the availability RPCs already filter+-- status = 'Available'.++CREATE OR REPLACE FUNCTION sync_update_job_operation_quantities(+ 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_operation_id TEXT;+ v_job_id TEXT;+ v_user_id TEXT;+ v_is_last_top_level_operation BOOLEAN := FALSE;+BEGIN+ v_user_id := COALESCE(+ p_new->>'updatedBy', p_new->>'createdBy',+ p_old->>'updatedBy', p_old->>'createdBy'+ );++ IF p_operation = 'INSERT' THEN+ v_job_operation_id := p_new->>'jobOperationId';++ UPDATE "jobOperation"+ SET+ "quantityComplete" = "quantityComplete" ++ CASE WHEN (p_new->>'type') = 'Production' THEN (p_new->>'quantity')::numeric ELSE 0 END,+ "quantityReworked" = "quantityReworked" ++ CASE WHEN (p_new->>'type') = 'Rework' THEN (p_new->>'quantity')::numeric ELSE 0 END,+ "quantityScrapped" = "quantityScrapped" ++ CASE WHEN (p_new->>'type') = 'Scrap' THEN (p_new->>'quantity')::numeric ELSE 0 END+ WHERE id = v_job_operation_id;++ ELSIF p_operation = 'UPDATE' THEN+ v_job_operation_id := p_new->>'jobOperationId';++ UPDATE "jobOperation"+ SET+ "quantityComplete" = "quantityComplete"+ - CASE WHEN (p_old->>'type') = 'Production' THEN (p_old->>'quantity')::numeric ELSE 0 END+ + CASE WHEN (p_new->>'type') = 'Production' THEN (p_new->>'quantity')::numeric ELSE 0 END,+ "quantityReworked" = "quantityReworked"+ - CASE WHEN (p_old->>'type') = 'Rework' THEN (p_old->>'quantity')::numeric ELSE 0 END+ + CASE WHEN (p_new->>'type') = 'Rework' THEN (p_new->>'quantity')::numeric ELSE 0 END,+ "quantityScrapped" = "quantityScrapped"+ - CASE WHEN (p_old->>'type') = 'Scrap' THEN (p_old->>'quantity')::numeric ELSE 0 END+ + CASE WHEN (p_new->>'type') = 'Scrap' THEN (p_new->>'quantity')::numeric ELSE 0 END+ WHERE id = v_job_operation_id;++ ELSIF p_operation = 'DELETE' THEN+ v_job_operation_id := p_old->>'jobOperationId';++ UPDATE "jobOperation"+ SET+ "quantityComplete" = "quantityComplete" -+ CASE WHEN (p_old->>'type') = 'Production' THEN (p_old->>'quantity')::numeric ELSE 0 END,+ "quantityReworked" = "quantityReworked" -+ CASE WHEN (p_old->>'type') = 'Rework' THEN (p_old->>'quantity')::numeric ELSE 0 END,+ "quantityScrapped" = "quantityScrapped" -+ CASE WHEN (p_old->>'type') = 'Scrap' THEN (p_old->>'quantity')::numeric ELSE 0 END+ WHERE id = v_job_operation_id;+ END IF;++ UPDATE "jobOperation"+ SET "status" = 'Done',+ "updatedBy" = COALESCE(v_user_id, "updatedBy", "createdBy"),+ "updatedAt" = NOW()+ WHERE id = v_job_operation_id+ AND "status" NOT IN ('Done', 'Canceled')+ AND "targetQuantity" > 0+ AND ("quantityComplete" + "quantityReworked") >= "targetQuantity";++ SELECT jo."jobId" INTO v_job_id+ FROM "jobOperation" jo+ WHERE jo.id = v_job_operation_id;++ SELECT EXISTS (+ SELECT 1+ FROM "jobOperation" jo+ INNER JOIN "jobMakeMethod" jmm ON jmm.id = jo."jobMakeMethodId"+ WHERE jo.id = v_job_operation_id+ AND 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" = jo.id+ AND child_jmm."parentMaterialId" IS NULL+ )+ ) INTO v_is_last_top_level_operation;++ IF v_job_id IS NOT NULL AND v_is_last_top_level_operation THEN+ UPDATE "job"+ SET "quantityComplete" = (+ 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" = v_job_id+ 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+ )+ )+ WHERE id = v_job_id+ AND status NOT IN ('Completed', 'Cancelled');+ END IF;+END;+$$;+diff --git a/packages/database/supabase/migrations/20260808114732_backfill-scrap-reason-dimension.sql b/packages/database/supabase/migrations/20260808114732_backfill-scrap-reason-dimension.sqlnew file mode 100644index 0000000000..2e87395800--- /dev/null+++ b/packages/database/supabase/migrations/20260808114732_backfill-scrap-reason-dimension.sql@@ -0,0 +1,16 @@+-- Backfill the default "Scrap Reason" entity-backed dimension for every existing+-- company group. Dimensions are user-configured per company group, but the scrap+-- flow expects a ScrapReason dimension to exist so scrap postings get tagged (and+-- so the reason is selectable on journal lines). New-company seeding covers this+-- via functions/lib/seed.data.ts; this migration covers pre-existing groups.+--+-- Idempotent: the partial unique index on (name, companyGroupId) WHERE active = true+-- plus ON CONFLICT DO NOTHING guarantees no duplicate, so this is safe to (re)run.+-- Name mirrors seed.data.ts exactly ("Scrap Reason"). Inserted rows default active = true.+--+-- 'ScrapReason' was added to the "dimensionEntityType" enum in a prior migration+-- (20260807090400_scrap-unscrap-enums.sql), so it is safe to reference here.+INSERT INTO "dimension" ("name", "entityType", "companyGroupId", "createdBy")+SELECT 'Scrap Reason', 'ScrapReason'::"dimensionEntityType", cg."id", 'system'+FROM "companyGroup" cg+ON CONFLICT ("name", "companyGroupId") WHERE "active" = true DO NOTHING;diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 83e416e52f..61b2074813 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -10776,6 +10776,9 @@ msgstr "Ressourcen"msgid "Restore from Trash"msgstr "Aus dem Papierkorb wiederherstellen"+msgid "Restore this entity to available stock at the bin and cost it was scrapped from."+msgstr "Diese Entität zum verfügbaren Bestand in dem Behälter und den Kosten zurückholen, von denen sie verschrottet wurde."+msgid "Restore tracked entities to available"msgstr "Nachverfolgter Entitäten als verfügbar wiederherstellen"@@ -11246,6 +11249,9 @@ msgstr "Verschrottungsgründe"msgid "Scrap Reasons"msgstr "Verschrottungsgründe"+msgid "Scrapped"+msgstr "Verschrottet"+msgid "Search"msgstr "Suchen"@@ -13976,6 +13982,12 @@ msgstr "Nicht eingegangene Bestellungen"msgid "Unsaved changes"msgstr "Nicht gespeicherte Änderungen"+msgid "Unscrap"+msgstr "Entschrotten"++msgid "Unscrap {label}"+msgstr "Entschrotten {label}"+msgid "Unshipped orders"msgstr "Nicht versendete Bestellungen"diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.poindex 968f0dd3bb..3c34de84c3 100644--- a/packages/locale/locales/de/mes.po+++ b/packages/locale/locales/de/mes.po@@ -153,6 +153,9 @@ msgstr "Authentifizierungsfehler"msgid "available"msgstr "verfügbar"+msgid "Available"+msgstr "Verfügbar"+msgid "Batch"msgstr "Charge"@@ -268,6 +271,9 @@ msgstr "Konsole"msgid "Console Mode"msgstr "Konsolenmodus"+msgid "Consumed"+msgstr "Verbraucht"+msgid "Consumed expired"msgstr "Verbrauchte abgelaufen"@@ -678,6 +684,9 @@ msgstr "Instandhaltung abgeschlossen"msgid "Maintenance overdue"msgstr "Wartung überfällig"+msgid "Make a replacement"+msgstr "Ersatzteil erstellen"+msgid "Manually add items to inventory"msgstr "Artikel manuell zum Bestand hinzufügen"@@ -868,6 +877,9 @@ msgstr "Nichts läuft"msgid "Nothing scheduled at this work center"msgstr "Nichts geplant in diesem Arbeitszentrum"+msgid "Nothing to scrap"+msgstr "Nichts zum Verschrotten"+msgid "OEE Impact"msgstr "OEE-Auswirkung"@@ -1053,6 +1065,9 @@ msgstr "Bestand entfernen"msgid "Remove part"msgstr "Teil entfernen"+msgid "Reopen the subassembly and create a replacement unit"+msgstr "Unterbaugruppe erneut öffnen und Ersatzeinheit erstellen"+msgid "Result"msgstr "Ergebnis"@@ -1101,6 +1116,12 @@ msgstr "Zeitplan"msgid "Scrap"msgstr "Ausschuss"+msgid "Scrap {readableId}"+msgstr "{readableId} verschrotten"++msgid "Scrap material"+msgstr "Material verschrotten"+msgid "Scrap quantity"msgstr "Verschrottungsmenge"@@ -1110,6 +1131,12 @@ msgstr "Ausschussgrund"msgid "Scrapped"msgstr "Ausschuss"+msgid "Scrapping serial {trackedEntityReadableId}"+msgstr "Seriennummer {trackedEntityReadableId} wird verschrottet"++msgid "Scrapping the selected serial"+msgstr "Ausgewählte Seriennummer wird verschrottet"+msgid "Search"msgstr "Suchen"@@ -1294,6 +1321,9 @@ msgstr "Das Los wird als Bestanden markiert und {remaining} verbleibende Einheitmsgid "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."+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."+msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."msgstr "Es gibt serien- oder chargenverfolgte Materialien in der Stückliste, die noch nicht vollständig ausgegeben wurden. Ein Abschluss ohne Ausgabe kann zu fehlerhaften Rückverfolgbarkeitsdaten führen."@@ -1303,6 +1333,15 @@ msgstr "Diese Artikel haben noch Material zum Picken. Ein Abschluss jetzt markiemsgid "This lot is expired and can't be picked."msgstr "Dieses Los ist abgelaufen und kann nicht entnommen werden."+msgid "This part was made to order. Scrapping it can reopen its routing to make a replacement."+msgstr "Dieses Teil wurde auf Bestellung gefertigt. Durch das Verschrotten kann seine Arbeitsfolge erneut geöffnet werden, um ein Ersatzteil zu erstellen."++msgid "This part will be scrapped from stock. Its requirement stays open so you can issue a replacement."+msgstr "Dieses Teil wird aus dem Lager verschrottet. Sein Bedarf bleibt offen, damit Sie ein Ersatzteil ausgeben können."++msgid "This unit will be permanently scrapped and a replacement serial number will be created."+msgstr "Diese Einheit wird endgültig verschrottet und es wird eine neue Seriennummer erstellt."+msgid "Thumbnail"msgstr "Vorschaubild"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 900151fd0e..d849f6a48b 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -10776,6 +10776,9 @@ msgstr "Resources"msgid "Restore from Trash"msgstr "Restore from Trash"+msgid "Restore this entity to available stock at the bin and cost it was scrapped from."+msgstr "Restore this entity to available stock at the bin and cost it was scrapped from."+msgid "Restore tracked entities to available"msgstr "Restore tracked entities to available"@@ -11246,6 +11249,9 @@ msgstr "scrap reasons"msgid "Scrap Reasons"msgstr "Scrap Reasons"+msgid "Scrapped"+msgstr "Scrapped"+msgid "Search"msgstr "Search"@@ -13976,6 +13982,12 @@ msgstr "Unreceived POs"msgid "Unsaved changes"msgstr "Unsaved changes"+msgid "Unscrap"+msgstr "Unscrap"++msgid "Unscrap {label}"+msgstr "Unscrap {label}"+msgid "Unshipped orders"msgstr "Unshipped orders"diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.poindex 7fcf74e490..fda646b2fb 100644--- a/packages/locale/locales/en/mes.po+++ b/packages/locale/locales/en/mes.po@@ -153,6 +153,9 @@ msgstr "Authentication Error"msgid "available"msgstr "available"+msgid "Available"+msgstr "Available"+msgid "Batch"msgstr "Batch"@@ -268,6 +271,9 @@ msgstr "Console"msgid "Console Mode"msgstr "Console Mode"+msgid "Consumed"+msgstr "Consumed"+msgid "Consumed expired"msgstr "Consumed expired"@@ -678,6 +684,9 @@ msgstr "Maintenance Completed"msgid "Maintenance overdue"msgstr "Maintenance overdue"+msgid "Make a replacement"+msgstr "Make a replacement"+msgid "Manually add items to inventory"msgstr "Manually add items to inventory"@@ -868,6 +877,9 @@ msgstr "Nothing running"msgid "Nothing scheduled at this work center"msgstr "Nothing scheduled at this work center"+msgid "Nothing to scrap"+msgstr "Nothing to scrap"+msgid "OEE Impact"msgstr "OEE Impact"@@ -1053,6 +1065,9 @@ msgstr "Remove Inventory"msgid "Remove part"msgstr "Remove part"+msgid "Reopen the subassembly and create a replacement unit"+msgstr "Reopen the subassembly and create a replacement unit"+msgid "Result"msgstr "Result"@@ -1101,6 +1116,12 @@ msgstr "Schedule"msgid "Scrap"msgstr "Scrap"+msgid "Scrap {readableId}"+msgstr "Scrap {readableId}"++msgid "Scrap material"+msgstr "Scrap material"+msgid "Scrap quantity"msgstr "Scrap quantity"@@ -1110,6 +1131,12 @@ msgstr "Scrap Reason"msgid "Scrapped"msgstr "Scrapped"+msgid "Scrapping serial {trackedEntityReadableId}"+msgstr "Scrapping serial {trackedEntityReadableId}"++msgid "Scrapping the selected serial"+msgstr "Scrapping the selected serial"+msgid "Search"msgstr "Search"@@ -1294,6 +1321,9 @@ msgstr "The lot will be marked Passed and {remaining} remaining unit(s) will bemsgid "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."+msgid "There are no available or consumed tracked parts for this material."+msgstr "There are no available or consumed tracked parts for this material."+msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."msgstr "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."@@ -1303,6 +1333,15 @@ msgstr "These items still have material to pick. Finishing now marks the list Pamsgid "This lot is expired and can't be picked."msgstr "This lot is expired and can't be picked."+msgid "This part was made to order. Scrapping it can reopen its routing to make a replacement."+msgstr "This part was made to order. Scrapping it can reopen its routing to make a replacement."++msgid "This part will be scrapped from stock. Its requirement stays open so you can issue a replacement."+msgstr "This part will be scrapped from stock. Its requirement stays open so you can issue a replacement."++msgid "This unit will be permanently scrapped and a replacement serial number will be created."+msgstr "This unit will be permanently scrapped and a replacement serial number will be created."+msgid "Thumbnail"msgstr "Thumbnail"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex ff53ee36e2..9603153abd 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -10776,6 +10776,9 @@ msgstr "Recursos"msgid "Restore from Trash"msgstr "Restaurar desde la papelera"+msgid "Restore this entity to available stock at the bin and cost it was scrapped from."+msgstr "Restaurar esta entidad al inventario disponible en la ubicación y el costo desde el que fue descartada."+msgid "Restore tracked entities to available"msgstr "Restaurar entidades rastreadas a disponibles"@@ -11246,6 +11249,9 @@ msgstr "Motivos de desecho"msgid "Scrap Reasons"msgstr "Razones de Rechazo"+msgid "Scrapped"+msgstr "Descartada"+msgid "Search"msgstr "Buscar"@@ -13976,6 +13982,12 @@ msgstr "POs no recibidas"msgid "Unsaved changes"msgstr "Cambios no guardados"+msgid "Unscrap"+msgstr "Restaurar"++msgid "Unscrap {label}"+msgstr "Restaurar {label}"+msgid "Unshipped orders"msgstr "Pedidos no enviados"diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.poindex 454d1235c8..38f4217ec7 100644--- a/packages/locale/locales/es/mes.po+++ b/packages/locale/locales/es/mes.po@@ -153,6 +153,9 @@ msgstr "Error de autenticación"msgid "available"msgstr "disponible"+msgid "Available"+msgstr "Disponible"+msgid "Batch"msgstr "Lote"@@ -268,6 +271,9 @@ msgstr "Consola"msgid "Console Mode"msgstr "Modo consola"+msgid "Consumed"+msgstr "Consumido"+msgid "Consumed expired"msgstr "Consumido vencido"@@ -678,6 +684,9 @@ msgstr "Mantenimiento completado"msgid "Maintenance overdue"msgstr "Mantenimiento vencido"+msgid "Make a replacement"+msgstr "Hacer un reemplazo"+msgid "Manually add items to inventory"msgstr "Agregar artículos al inventario manualmente"@@ -868,6 +877,9 @@ msgstr "Nada en ejecución"msgid "Nothing scheduled at this work center"msgstr "Nada programado en este centro de trabajo"+msgid "Nothing to scrap"+msgstr "Nada que descartar"+msgid "OEE Impact"msgstr "Impacto OEE"@@ -1053,6 +1065,9 @@ msgstr "Eliminar inventario"msgid "Remove part"msgstr "Eliminar pieza"+msgid "Reopen the subassembly and create a replacement unit"+msgstr "Reabrir el subconjunto y crear una unidad de reemplazo"+msgid "Result"msgstr "Resultado"@@ -1101,6 +1116,12 @@ msgstr "Programación"msgid "Scrap"msgstr "Descartar"+msgid "Scrap {readableId}"+msgstr "Descartar {readableId}"++msgid "Scrap material"+msgstr "Descartar material"+msgid "Scrap quantity"msgstr "Cantidad de desecho"@@ -1110,6 +1131,12 @@ msgstr "Motivo de desperdicio"msgid "Scrapped"msgstr "Descartado"+msgid "Scrapping serial {trackedEntityReadableId}"+msgstr "Descartando serie {trackedEntityReadableId}"++msgid "Scrapping the selected serial"+msgstr "Descartando la serie seleccionada"+msgid "Search"msgstr "Buscar"@@ -1294,6 +1321,9 @@ msgstr "El lote se marcará como Aprobado y {remaining} unidad(es) restante(s) smsgid "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."+msgid "There are no available or consumed tracked parts for this material."+msgstr "No hay piezas rastreadas disponibles o consumidas para este material."+msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."msgstr "Hay materiales con seguimiento de serie o lote en la lista de materiales que no se han emitido completamente. Completar sin emitir puede generar registros de trazabilidad incorrectos."@@ -1303,6 +1333,15 @@ msgstr "Estos elementos aún tienen material para recoger. Finalizar ahora marcamsgid "This lot is expired and can't be picked."msgstr "Este lote ha expirado y no se puede seleccionar."+msgid "This part was made to order. Scrapping it can reopen its routing to make a replacement."+msgstr "Esta pieza fue hecha por encargo. Descartarla puede reabrir su ruta para hacer un reemplazo."++msgid "This part will be scrapped from stock. Its requirement stays open so you can issue a replacement."+msgstr "Esta pieza será descartada del inventario. Su requisito permanece abierto para que puedas emitir un reemplazo."++msgid "This unit will be permanently scrapped and a replacement serial number will be created."+msgstr "Esta unidad será descartada permanentemente y se creará un nuevo número de serie de reemplazo."+msgid "Thumbnail"msgstr "Miniatura"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex b4c85f2b56..9d2805ecd8 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -10776,6 +10776,9 @@ msgstr "Ressources"msgid "Restore from Trash"msgstr "Restaurer à partir de la corbeille"+msgid "Restore this entity to available stock at the bin and cost it was scrapped from."+msgstr "Restaurer cette entité au stock disponible dans le bac et au coût d'où elle a été mise au rebut."+msgid "Restore tracked entities to available"msgstr "Restaurer les entités suivies en disponibles"@@ -11246,6 +11249,9 @@ msgstr "Motifs de déchet"msgid "Scrap Reasons"msgstr "Raisons de rebut"+msgid "Scrapped"+msgstr "Mise au rebut"+msgid "Search"msgstr "Rechercher"@@ -13976,6 +13982,12 @@ msgstr "Bons de commande non reçus"msgid "Unsaved changes"msgstr "Modifications non enregistrées"+msgid "Unscrap"+msgstr "Annuler la mise au rebut"++msgid "Unscrap {label}"+msgstr "Annuler la mise au rebut {label}"+msgid "Unshipped orders"msgstr "Commandes non expédiées"diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.poindex ad461bc3d1..0fe8edcce5 100644--- a/packages/locale/locales/fr/mes.po+++ b/packages/locale/locales/fr/mes.po@@ -153,6 +153,9 @@ msgstr "Erreur d'authentification"msgid "available"msgstr "disponible"+msgid "Available"+msgstr "Disponible"+msgid "Batch"msgstr "Lot"@@ -268,6 +271,9 @@ msgstr "Console"msgid "Console Mode"msgstr "Mode console"+msgid "Consumed"+msgstr "Consommé"+msgid "Consumed expired"msgstr "Consommé expiré"@@ -678,6 +684,9 @@ msgstr "Maintenance terminée"msgid "Maintenance overdue"msgstr "Maintenance en retard"+msgid "Make a replacement"+msgstr "Effectuer un remplacement"+msgid "Manually add items to inventory"msgstr "Ajouter manuellement des articles au stock"@@ -868,6 +877,9 @@ msgstr "Rien en cours"msgid "Nothing scheduled at this work center"msgstr "Rien de planifié à ce centre de travail"+msgid "Nothing to scrap"+msgstr "Rien à rebuter"+msgid "OEE Impact"msgstr "Impact TRS"@@ -1053,6 +1065,9 @@ msgstr "Retirer du stock"msgid "Remove part"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 "Result"msgstr "Résultat"@@ -1101,6 +1116,12 @@ msgstr "Planification"msgid "Scrap"msgstr "Rebut"+msgid "Scrap {readableId}"+msgstr "Rebut {readableId}"++msgid "Scrap material"+msgstr "Mise au rebut du matériel"+msgid "Scrap quantity"msgstr "Quantité de rebut"@@ -1110,6 +1131,12 @@ msgstr "Motif de rebut"msgid "Scrapped"msgstr "Rebuté"+msgid "Scrapping serial {trackedEntityReadableId}"+msgstr "Mise au rebut du numéro de série {trackedEntityReadableId}"++msgid "Scrapping the selected serial"+msgstr "Mise au rebut du numéro de série sélectionné"+msgid "Search"msgstr "Rechercher"@@ -1294,6 +1321,9 @@ msgstr "Le lot sera marqué comme Réussi et {remaining} unité(s) restante(s) smsgid "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é."+msgid "There are no available or consumed tracked parts for this material."+msgstr "Il n'y a aucun article suivi disponible ou consommé pour ce matériel."+msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."msgstr "Il existe des matériaux suivis par numéro de série ou par lot dans la nomenclature qui n'ont pas été entièrement distribués. Terminer sans distribuer peut entraîner des enregistrements de traçabilité incorrects."@@ -1303,6 +1333,15 @@ msgstr "Ces articles ont encore du matériel à prélever. L'arrêt maintenant mmsgid "This lot is expired and can't be picked."msgstr "Ce lot est expiré et ne peut pas être prélevé."+msgid "This part was made to order. Scrapping it can reopen its routing to make a replacement."+msgstr "Cette pièce a été fabriquée sur commande. Sa mise au rebut peut rouvrir son itinéraire pour créer un remplacement."++msgid "This part will be scrapped from stock. Its requirement stays open so you can issue a replacement."+msgstr "Cette pièce sera mise au rebut du stock. Son besoin reste ouvert pour que vous puissiez émettre un remplacement."++msgid "This unit will be permanently scrapped and a replacement serial number will be created."+msgstr "Cette unité sera définitivement mise au rebut et un nouveau numéro de série de remplacement sera créé."+msgid "Thumbnail"msgstr "Miniature"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 4726ede82d..9e83398e56 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -10776,6 +10776,9 @@ msgstr "संसाधन"msgid "Restore from Trash"msgstr "ट्रैश से पुनः स्थापित करें"+msgid "Restore this entity to available stock at the bin and cost it was scrapped from."+msgstr "इस इकाई को उसी बिन और लागत पर उपलब्ध स्टॉक में पुनः स्थापित करें जहां से इसे स्क्रैप किया गया था।"+msgid "Restore tracked entities to available"msgstr "ट्रैक किए गए इकाइयों को उपलब्ध में पुनः स्थापित करें"@@ -11246,6 +11249,9 @@ msgstr "स्क्रैप कारण"msgid "Scrap Reasons"msgstr "स्क्रैप कारण"+msgid "Scrapped"+msgstr "स्क्रैप किया गया"+msgid "Search"msgstr "खोज"@@ -13976,6 +13982,12 @@ msgstr "अप्राप्त POs"msgid "Unsaved changes"msgstr "असहेजे परिवर्तन"+msgid "Unscrap"+msgstr "अनस्क्रैप करें"++msgid "Unscrap {label}"+msgstr "अनस्क्रैप करें {label}"+msgid "Unshipped orders"msgstr "अभी भेजे जाने वाले ऑर्डर"diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.poindex ff107f579b..a2cd4e970a 100644--- a/packages/locale/locales/hi/mes.po+++ b/packages/locale/locales/hi/mes.po@@ -153,6 +153,9 @@ msgstr "प्रमाणीकरण त्रुटि"msgid "available"msgstr "उपलब्ध"+msgid "Available"+msgstr "उपलब्ध"+msgid "Batch"msgstr "बैच"@@ -268,6 +271,9 @@ msgstr "कंसोल"msgid "Console Mode"msgstr "कंसोल मोड"+msgid "Consumed"+msgstr "खपत"+msgid "Consumed expired"msgstr "खपत की गई समाप्त"@@ -678,6 +684,9 @@ msgstr "रखरखाव पूर्ण"msgid "Maintenance overdue"msgstr "रखरखाव अतिदेय"+msgid "Make a replacement"+msgstr "एक प्रतिस्थापन बनाएं"+msgid "Manually add items to inventory"msgstr "इन्वेंटरी में आइटम मैन्युअली जोड़ें"@@ -868,6 +877,9 @@ msgstr "कुछ नहीं चल रहा"msgid "Nothing scheduled at this work center"msgstr "इस कार्य केंद्र पर कुछ भी शेड्यूल नहीं है"+msgid "Nothing to scrap"+msgstr "स्क्रैप करने के लिए कुछ नहीं"+msgid "OEE Impact"msgstr "OEE प्रभाव"@@ -1053,6 +1065,9 @@ msgstr "इन्वेंटरी हटाएं"msgid "Remove part"msgstr "भाग हटाएं"+msgid "Reopen the subassembly and create a replacement unit"+msgstr "सबअ्यासेम्बली को फिर से खोलें और एक प्रतिस्थापन इकाई बनाएं"+msgid "Result"msgstr "परिणाम"@@ -1101,6 +1116,12 @@ msgstr "शेड्यूल"msgid "Scrap"msgstr "स्क्रैप"+msgid "Scrap {readableId}"+msgstr "स्क्रैप {readableId}"++msgid "Scrap material"+msgstr "स्क्रैप सामग्री"+msgid "Scrap quantity"msgstr "स्क्रैप मात्रा"@@ -1110,6 +1131,12 @@ msgstr "स्क्रैप कारण"msgid "Scrapped"msgstr "स्क्रैप किया गया"+msgid "Scrapping serial {trackedEntityReadableId}"+msgstr "सीरीयल को स्क्रैप किया जा रहा है {trackedEntityReadableId}"++msgid "Scrapping the selected serial"+msgstr "चयनित सीरीयल को स्क्रैप किया जा रहा है"+msgid "Search"msgstr "खोजें"@@ -1294,6 +1321,9 @@ msgstr "लॉट को पास के रूप में चिह्नि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 नहीं बनाया जा सकता।"+msgid "There are no available or consumed tracked parts for this material."+msgstr "इस सामग्री के लिए कोई उपलब्ध या खपत ट्रैक की गई वस्तुएं नहीं हैं।"+msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."msgstr "बिल ऑफ मेटेरियल पर सीरियल या बैच ट्रैक किए गए मेटेरियल हैं जो पूरी तरह से जारी नहीं किए गए हैं। जारी किए बिना पूरा करने से गलत ट्रेसेबिलिटी रिकॉर्ड हो सकते हैं।"@@ -1303,6 +1333,15 @@ msgstr "इन आइटम के पास अभी भी चुननेmsgid "This lot is expired and can't be picked."msgstr "यह लॉट समाप्त हो गया है और इसे चुना नहीं जा सकता।"+msgid "This part was made to order. Scrapping it can reopen its routing to make a replacement."+msgstr "यह हिस्सा आदेश के अनुसार बनाया गया था। इसे स्क्रैप करने से इसका रूटिंग फिर से खुल सकता है प्रतिस्थापन बनाने के लिए।"++msgid "This part will be scrapped from stock. Its requirement stays open so you can issue a replacement."+msgstr "यह हिस्सा स्टॉक से स्क्रैप किया जाएगा। इसकी आवश्यकता खुली रहती है ताकि आप एक प्रतिस्थापन जारी कर सकें।"++msgid "This unit will be permanently scrapped and a replacement serial number will be created."+msgstr "यह इकाई स्थायी रूप से स्क्रैप की जाएगी और एक प्रतिस्थापन सीरीयल नंबर बनाया जाएगा।"+msgid "Thumbnail"msgstr "थंबनेल"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex f3e88c3b71..62fc90fc07 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -10776,6 +10776,9 @@ msgstr "Risorse"msgid "Restore from Trash"msgstr "Ripristina dal Cestino"+msgid "Restore this entity to available stock at the bin and cost it was scrapped from."+msgstr "Ripristina questa entità al magazzino disponibile nel bin e al costo da cui è stata scartata."+msgid "Restore tracked entities to available"msgstr "Ripristina le entità tracciate come disponibili"@@ -11246,6 +11249,9 @@ msgstr "Motivi dello scarto"msgid "Scrap Reasons"msgstr "Motivi di Scarto"+msgid "Scrapped"+msgstr "Scartato"+msgid "Search"msgstr "Cerca"@@ -13976,6 +13982,12 @@ msgstr "PO non ricevuti"msgid "Unsaved changes"msgstr "Modifiche non salvate"+msgid "Unscrap"+msgstr "Annulla scarto"++msgid "Unscrap {label}"+msgstr "Annulla scarto {label}"+msgid "Unshipped orders"msgstr "Ordini non spediti"diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.poindex f39bad978f..49a5e5ae83 100644--- a/packages/locale/locales/it/mes.po+++ b/packages/locale/locales/it/mes.po@@ -153,6 +153,9 @@ msgstr "Errore di Autenticazione"msgid "available"msgstr "disponibile"+msgid "Available"+msgstr "Disponibile"+msgid "Batch"msgstr "Lotto"@@ -268,6 +271,9 @@ msgstr "Console"msgid "Console Mode"msgstr "Modalità Console"+msgid "Consumed"+msgstr "Consumato"+msgid "Consumed expired"msgstr "Consumato scaduto"@@ -678,6 +684,9 @@ msgstr "Manutenzione Completata"msgid "Maintenance overdue"msgstr "Manutenzione scaduta"+msgid "Make a replacement"+msgstr "Crea una sostituzione"+msgid "Manually add items to inventory"msgstr "Aggiungi manualmente articoli all'inventario"@@ -868,6 +877,9 @@ msgstr "Niente in esecuzione"msgid "Nothing scheduled at this work center"msgstr "Niente pianificato in questo centro di lavoro"+msgid "Nothing to scrap"+msgstr "Nulla da scartare"+msgid "OEE Impact"msgstr "Impatto OEE"@@ -1053,6 +1065,9 @@ msgstr "Rimuovi Inventario"msgid "Remove part"msgstr "Rimuovi componente"+msgid "Reopen the subassembly and create a replacement unit"+msgstr "Riaprire il sottoassieme e creare un'unità di ricambio"+msgid "Result"msgstr "Risultato"@@ -1101,6 +1116,12 @@ msgstr "Pianificazione"msgid "Scrap"msgstr "Scarto"+msgid "Scrap {readableId}"+msgstr "Scarta {readableId}"++msgid "Scrap material"+msgstr "Scarta materiale"+msgid "Scrap quantity"msgstr "Quantità di scarto"@@ -1110,6 +1131,12 @@ msgstr "Motivo Scarto"msgid "Scrapped"msgstr "Scartato"+msgid "Scrapping serial {trackedEntityReadableId}"+msgstr "Scarto numero seriale {trackedEntityReadableId}"++msgid "Scrapping the selected serial"+msgstr "Scarto del numero di serie selezionato"+msgid "Search"msgstr "Cerca"@@ -1294,6 +1321,9 @@ msgstr "Il lotto sarà contrassegnato come Superato e {remaining} unità/unità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."+msgid "There are no available or consumed tracked parts for this material."+msgstr "Non ci sono parti tracciate disponibili o consumate per questo materiale."+msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."msgstr "Ci sono materiali tracciati per numero di serie o lotto nella distinta base che non sono stati completamente prelevati. Completare senza prelevare potrebbe causare registrazioni di tracciabilità errate."@@ -1303,6 +1333,15 @@ msgstr "Questi articoli hanno ancora materiale da prelevare. Il completamento ormsgid "This lot is expired and can't be picked."msgstr "Questo lotto è scaduto e non può essere prelevato."+msgid "This part was made to order. Scrapping it can reopen its routing to make a replacement."+msgstr "Questa parte è stata realizzata su ordinazione. Lo scarto può riaprire il percorso di produzione per creare una sostituzione."++msgid "This part will be scrapped from stock. Its requirement stays open so you can issue a replacement."+msgstr "Questa parte sarà scartata dallo stock. Il suo fabbisogno rimane aperto per poter emettere una sostituzione."++msgid "This unit will be permanently scrapped and a replacement serial number will be created."+msgstr "Questa unità sarà permanentemente scartata e verrà creato un nuovo numero seriale."+msgid "Thumbnail"msgstr "Miniatura"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 117b42a9b9..c87e882f69 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -10776,6 +10776,9 @@ msgstr "リソース"msgid "Restore from Trash"msgstr "ゴミ箱から復元"+msgid "Restore this entity to available stock at the bin and cost it was scrapped from."+msgstr "このエンティティを、スクラップされた元のビンと原価で利用可能な在庫に復元します。"+msgid "Restore tracked entities to available"msgstr "追跡対象エンティティを利用可能に復元"@@ -11246,6 +11249,9 @@ msgstr "スクラップ理由"msgid "Scrap Reasons"msgstr "スクラップ理由"+msgid "Scrapped"+msgstr "スクラップ済み"+msgid "Search"msgstr "検索"@@ -13976,6 +13982,12 @@ msgstr "未受領PO"msgid "Unsaved changes"msgstr "未保存の変更"+msgid "Unscrap"+msgstr "スクラップ解除"++msgid "Unscrap {label}"+msgstr "スクラップ解除 {label}"+msgid "Unshipped orders"msgstr "未発送注文"diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.poindex d2c792f3a6..da0ff30050 100644--- a/packages/locale/locales/ja/mes.po+++ b/packages/locale/locales/ja/mes.po@@ -153,6 +153,9 @@ msgstr "認証エラー"msgid "available"msgstr "利用可能"+msgid "Available"+msgstr "利用可能"+msgid "Batch"msgstr "バッチ"@@ -268,6 +271,9 @@ msgstr "コンソール"msgid "Console Mode"msgstr "コンソールモード"+msgid "Consumed"+msgstr "消費済み"+msgid "Consumed expired"msgstr "消費期限切れ"@@ -678,6 +684,9 @@ msgstr "メンテナンス完了"msgid "Maintenance overdue"msgstr "メンテナンス期限超過"+msgid "Make a replacement"+msgstr "代替品を作成"+msgid "Manually add items to inventory"msgstr "手動で在庫に品目を追加"@@ -868,6 +877,9 @@ msgstr "稼働中の作業はありません"msgid "Nothing scheduled at this work center"msgstr "このワークセンターにはスケジュールされたものはありません"+msgid "Nothing to scrap"+msgstr "スクラップするものがない"+msgid "OEE Impact"msgstr "OEE影響度"@@ -1053,6 +1065,9 @@ msgstr "在庫削除"msgid "Remove part"msgstr "パーツを削除"+msgid "Reopen the subassembly and create a replacement unit"+msgstr "サブアセンブリを再度開いて代替ユニットを作成"+msgid "Result"msgstr "結果"@@ -1101,6 +1116,12 @@ msgstr "スケジュール"msgid "Scrap"msgstr "廃棄"+msgid "Scrap {readableId}"+msgstr "{readableId} をスクラップ"++msgid "Scrap material"+msgstr "材料をスクラップ"+msgid "Scrap quantity"msgstr "スクラップ数量"@@ -1110,6 +1131,12 @@ msgstr "スクラップ理由"msgid "Scrapped"msgstr "スクラップ済み"+msgid "Scrapping serial {trackedEntityReadableId}"+msgstr "シリアル {trackedEntityReadableId} をスクラップ中"++msgid "Scrapping the selected serial"+msgstr "選択したシリアルをスクラップ中"+msgid "Search"msgstr "検索"@@ -1294,6 +1321,9 @@ 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を作成することはできません。"+msgid "There are no available or consumed tracked parts for this material."+msgstr "このマテリアルについて、利用可能または消費済みの追跡部品がありません。"+msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."msgstr "部品表にシリアルまたはバッチ追跡対象の材料が完全に払い出されていません。払出なしで完了すると、トレーサビリティ記録が不正確になる可能性があります。"@@ -1303,6 +1333,15 @@ msgstr "これらのアイテムにはまだピッキング対象の材料があmsgid "This lot is expired and can't be picked."msgstr "このロットは期限切れであり、ピックできません。"+msgid "This part was made to order. Scrapping it can reopen its routing to make a replacement."+msgstr "この部品は注文に応じて製造されました。これをスクラップすると、代替品を製造するためにそのルーティングを再度開くことができます。"++msgid "This part will be scrapped from stock. Its requirement stays open so you can issue a replacement."+msgstr "この部品は在庫からスクラップされます。その要件は開いたままなので、代替品を発行できます。"++msgid "This unit will be permanently scrapped and a replacement serial number will be created."+msgstr "このユニットは永久にスクラップされ、代替シリアル番号が作成されます。"+msgid "Thumbnail"msgstr "サムネイル"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex ebecab8614..91d0940786 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -10776,6 +10776,9 @@ msgstr "리소스"msgid "Restore from Trash"msgstr "휴지통에서 복원"+msgid "Restore this entity to available stock at the bin and cost it was scrapped from."+msgstr "이 항목을 폐기 전 보관 위치 및 원가의 사용 가능한 재고로 복원합니다."+msgid "Restore tracked entities to available"msgstr "추적 개체를 사용 가능 상태로 복원"@@ -11246,6 +11249,9 @@ msgstr "스크랩 사유"msgid "Scrap Reasons"msgstr "스크랩 사유"+msgid "Scrapped"+msgstr "폐기됨"+msgid "Search"msgstr "검색"@@ -13976,6 +13982,12 @@ msgstr "미입고 구매주문"msgid "Unsaved changes"msgstr "저장되지 않은 변경 사항"+msgid "Unscrap"+msgstr "폐기 취소"++msgid "Unscrap {label}"+msgstr "{label} 폐기 취소"+msgid "Unshipped orders"msgstr "미출하 주문"diff --git a/packages/locale/locales/ko/mes.po b/packages/locale/locales/ko/mes.poindex 5846641816..82e07d3539 100644--- a/packages/locale/locales/ko/mes.po+++ b/packages/locale/locales/ko/mes.po@@ -153,6 +153,9 @@ msgstr "인증 오류"msgid "available"msgstr "사용 가능"+msgid "Available"+msgstr "사용 가능"+msgid "Batch"msgstr "배치"@@ -268,6 +271,9 @@ msgstr "콘솔"msgid "Console Mode"msgstr "콘솔 모드"+msgid "Consumed"+msgstr "소비됨"+msgid "Consumed expired"msgstr "만료 후 소모됨"@@ -678,6 +684,9 @@ msgstr "유지보수 완료"msgid "Maintenance overdue"msgstr "기한이 지난 유지보수"+msgid "Make a replacement"+msgstr "교체품 만들기"+msgid "Manually add items to inventory"msgstr "재고에 품목을 수동으로 추가"@@ -868,6 +877,9 @@ msgstr "실행 중인 것 없음"msgid "Nothing scheduled at this work center"msgstr "이 작업 센터에서 예정된 것 없음"+msgid "Nothing to scrap"+msgstr "폐기할 것이 없습니다"+msgid "OEE Impact"msgstr "OEE 영향"@@ -1053,6 +1065,9 @@ msgstr "재고 제거"msgid "Remove part"msgstr "품목 제거"+msgid "Reopen the subassembly and create a replacement unit"+msgstr "부분 조립품을 다시 열고 교체 단위를 생성합니다"+msgid "Result"msgstr "결과"@@ -1101,6 +1116,12 @@ msgstr "일정"msgid "Scrap"msgstr "스크랩"+msgid "Scrap {readableId}"+msgstr "{readableId} 폐기"++msgid "Scrap material"+msgstr "자재 폐기"+msgid "Scrap quantity"msgstr "폐기 수량"@@ -1110,6 +1131,12 @@ msgstr "스크랩 사유"msgid "Scrapped"msgstr "스크랩됨"+msgid "Scrapping serial {trackedEntityReadableId}"+msgstr "일련번호 {trackedEntityReadableId} 폐기"++msgid "Scrapping the selected serial"+msgstr "선택한 일련번호 폐기"+msgid "Search"msgstr "검색"@@ -1294,6 +1321,9 @@ 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을 생성할 수 없습니다."+msgid "There are no available or consumed tracked parts for this material."+msgstr "이 재료에 대해 사용 가능하거나 소비된 추적된 부품이 없습니다."+msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."msgstr "자재명세서(BOM)에 아직 완전히 출고되지 않은 일련번호 또는 배치 추적 자재가 있습니다. 출고하지 않고 완료하면 이력추적 기록이 부정확해질 수 있습니다."@@ -1303,6 +1333,15 @@ msgstr "이 항목들은 아직 선택할 재료가 있습니다. 지금 완료msgid "This lot is expired and can't be picked."msgstr "이 로트는 만료되어 피킹할 수 없습니다."+msgid "This part was made to order. Scrapping it can reopen its routing to make a replacement."+msgstr "이 부품은 주문 제작되었습니다. 폐기하면 교체품을 만들기 위해 라우팅을 다시 열 수 있습니다."++msgid "This part will be scrapped from stock. Its requirement stays open so you can issue a replacement."+msgstr "이 부품은 재고에서 폐기됩니다. 요구사항은 열려있으므로 교체품을 발급할 수 있습니다."++msgid "This unit will be permanently scrapped and a replacement serial number will be created."+msgstr "이 단위는 영구적으로 폐기되며 교체 일련번호가 생성됩니다."+msgid "Thumbnail"msgstr "썸네일"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex a911e2c35f..c3c1d4e42c 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -10776,6 +10776,9 @@ msgstr "Zasoby"msgid "Restore from Trash"msgstr "Przywróć z Kosza"+msgid "Restore this entity to available stock at the bin and cost it was scrapped from."+msgstr "Przywróć tę jednostkę do dostępnych zapasów w pojemniku i po koszcie, z których została złomowana."+msgid "Restore tracked entities to available"msgstr "Przywróć śledzone jednostki do dostępnych"@@ -11246,6 +11249,9 @@ msgstr "Przyczyny złomu"msgid "Scrap Reasons"msgstr "Przyczyny złomu"+msgid "Scrapped"+msgstr "Złomowany"+msgid "Search"msgstr "Szukaj"@@ -13976,6 +13982,12 @@ msgstr "Nieprzyjęte zamówienia"msgid "Unsaved changes"msgstr "Niezapisane zmiany"+msgid "Unscrap"+msgstr "Przywrócić"++msgid "Unscrap {label}"+msgstr "Przywrócić {label}"+msgid "Unshipped orders"msgstr "Niewysłane zamówienia"diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.poindex bf1dd83d8b..092c92a266 100644--- a/packages/locale/locales/pl/mes.po+++ b/packages/locale/locales/pl/mes.po@@ -153,6 +153,9 @@ msgstr "Błąd uwierzytelniania"msgid "available"msgstr "dostępne"+msgid "Available"+msgstr "Dostępne"+msgid "Batch"msgstr "Partia"@@ -268,6 +271,9 @@ msgstr "Konsola"msgid "Console Mode"msgstr "Tryb konsoli"+msgid "Consumed"+msgstr "Zużyte"+msgid "Consumed expired"msgstr "Zużyte wygasłe"@@ -678,6 +684,9 @@ msgstr "Utrzymanie ruchu zakończone"msgid "Maintenance overdue"msgstr "Konserwacja przeterminowana"+msgid "Make a replacement"+msgstr "Utwórz zamiennik"+msgid "Manually add items to inventory"msgstr "Ręcznie dodaj pozycje do zapasów"@@ -868,6 +877,9 @@ msgstr "Nic nie działa"msgid "Nothing scheduled at this work center"msgstr "Nic nie zaplanowano w tym centrum roboczym"+msgid "Nothing to scrap"+msgstr "Nic do złomowania"+msgid "OEE Impact"msgstr "Wpływ na OEE"@@ -1053,6 +1065,9 @@ msgstr "Usuń zapasy"msgid "Remove part"msgstr "Usuń część"+msgid "Reopen the subassembly and create a replacement unit"+msgstr "Ponownie otwórz podzespół i utwórz zastępczą jednostkę"+msgid "Result"msgstr "Wynik"@@ -1101,6 +1116,12 @@ msgstr "Harmonogram"msgid "Scrap"msgstr "Złom"+msgid "Scrap {readableId}"+msgstr "Złom {readableId}"++msgid "Scrap material"+msgstr "Złom materiału"+msgid "Scrap quantity"msgstr "Ilość złomu"@@ -1110,6 +1131,12 @@ msgstr "Przyczyna odrzutu"msgid "Scrapped"msgstr "Odrzucone"+msgid "Scrapping serial {trackedEntityReadableId}"+msgstr "Złomowanie numeru seryjnego {trackedEntityReadableId}"++msgid "Scrapping the selected serial"+msgstr "Złomowanie wybranego numeru seryjnego"+msgid "Search"msgstr "Szukaj"@@ -1294,6 +1321,9 @@ msgstr "Partia zostanie oznaczona jako Zaakceptowana i {remaining} pozostałychmsgid "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."+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."+msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."msgstr "Na liście materiałowej znajdują się materiały śledzone seryjnie lub partiami, które nie zostały w pełni wydane. Ukończenie bez wydania może skutkować nieprawidłowymi rekordami śledzenia."@@ -1303,6 +1333,15 @@ msgstr "Te pozycje mają jeszcze materiał do wybrania. Zakończenie teraz oznacmsgid "This lot is expired and can't be picked."msgstr "Ta partia wygasła i nie można jej pobrać."+msgid "This part was made to order. Scrapping it can reopen its routing to make a replacement."+msgstr "Ta część została wykonana na zamówienie. Jej złomowanie może ponownie otworzyć trasę producji, aby wykonać zamiennik."++msgid "This part will be scrapped from stock. Its requirement stays open so you can issue a replacement."+msgstr "Ta część zostanie złomowana z magazynu. Jej zapotrzebowanie pozostaje otwarte, aby można było wystawić zamiennik."++msgid "This unit will be permanently scrapped and a replacement serial number will be created."+msgstr "Ta jednostka zostanie bezpowrotnie złomowana i zostanie utworzony nowy numer seryjny zamiennika."+msgid "Thumbnail"msgstr "Miniatura"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 9dce249943..fbdc562476 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -10776,6 +10776,9 @@ msgstr "Recursos"msgid "Restore from Trash"msgstr "Restaurar da Lixeira"+msgid "Restore this entity to available stock at the bin and cost it was scrapped from."+msgstr "Restaurar esta entidade para o estoque disponível no depósito e custo de onde foi sucatada."+msgid "Restore tracked entities to available"msgstr "Restaurar entidades rastreadas para disponível"@@ -11246,6 +11249,9 @@ msgstr "Motivos da sucata"msgid "Scrap Reasons"msgstr "Motivos de Sucata"+msgid "Scrapped"+msgstr "Sucatada"+msgid "Search"msgstr "Pesquisar"@@ -13976,6 +13982,12 @@ msgstr "POs não recebidas"msgid "Unsaved changes"msgstr "Alterações não salvas"+msgid "Unscrap"+msgstr "Recuperar da Sucata"++msgid "Unscrap {label}"+msgstr "Recuperar da Sucata {label}"+msgid "Unshipped orders"msgstr "Pedidos não enviados"diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.poindex 04c2d7fb5d..7d1196760b 100644--- a/packages/locale/locales/pt/mes.po+++ b/packages/locale/locales/pt/mes.po@@ -153,6 +153,9 @@ msgstr "Erro de Autenticação"msgid "available"msgstr "disponível"+msgid "Available"+msgstr "Disponível"+msgid "Batch"msgstr "Lote"@@ -268,6 +271,9 @@ msgstr "Console"msgid "Console Mode"msgstr "Modo Console"+msgid "Consumed"+msgstr "Consumido"+msgid "Consumed expired"msgstr "Consumido expirado"@@ -678,6 +684,9 @@ msgstr "Manutenção Concluída"msgid "Maintenance overdue"msgstr "Manutenção vencida"+msgid "Make a replacement"+msgstr "Fazer uma substituição"+msgid "Manually add items to inventory"msgstr "Adicionar itens ao estoque manualmente"@@ -868,6 +877,9 @@ msgstr "Nada em execução"msgid "Nothing scheduled at this work center"msgstr "Nada agendado neste centro de trabalho"+msgid "Nothing to scrap"+msgstr "Nada para descartar"+msgid "OEE Impact"msgstr "Impacto OEE"@@ -1053,6 +1065,9 @@ msgstr "Remover Estoque"msgid "Remove part"msgstr "Remover peça"+msgid "Reopen the subassembly and create a replacement unit"+msgstr "Reabrir a subassebleia e criar uma unidade de substituição"+msgid "Result"msgstr "Resultado"@@ -1101,6 +1116,12 @@ msgstr "Cronograma"msgid "Scrap"msgstr "Sucata"+msgid "Scrap {readableId}"+msgstr "Descartar {readableId}"++msgid "Scrap material"+msgstr "Descartar material"+msgid "Scrap quantity"msgstr "Quantidade de sucata"@@ -1110,6 +1131,12 @@ msgstr "Motivo do Refugo"msgid "Scrapped"msgstr "Refugado"+msgid "Scrapping serial {trackedEntityReadableId}"+msgstr "Descartando serial {trackedEntityReadableId}"++msgid "Scrapping the selected serial"+msgstr "Descartando a serial selecionada"+msgid "Search"msgstr "Pesquisar"@@ -1294,6 +1321,9 @@ msgstr "O lote será marcado como Aprovado e {remaining} unidade(s) restante(s)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."+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."+msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."msgstr "Existem materiais rastreados por série ou lote na lista de materiais que não foram totalmente emitidos. Concluir sem emitir pode resultar em registros de rastreabilidade incorretos."@@ -1303,6 +1333,15 @@ msgstr "Estes itens ainda têm material para selecionar. Finalizar agora marca amsgid "This lot is expired and can't be picked."msgstr "Este lote expirou e não pode ser selecionado."+msgid "This part was made to order. Scrapping it can reopen its routing to make a replacement."+msgstr "Esta peça foi feita sob encomenda. Descartá-la pode reabrir seu roteamento para fazer uma substituição."++msgid "This part will be scrapped from stock. Its requirement stays open so you can issue a replacement."+msgstr "Esta peça será descartada do estoque. Seu requisito permanece aberto para que você possa emitir uma substituição."++msgid "This unit will be permanently scrapped and a replacement serial number will be created."+msgstr "Esta unidade será permanentemente descartada e um novo número de série de substituição será criado."+msgid "Thumbnail"msgstr "Miniatura"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex be16ff1a3a..cca2d1e981 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -10776,6 +10776,9 @@ msgstr "Ресурсы"msgid "Restore from Trash"msgstr "Восстановить из корзины"+msgid "Restore this entity to available stock at the bin and cost it was scrapped from."+msgstr "Восстановить эту сущность в доступный запас на складе и стоимость, из которых она была списана."+msgid "Restore tracked entities to available"msgstr "Восстановить отслеживаемые объекты в доступные"@@ -11246,6 +11249,9 @@ msgstr "Причины брака"msgid "Scrap Reasons"msgstr "Причины брака"+msgid "Scrapped"+msgstr "Списано"+msgid "Search"msgstr "Поиск"@@ -13976,6 +13982,12 @@ msgstr "Неполученные ПО"msgid "Unsaved changes"msgstr "Несохранённые изменения"+msgid "Unscrap"+msgstr "Восстановить из списания"++msgid "Unscrap {label}"+msgstr "Восстановить из списания {label}"+msgid "Unshipped orders"msgstr "Невыполненные заказы"diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.poindex 9a574b24ae..13a4a35b7f 100644--- a/packages/locale/locales/ru/mes.po+++ b/packages/locale/locales/ru/mes.po@@ -153,6 +153,9 @@ msgstr "Ошибка аутентификации"msgid "available"msgstr "доступно"+msgid "Available"+msgstr "Доступно"+msgid "Batch"msgstr "Партия"@@ -268,6 +271,9 @@ msgstr "Консоль"msgid "Console Mode"msgstr "Режим консоли"+msgid "Consumed"+msgstr "Использовано"+msgid "Consumed expired"msgstr "Потреблено истекшее"@@ -678,6 +684,9 @@ msgstr "Обслуживание завершено"msgid "Maintenance overdue"msgstr "Обслуживание просрочено"+msgid "Make a replacement"+msgstr "Создать замену"+msgid "Manually add items to inventory"msgstr "Добавить номенклатуру на склад вручную"@@ -868,6 +877,9 @@ msgstr "Ничего не работает"msgid "Nothing scheduled at this work center"msgstr "Ничего не запланировано на этом рабочем центре"+msgid "Nothing to scrap"+msgstr "Нечего списывать"+msgid "OEE Impact"msgstr "Влияние на OEE"@@ -1053,6 +1065,9 @@ msgstr "Списать запас"msgid "Remove part"msgstr "Удалить деталь"+msgid "Reopen the subassembly and create a replacement unit"+msgstr "Снова открыть узел и создать сменный агрегат"+msgid "Result"msgstr "Результат"@@ -1101,6 +1116,12 @@ msgstr "Расписание"msgid "Scrap"msgstr "Брак"+msgid "Scrap {readableId}"+msgstr "Списать {readableId}"++msgid "Scrap material"+msgstr "Списать материал"+msgid "Scrap quantity"msgstr "Количество брака"@@ -1110,6 +1131,12 @@ msgstr "Причина брака"msgid "Scrapped"msgstr "Списано в брак"+msgid "Scrapping serial {trackedEntityReadableId}"+msgstr "Списание серийного номера {trackedEntityReadableId}"++msgid "Scrapping the selected serial"+msgstr "Списание выбранного серийного номера"+msgid "Search"msgstr "Поиск"@@ -1294,6 +1321,9 @@ msgstr "Партия будет отмечена как Пройдена, и {remsgid "The lot will still be dispositioned, but an NCR cannot be created until at least one Issue Type is configured."msgstr "Партия все еще будет распределена, но NCR не может быть создана до тех пор, пока не будет настроен хотя бы один тип проблемы."+msgid "There are no available or consumed tracked parts for this material."+msgstr "Для этого материала нет доступных или использованных отслеживаемых компонентов."+msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."msgstr "В спецификации есть материалы с серийным или партионным учётом, которые не были полностью выданы. Завершение без выдачи может привести к некорректным записям прослеживаемости."@@ -1303,6 +1333,15 @@ msgstr "Эти позиции содержат материал для подбmsgid "This lot is expired and can't be picked."msgstr "Эта партия истекла и не может быть выбрана."+msgid "This part was made to order. Scrapping it can reopen its routing to make a replacement."+msgstr "Эта часть была изготовлена на заказ. Её списание может снова открыть маршрут для создания замены."++msgid "This part will be scrapped from stock. Its requirement stays open so you can issue a replacement."+msgstr "Эта часть будет списана со склада. Её требование остается открытым, чтобы вы могли выдать замену."++msgid "This unit will be permanently scrapped and a replacement serial number will be created."+msgstr "Эта единица будет окончательно списана, и будет создан новый серийный номер замены."+msgid "Thumbnail"msgstr "Миниатюра"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex ddd416234c..fe13e64169 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -10776,6 +10776,9 @@ msgstr "Kaynaklar"msgid "Restore from Trash"msgstr "Çöp'ten Geri Yükle"+msgid "Restore this entity to available stock at the bin and cost it was scrapped from."+msgstr "Bu varlığı çıkartıldığı depo ve maliyet için kullanılabilir stoka geri yükleyin."+msgid "Restore tracked entities to available"msgstr "Takip edilen varlıkları kullanılabilir hale getir"@@ -11246,6 +11249,9 @@ msgstr "Hurda nedenleri"msgid "Scrap Reasons"msgstr "Hurdaya Nega"+msgid "Scrapped"+msgstr "Çıkartıldı"+msgid "Search"msgstr "Ara"@@ -13976,6 +13982,12 @@ msgstr "Alınmamış PO'lar"msgid "Unsaved changes"msgstr "Kaydedilmemiş değişiklikler"+msgid "Unscrap"+msgstr "Çıkartmayı Geri Al"++msgid "Unscrap {label}"+msgstr "Çıkartmayı Geri Al {label}"+msgid "Unshipped orders"msgstr "Gönderilmemiş siparişler"diff --git a/packages/locale/locales/tr/mes.po b/packages/locale/locales/tr/mes.poindex 1edd25508d..a861e6af14 100644--- a/packages/locale/locales/tr/mes.po+++ b/packages/locale/locales/tr/mes.po@@ -153,6 +153,9 @@ msgstr "Kimlik Doğrulama Hatası"msgid "available"msgstr "mevcut"+msgid "Available"+msgstr "Mevcut"+msgid "Batch"msgstr "Parti"@@ -268,6 +271,9 @@ msgstr "Konsol"msgid "Console Mode"msgstr "Konsol Modu"+msgid "Consumed"+msgstr "Tüketildi"+msgid "Consumed expired"msgstr "Tüketilmiş süre dolmuş"@@ -678,6 +684,9 @@ msgstr "Bakım Tamamlandı"msgid "Maintenance overdue"msgstr "Bakım vadesi geçmiş"+msgid "Make a replacement"+msgstr "Bir yedek oluştur"+msgid "Manually add items to inventory"msgstr "Envantere öğeler eklemek için manuel olarak"@@ -868,6 +877,9 @@ msgstr "Hiçbir şey çalışmıyor"msgid "Nothing scheduled at this work center"msgstr "Bu iş merkezinde hiçbir şey planlanmadı"+msgid "Nothing to scrap"+msgstr "Atılacak hiçbir şey yok"+msgid "OEE Impact"msgstr "OEE Etkisi"@@ -1053,6 +1065,9 @@ msgstr "Stoktan Çıkar"msgid "Remove part"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 "Result"msgstr "Sonuç"@@ -1101,6 +1116,12 @@ msgstr "Planlama"msgid "Scrap"msgstr "Hurda"+msgid "Scrap {readableId}"+msgstr "Hurdala {readableId}"++msgid "Scrap material"+msgstr "Malzeme hurdası"+msgid "Scrap quantity"msgstr "Hurda miktarı"@@ -1110,6 +1131,12 @@ msgstr "Hurda Nedeni"msgid "Scrapped"msgstr "Hurdaya Ayrılan"+msgid "Scrapping serial {trackedEntityReadableId}"+msgstr "Seri hurdası {trackedEntityReadableId}"++msgid "Scrapping the selected serial"+msgstr "Seçilen serinin hurdası"+msgid "Search"msgstr "Ara"@@ -1294,6 +1321,9 @@ msgstr "Lot Passed olarak işaretlenecek ve {remaining} kalan birim(ler) bu opermsgid "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."+msgid "There are no available or consumed tracked parts for this material."+msgstr "Bu malzeme için mevcut veya tüketilmiş izlenen parça bulunmamaktadır."+msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."msgstr "Malzeme listesindeki seri veya parti takipli malzemeler tam olarak verilmemiş. Vermeden tamamlamak, yanlış izlenebilirlik kayıtlarına neden olabilir."@@ -1303,6 +1333,15 @@ msgstr "Bu öğelerin hala seçilecek malzemesi var. Şimdi bitirmek listeyi Kımsgid "This lot is expired and can't be picked."msgstr "Bu parti süresi dolmuş ve alınamaz."+msgid "This part was made to order. Scrapping it can reopen its routing to make a replacement."+msgstr "Bu parça siparişe göre yapılmıştır. Hurdalaması, bir yedek yapmak için rotasını yeniden açabilir."++msgid "This part will be scrapped from stock. Its requirement stays open so you can issue a replacement."+msgstr "Bu parça stoktan hurdaya çıkarılacaktır. Gereksinimleri açık kalır, böylece bir yedek çıkarabilirsiniz."++msgid "This unit will be permanently scrapped and a replacement serial number will be created."+msgstr "Bu birim kalıcı olarak hurdaya çıkarılacak ve yedek bir seri numarası oluşturulacaktır."+msgid "Thumbnail"msgstr "Küçük Resim"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 820bdd24ed..53ee2a686a 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -10776,6 +10776,9 @@ msgstr "资源"msgid "Restore from Trash"msgstr "从垃圾箱恢复"+msgid "Restore this entity to available stock at the bin and cost it was scrapped from."+msgstr "将此实体恢复到报废时所在的仓位和成本的可用库存。"+msgid "Restore tracked entities to available"msgstr "将跟踪的实体恢复为可用"@@ -11246,6 +11249,9 @@ msgstr "报废原因"msgid "Scrap Reasons"msgstr "报废原因"+msgid "Scrapped"+msgstr "已报废"+msgid "Search"msgstr "搜索"@@ -13976,6 +13982,12 @@ msgstr "未收到的采购订单"msgid "Unsaved changes"msgstr "未保存的更改"+msgid "Unscrap"+msgstr "取消报废"++msgid "Unscrap {label}"+msgstr "取消报废 {label}"+msgid "Unshipped orders"msgstr "未发货订单"diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.poindex 64972708b5..bf5ccf22b2 100644--- a/packages/locale/locales/zh/mes.po+++ b/packages/locale/locales/zh/mes.po@@ -153,6 +153,9 @@ msgstr "认证错误"msgid "available"msgstr "可用"+msgid "Available"+msgstr "可用"+msgid "Batch"msgstr "批次"@@ -268,6 +271,9 @@ msgstr "控制台"msgid "Console Mode"msgstr "控制台模式"+msgid "Consumed"+msgstr "已消耗"+msgid "Consumed expired"msgstr "已消耗过期"@@ -678,6 +684,9 @@ msgstr "维护已完成"msgid "Maintenance overdue"msgstr "维护逾期"+msgid "Make a replacement"+msgstr "制作替换件"+msgid "Manually add items to inventory"msgstr "手动添加物料到库存"@@ -868,6 +877,9 @@ msgstr "没有运行"msgid "Nothing scheduled at this work center"msgstr "该工作中心没有计划任务"+msgid "Nothing to scrap"+msgstr "没有需要报废的"+msgid "OEE Impact"msgstr "OEE 影响"@@ -1053,6 +1065,9 @@ msgstr "移除库存"msgid "Remove part"msgstr "移除零件"+msgid "Reopen the subassembly and create a replacement unit"+msgstr "重新打开子装配体并创建替换单元"+msgid "Result"msgstr "结果"@@ -1101,6 +1116,12 @@ msgstr "排程"msgid "Scrap"msgstr "报废"+msgid "Scrap {readableId}"+msgstr "报废 {readableId}"++msgid "Scrap material"+msgstr "报废物料"+msgid "Scrap quantity"msgstr "报废数量"@@ -1110,6 +1131,12 @@ msgstr "报废原因"msgid "Scrapped"msgstr "已报废"+msgid "Scrapping serial {trackedEntityReadableId}"+msgstr "报废序列号 {trackedEntityReadableId}"++msgid "Scrapping the selected serial"+msgstr "报废所选序列号"+msgid "Search"msgstr "搜索"@@ -1294,6 +1321,9 @@ 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。"+msgid "There are no available or consumed tracked parts for this material."+msgstr "此材料没有可用或已消耗的追踪件。"+msgid "There are serial or batch tracked materials on the bill of material that have not been fully issued. Completing without issuing may result in incorrect traceability records."msgstr "物料清单中有序列号或批次追踪的物料尚未完全发放。不发放即完成可能导致追溯记录不正确。"@@ -1303,6 +1333,15 @@ msgstr "这些项目仍有物料需要拣选。现在完成将把列表标记为msgid "This lot is expired and can't be picked."msgstr "此批次已过期,无法领取。"+msgid "This part was made to order. Scrapping it can reopen its routing to make a replacement."+msgstr "此部件是按订单生产的。报废它可以重新打开其路线以制作替换件。"++msgid "This part will be scrapped from stock. Its requirement stays open so you can issue a replacement."+msgstr "此部件将从库存中报废。其需求保持打开状态,以便您可以发放替换件。"++msgid "This unit will be permanently scrapped and a replacement serial number will be created."+msgstr "此单元将被永久报废,并将创建替换序列号。"+msgid "Thumbnail"msgstr "缩略图"diff --git a/packages/react/src/Spinner.tsx b/packages/react/src/Spinner.tsxindex 796022bab5..2833a53626 100644--- a/packages/react/src/Spinner.tsx+++ b/packages/react/src/Spinner.tsx@@ -8,7 +8,7 @@ interface SpinnerProps {const BARS = Array.from({ length: 12 });-export function Spinner({ size = 18, className }: SpinnerProps) {+export function Spinner({ size = 16, className }: SpinnerProps) {return (<divrole="status"diff --git a/packages/utils/src/status-colors.ts b/packages/utils/src/status-colors.tsindex 7f15b1de4e..7693fe4542 100644--- a/packages/utils/src/status-colors.ts+++ b/packages/utils/src/status-colors.ts@@ -130,7 +130,8 @@ export const TRACKED_ENTITY_STATUS_COLOR_MAP = {Reserved: "gray","On Hold": "orange",Rejected: "red",- Consumed: "blue"+ Consumed: "blue",+ Scrapped: "red"} as const satisfies Record<string, StatusColor>;export const SALES_INVOICE_STATUS_COLOR_MAP = {