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.
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
- Task 1: Migration A — scrap enums + itemLedger.scrapReasonId
- Task 2: Migration B — Done-predicate fix (RPC exclusions verified unnecessary — see task note)
- Task 3: Apply migrations and regenerate types
- Task 4: Extend the shared adjustment posting core (dimensions, scrapReasonId, fixed-cost override)
- Task 5: post-inventory-adjustment — Scrap and Unscrap adjustment types
- Task 6: issue — jobOperationScrap case (serial/batch/untracked WIP scrap + spawn + reopen). Deviation:
issueJobOperationMaterialsreturns{ totalMaterialCost }(additive) — a local COGS recompute would double-relieve layers. - Task 7: issue — rework scrapTrackedEntity (reason, methodType branches, replacement). Deviations:
rework.trackedEntityIdcolumn 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. - Task 8: MES routes + validators for the new scrap paths
- Task 9: MES UI — QuantityModal serial confirmation + entity-scrap modal fields
- Task 10: ERP models/service/route for Scrap + Unscrap
- Task 11: ERP UI — Scrap adjustment type + Scrapped filter + Unscrap action
- Task 12: Sweep app-side predicate mirrors + serial-navigation helpers
- 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(viapnpm db:migrate:new scrap-unscrap-enums— never hand-pick the timestamp; HHMMSS must not be000000)
Steps:
- Run
pnpm db:migrate:new scrap-unscrap-enumsfrom the repo root. - 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):
-- 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:
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(viapnpm db:migrate:new scrap-unscrap-functions)
Steps:
- Run
pnpm db:migrate:new scrap-unscrap-functions. - 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):
Extract each newest body withgrep -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 | sortsed -n '<start>,<end>p'into the new migration, thendiffyour pasted body against the source so the ONLY hunks are the edits below. - Edits per function:
sync_update_job_operation_quantities(newest:20260706181125_fix-auto-complete-null-user.sql): change the auto-Done predicate lineAND ("quantityComplete" + "quantityReworked" + "quantityScrapped") >= "targetQuantity"toAND ("quantityComplete" + "quantityReworked") >= "targetQuantity"(Brad, 2026-08-07 —targetQuantityis the GOOD quantity per20260119120000; scrap must not consume it). No other hunk.— verified unnecessary during execution (2026-08-07):get_inventory_quantities,get_available_tracked_entities,get_picking_list_tracked_availableitemLedger.trackedEntityStatusis SYNCED to the entity's current status (20260420112047triggersync_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 inget_inventory_quantitieswith or without a status exclusion (unlikeRejected, which keeps positive rows and needs the exclusion).get_available_tracked_entities(20260709125411:104) andget_picking_list_tracked_available(20260617142853:100) filterte."status" = 'Available'— Scrapped is excluded by construction. No redefinition of the three RPCs.
- Preserve
SECURITY DEFINER/language attributes exactly as the newest version has them.
Verify:
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:
pnpm run generate:types- Commit the regenerated files together with the migrations (types regen is normal and expected).
Verify:
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:
- Add to the
accountingarg 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". - In the dimension-tagging block (currently ~lines 354–378, the
dimensionValuesarray of["Item", ...], ["ItemPostingGroup", ...], ["Location", ...]): append...(accounting.extraDimensions ?? []).map(d => [d.entityType, d.valueId] as [string, string])todimensionValuesbefore the.filter(...)that drops entries whose entityType has no active dimension. - Add to the ledger arg type:
scrapReasonId?: string | null; pass it through on theitemLedgerinsert (~line 166–184). - Add
fixedUnitCost?: numberto the args: when set AND the movement is an increase, the newcostLedgerlayer is booked atfixedUnitCost × quantityinstead ofcomputeCurrentUnitCost(used by Unscrap to reverse at the original scrapped cost). Decreases ignore it (they always go throughcalculateCOGS). 'Scrap'must be added toJOURNAL_LINE_SAFE_DOCUMENT_TYPES(~line 93) so scrap ledger rows map to journaldocumentType='Scrap'instead of falling back to'Inventory Adjustment'.
Verify:
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— widenchildStatusunion with"Scrapped"(discovered during execution; additive type change only, callers unaffected)
Steps:
- Extend the zod payload (~line 28):
adjustmentTypeenum adds"Scrap"and"Unscrap"; addscrapReasonId: z.string().optional(),unscrapOfItemLedgerId: z.string().optional();.superRefinerequiringscrapReasonIdwheneveradjustmentTypeisScraporUnscrap. - Extend the active-dimension fetch (~line 161):
.in("entityType", ["Item", "ItemPostingGroup", "Location", "ScrapReason", "WorkCenter", "Employee"]). - Scrap branch = the existing Negative-Adjmt. resolution path (serial-by-readableId / single-tracked-entity / untracked,
Set Quantityexcluded) with these deltas:bookAdjustmentcalled withdocumentType: "Scrap",scrapReasonId, andaccounting.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 itsquantity(the record of what was scrapped — today's negative path decrements it; the Scrap branch must not). Insert atrackedActivitytype: 'Scrap'(sourceDocument: 'Item',sourceDocumentId: itemId, attributes{ "Scrap Reason": scrapReasonId }) +trackedActivityInput(entity, quantity). - Batch partial scrap (quantity < entity quantity): use
buildBatchSplitRecordsfrom../shared/batch-split.ts— the departing CHILD becomes theScrappedentity, the parent keeps its id and is decremented (identity-flip convention).
- Unscrap branch (tracked): payload carries
trackedEntityIdof aScrappedentity +unscrapOfItemLedgerId(the original scrapitemLedgerrow). Steps: verify the entity isScrapped(else throw); setstatus = 'Available'; positiveitemLedgerviabookAdjustment(documentType: "Scrap",correctionOfItemLedgerId: unscrapOfItemLedgerId, samestorageUnitIdas the original scrap row,scrapReasonId, extraDimensions as above) withfixedUnitCost= original scrapped unit cost;trackedActivitytype: 'Unscrap'+trackedActivityOutput. - Unscrap branch (untracked): positive adjustment through
bookAdjustmentwith the scrap offset + reason, nofixedUnitCost(current cost — v1). resolve-unscrap-cost.ts: pure functionresolveUnscrapUnitCost(rows: Array<{ quantity: number; cost: number }>): number | null— given the original scrap movement'scostLedgerrows, returnMath.abs(total cost / total quantity)ornullwhen rows are empty/zero-quantity (caller then falls back to current cost).deno testcovers: single row, multi-row, empty, zero-quantity.- Wire the cost lookup:
costLedgerrows are found by the scrap ledger row's id — check howcostLedgerlinks toitemLedgerin this function's existing decrease path (it inserts both; find the linking column, e.g.itemLedgerIdordocumentId). If NO queryable link from anitemLedgerrow to itscostLedgerrows exists, STOP and report — do not guess a join.
Verify:
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.tscasejobOperationSerialComplete(lines ~1173–1386 pre-change)
Steps:
- 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 pathjobOperationSerialScrap; implementation is ONE case discriminated internally by the make method's tracking flags — serial requirestrackedEntityIdandquantity === 1; batch/untracked takequantity. Note this naming consolidation in the PR description.) - In one Kysely transaction, mirroring
jobOperationSerialComplete's structure: a. InsertproductionQuantity{ type: 'Scrap', quantity, scrapReasonId, notes, jobOperationId, companyId, createdBy: userId }+ the event links (the quantity-sync interceptor aggregatesquantityScrapped; with Task 2's predicate it no longer flips Done). b. Backflush the operation's materials forquantityunits viaissueJobOperationMaterials(same call thejobOperationcase makes), capturing the returned/computed total material cost for step (e). c. Serial only:trackedActivitytype: 'Scrap',sourceDocument: 'Job Operation',sourceDocumentId: jobOperationId, attributes{ "Scrap Reason": scrapReasonId, ["Operation " + jobOperationId]: <index> };trackedActivityInput(entity, qty 1); update entitystatus: 'Scrapped'(keep quantity 1). If the entity's status isConsumedor alreadyScrapped, throw ("entity is not in progress"). d. Serial only — spawn the next serial: samegetNextSerialNumbers(trx, { itemId, companyId, count: 1, locationCode, locationName })+Reserved-entity insert (cloned attributes,readableId= spawned) asjobOperationSerialComplete, spawned when count of the make method's non-Scrappedentities < the good quantity still required (targetQuantityof the operation). ReturnnewTrackedEntityId. e. GL (only whencompanySettings.accountingEnabled): one journal, DraccountDefault.scrapAccount ?? inventoryAdjustmentVarianceAccount/ CrworkInProgressAccount, amount = (b)'s actual current-op backflush cost + estimated prior-op material cost (Σ over the make method'sjobMaterialrows attached to operations ordered BEFORE this one:quantityPerParent-equivalent unit quantity × itemCost.unitCost) ×quantity. Use thedebit()/credit()helpers,sourceTypethe same value the existingcreateMaterialWipEntriesjournals use,documentType: 'Scrap',documentId: jobId. Dimension tags per thepost-adjustment.tsmechanism: fetch active dimensions for entityTypes["Item","ItemPostingGroup","Location","ScrapReason","WorkCenter","Employee"](company →companyGroupId, precedentpost-inventory-adjustment/index.ts:146-167) and insertjournalLineDimensionrows for item, item's posting group, job location,scrapReasonId, the operation'sworkCenterId, anduserId. f.scrap-replacement.tshelperapplyScrapReplacement(trx, { jobMakeMethodId, jobId, quantity, companyId, userId }): (i) reopen the make method's operationsstatus = 'Ready'wherestatus = 'Done'(stampupdatedBy/updatedAt— null-audit lesson); (ii) compute cumulative allowance: root make method →job.scrapQuantity; if the job's cumulative actual scrap (ΣquantityScrappedof the make method's ops... use the make method's max opquantityScrapped+ this quantity) exceeds the allowance, bump each op'soperationQuantityby the excess and, when the make method is the root (parentMaterialId IS NULL), bumpjob.scrapQuantityby the excess; (iii) refresh the make method'sjobMaterial.estimatedQuantity/quantityfields to per-unit quantity × newoperationQuantity(read how those two columns relate on existing rows first; mirror the ratio).targetQuantityis NEVER written. (iv) invoke the same reschedule thetrigger-reworkfunction calls (find its invoke near the end oftrigger-rework/index.tsand replicate). g. CallapplyScrapReplacementfor serial and batch parents (untracked too — the reopen/top-up logic is tracking-agnostic). - If
issueJobOperationMaterialsdoes 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 modifyissueJobOperationMaterials' return type if other callers would be affected; prefer a local computation.
Verify:
# 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— casescrapTrackedEntity(~lines 1682–1871 pre-change)
Steps:
- Payload additions:
scrapReasonId: z.string()(required),makeReplacement: z.boolean().optional(). - Common changes (all branches): entity
status: 'Scrapped'(wasConsumed); activitytype: 'Scrap'(was'Consume'+attributes.Scrapped), attributes gain{ "Scrap Reason": scrapReasonId }; keep theparentTrackedEntityIdoutput row behavior exactly as today. - Non-Make-to-Order branch (was: Consumption ledger +
createMaterialWipEntries+quantityIssuedbump) becomes:bookAdjustment(import from../shared/post-adjustment.ts) with:entryType 'Negative Adjmt.',documentType 'Scrap',documentId: jobId,scrapReasonId, quantity negative,storageUnitIdfromresolveTrackedEntityBin(already imported in this file — never.find(...)?.storageUnitId),trackedEntityId,accounting.offsetAccount = scrapAccountfallback chain,extraDimensions= ScrapReason + WorkCenter (material.jobOperationId→ operation'sworkCenterId) + Employee (userId).- DELETE the
jobMaterial.quantityIssuedbump (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 theScrappedentity.
- 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
jobMaterialunit estimates × quantity — resolve the subassembly'sjobMakeMethodvia the material'sjobMaterialWithMakeMethodId/jobMakeMethod.parentMaterialIdlinkage; readget_job_method's join in20240915192542_job-methods.sql:217-288for the exact columns). WhenmakeReplacementis true: callapplyScrapReplacementon the subassembly'sjobMakeMethod+ spawn a replacementReservedserial entity when the subassembly requires serial tracking (same spawn as Task 6 step d); insert areworkrow{ jobId, triggeredAtJobOperationId: material.jobOperationId, targetJobOperationId: <first op of the subassembly make method by order>, reason: <scrapReason.name>, quantity, trackedEntityId, requestedById: userId, companyId }. - If the material's
methodTypecannot be read where the branch splits (verify the existingmaterial.methodType !== "Make to Order"guard at ~line 1820 still exists), STOP and report.
Verify:
# 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— extendscrapQuantityValidator; addscrapTrackedEntityValidator - 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:
models.ts:scrapQuantityValidatoralready carriesjobOperationId,quantity,scrapReasonId(required),notes,trackedEntityId,trackingType— no change needed; confirm and leave as-is. Add:
(Checkexport const scrapTrackedEntityValidator = z.object({ scrapReasonId: zfd.text(z.string()), makeReplacement: zfd.checkbox(), notes: zfd.text(z.string().optional()) });zfd.checkboxexists in this file's zfd usage; if not, usezfd.text(z.string().optional()).transform(v => v === "true" || v === "on").)x+/scrap.tsx: replace theinsertScrapQuantity+issue type:"jobOperation"pair with ONE service-role invoke ofissue{ 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'snewTrackedEntityIdin the action data so the client can navigate to the spawned serial (mirror howx+/complete.tsxreturns its result — read that file first and copy its return shape).- Entity scrap route: parse
await request.formData()throughvalidator(scrapTrackedEntityValidator); passscrapReasonId+makeReplacementin theissuebody. KeepparentIdquery-param handling as-is. ChangerequirePermissions(request, {})torequirePermissions(request, { update: "production" })on BOTH routes only if the existing MES mutation routes do so — checkx+/complete.tsxfirst and match it exactly (do not invent a stricter gate than the app's convention).
Verify:
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' -lthen locate the caller of the$materialId.$trackedEntityId.scrappath helper — likely inJobOperation.tsx's Materials section orIssueMaterialModal.tsx) - Copy from (precedent):
QuantityModal.tsxscrap branch itself (ScrapReason + notes composition);apps/mes/app/components/JobOperation/components/ScrapReason.tsx
Steps:
QuantityModalscrap branch: when the parent is serial-tracked (the modal already receives tracking context — it submitstrackedEntityId/trackingTypehidden fields perbaseQuantityValidator), render the selected serial'sreadableIdabove 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 componentssize="lg".- On successful scrap of a serial with a spawned replacement (
newTrackedEntityIdin the action response), navigate to the new entity the same way the complete flow advances serials — find the?trackedEntityIdnavigation inuseOperation.tsx/AssemblyView.tsxpost-complete handling and reuse that exact mechanism. - Entity-scrap trigger: replace the current bare confirm (route invoke with no body) with a small modal:
ScrapReason(required), notesTextArea, and — only when the material'smethodType === "Make to Order"— aCheckbox"Make replacement" defaulting checked. Submit as formData to the same route.size="lg".
Verify:
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—insertManualInventoryAdjustmentpassthrough - Modify:
apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx— no structural change; confirm passthrough
Steps:
inventoryAdjustmentValidator: changeadjustmentTypetoz.enum([...itemLedgerTypes, "Set Quantity", "Scrap", "Unscrap"]); addscrapReasonId: zfd.text(z.string().optional()),unscrapOfItemLedgerId: zfd.text(z.string().optional()); extend the existing.superRefineto requirescrapReasonIdwhenadjustmentTypeis"Scrap"or"Unscrap"(.refinemust return boolean / use ctx.addIssue — zod refine lesson).insertManualInventoryAdjustment: it forwards the validated payload to thepost-inventory-adjustmentinvoke — add the two new fields to its body object (keep the{ data, error }signature).- The adjustment route action already strips
requiresSerialTrackingand 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 howadjustmentTypemaps to the surface today and extend the mapping the same way.
Verify:
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.tsxitself (its type select + conditional fields);apps/erp/app/components/Form/ScrapReason.tsxfor the reason select; existing row-action menus inTrackedEntitiesTable.tsx
Steps:
- 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 defaultsize="md". TrackedEntitiesTable: ensure the status filter options includeScrapped(read how the status filter list is built — if it derives from the generated enum type, it may pick upScrappedautomatically; verify rather than hardcode). Add a row action "Unscrap" visible only whenrow.status === "Scrapped"andpermissions.can("update", "inventory"): opens a modal (Drawer/Modal per this table's existing action precedent) withScrapReason+ confirm, posting topath.to.inventoryItemAdjustment(itemId)with hidden fieldsadjustmentType="Unscrap",trackedEntityId,quantity= entity quantity,locationId, andunscrapOfItemLedgerId= the entity's scrap movement (fetch: the entity'sitemLedgerrow withdocumentType='Scrap'and negative quantity, newest — if the table's loader can't provide it cheaply, pass onlytrackedEntityIdand resolve the ledger row server-side in the edge function; choose the server-side option if the loader would need a new join).- 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:
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),line 1205)getNextIncompleteSerialEntity(
Steps:
InspectionView.tsxopRemaining: remove the- (operation.quantityScrapped ?? 0)term (scrap no longer reduces remaining good work; keep thequantityReworkedterm).- 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 astarget − complete − scrapped(orcomplete + scrapped >= target) loses the scrap term; display-only usages stay (JobDag badge, theoperationQuantity + quantityScrappedstep-record navigation inJobOperation.tsx, kanban card counts, plain headings). List every changed and every deliberately-kept site in the task commit message. operations.service.ts: both serial-navigation helpers currently treatstatus !== "Consumed"as incomplete — extend to!["Consumed", "Scrapped"].includes(status)(or the equivalent in the existing code shape).
Verify:
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—trackedEntityStatusenum gainsScrapped; 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:
- 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.
- 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:
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:
- Boot the stack with plain
crbn up(portless). If the stack cannot boot, the loop is BLOCKED, not done — report. - Invoke the
/testskill 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,targetQuantitystill 3,operationQuantity4,job.scrapQuantity1 (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 +
reworkrow + 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
journalLineDimensionrows (activate those dimensions in settings first). - Planned-scrap job (10 + 20%): 8 good + 2 scrap does NOT auto-Done.
- Serial job qty 3: scrap the in-progress serial at op 2 from the operation view → verify entity
- Capture screenshots for the PR (net-new UI: ERP Scrap option, Scrapped filter + Unscrap action, MES scrap modal serial confirmation, entity-scrap modal).
Verify:
# /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).