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.
Plan: Picked-material return timing (job vs operation)
Spec: .ai/specs/2026-08-04-picked-material-return-timing.md
Research: .ai/research/material-staging-return-timing.md
Owed formula (final): owed = (jobMaterial.estimatedQuantity ÷ job.quantity) × op.quantityComplete
(includes scrap allowance). Op scope only; job scope owed = 0 (backflush ran first).
Tasks
T1 — Migration
packages/database/supabase/migrations/<ts>_picked-material-return-timing.sqlcompanySettings.returnPickedMaterialTiming TEXT NOT NULL DEFAULT 'job' CHECK IN ('job','operation')pickingListLine.quantityReturned NUMERIC NOT NULL DEFAULT 0backflush_job_materialsverbatim fork of20260713190909:131+ lineside clamp: after bin resolution, if bin hasworkCenterId, clamp qty toGREATEST(SUM(itemLedger.quantity) WHERE itemId/storageUnitId/locationId/companyId AND trackedEntityId IS NULL, 0);CONTINUEat ≤ 0.- Verify: SQL review. User runs
pnpm db:migrate(regenerates types). Never rebuild DB.
T2 — post-picking edge fn
packages/database/supabase/functions/post-picking/index.ts- Extract
returnTrackedAllocationRemainder(trx, ...)fromreturnPickedRemainderbody (:737-903): line update becomesquantityReturned += totalReturned(dropquantityPickeddecrement + status reset :884-900; keep allocation decrement/delete :853-882); drop unconditionalrestoreJobMaterialSource(:902) — repoint decided per material by sweep. - New
returnUntrackedMaterialRemainder(trx, ...): per-jobMaterial returnable =max(0, Σ(line.picked − line.returned) − max(quantityIssued, owed)), newest-first line allocation, per-line cap picked−returned, target binline.storageUnitId→ pickMethod default → NULL; untracked transfer pairs (hand-built inserts, transferPair requires trackedEntityId); incrementquantityReturned. - New cases
returnOperationRemainders {jobOperationId,userId,companyId}(readsreturnPickedMaterialTiming, no-op on 'job'; owed per formula; lines WHERE jobOperationId=op, line status ≠ Cancelled, list not Draft/Cancelled) andreturnJobRemainders {jobId,userId,companyId}(guard job.status='Completed'; owed=0; all non-Cancelled lines incl. NULL-op). Both derive locationId from job; conditional repoint: job scope always restore; op scope restore only when net lineside ≤ 0. - Keep legacy
returnPickedRemaindercase as wrapper. - Verify:
pnpm run lint.
- Extract
T3 — MES wiring
apps/mes/app/services/operations.service.ts: replacereturnAllocatedRemaindersAtJobComplete(:213-277) withreturnPickedRemainders: read op.jobId + job.status → Completed ?returnJobRemainders:returnOperationRemainders; keep log-on-error.finishJobOperation:195call unchanged.apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx: after postings succeed, re-read op status; if 'Done' →returnPickedRemainders(serviceRole, ...).- Verify:
pnpm exec turbo run typecheck --filter=mes(post-migrate),pnpm run lint.
T4 — ERP wiring
production.service.ts: addreturnPickedRemainders(op) +returnPickedJobRemainders(job) helpers, barrel export.x+/job+/methods+/operation.status.tsx: after update success, status==='Done' → op sweep viagetCarbonServiceRole().x+/job+/$jobId.complete.tsx: after RPC success → job sweep; failure = warning flash, completion stands (sweep idempotent).$jobId.status.tsxdirect-Completed bypass: comment only.- Verify:
pnpm exec turbo run typecheck --filter=erp(post-migrate),pnpm run lint.
T5 — Settings surface (ERP)
settings.models.ts:returnPickedMaterialTimings = ["job","operation"] as const+ validator.settings.service.ts:updateReturnPickedMaterialTimingSetting.x+/settings+/inventory.tsx: intent case + ChoiceSelect card (incompletePickingListPolicy pattern).pnpm lingui:extractafter.- Verify: typecheck erp (post-migrate), lint.
T6 — Net-picked consumers
- MES
getPickedQuantitiesByJobMaterial(inventory.service.ts:363): exposequantityReturned; staged-at-lineside math uses picked − returned. - Optional ERP PickingListLines "Returned" column.
- MES
T7 — Docs/rules sync
.claude/rules/traceability-model.md(pick→consume→return paragraph),.claude/rules/inventory-system.md,.ai/lessons.mdentry (quantityPicked decrement trips status trigger — use quantityReturned for returns).
Gate (after user runs pnpm db:migrate)
pnpm exec turbo run typecheck --filter=@carbon/database --filter=erp --filter=mes
pnpm run lint
Manual /test: pick → partial issue → op Done under 'operation' → remainder returned,
header stays Completed → complete job → backflush clamped + final sweep + storageUnitId restored.
Risks (accepted)
- Untracked newest-first allocation is bookkeeping, not physical truth.
- Op un-Done after sweep: not reversed; re-pick.
- Crash between completion and sweep: strands until re-invoke (idempotent) — same as today.
- Deploy edge fn before app (legacy case kept for skew).