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.
Tracked-entity quantity integrity — four fixes (C → A → B → D)
Source spec: pasted brief (ZeroFarms prod tracked-entity defects). Audited against
origin/main on 2026-09-22 — almost nothing had landed; only pre-existing building
blocks (getEdgeFunctionErrorMessage, serial-unscrap refusal, correct-stock-movement
non-negative guard, MES validator already dropped .int(), inputMode="decimal").
Order: C → A → B → D (A's pick-guards compare at scale from C; D's fractions flow through C's split path). One branch, sequential conventional commits (no AI attribution).
Spec corrections found in audit:
equals()does NOT exist inshared/precision.ts— PR C must add it.greedyFillAllocationlives inapps/mes/app/services/allocation.ts, notshared/.- No
@carbon/database/allocationexport — the MES test extendsinventory.greedy.test.ts. issue/index.tsgate sites are:1463and:4673(not 1201/4411).
PR C — round at the persist boundary fix(production): round tracked-entity quantities at the persist boundary
-
shared/precision.ts: addequals(a, b, tolerance = EPSILON). -
shared/batch-split.ts: importround; update header note; rounddraw/parentQty/remaininginbuildBatchSplitRecords(child insert, parentUpdate, both ledger rows, both activity edges, Original/Drawn/Remaining blob); guardsdraw <= 0/draw >= parentQty.buildMergeRecords: roundmergeQuantity/childRemaining; exact=== 0Consumed. -
shared/batch-merge.ts: importround; sum parents then round once; roundreceivedByBinoutputs + negative rows. -
apps/mes/app/services/allocation.ts:greedyFillAllocation—remaining = round(quantity)thenremaining = round(remaining - take). - Gate
!==→!equals(...):post-stock-transfer/index.ts:463;issue/index.tstwo sites (importequals). - Tests:
batch-split.test.ts(draw 0.98 ⇒ parentUpdate {quantity:0.02}; 0.3000…4 merge; drain→Consumed);batch-merge.test.ts(0.1+0.2⇒0.3);inventory.greedy.test.ts(pool [0.98,5], need 1 ⇒ [0.98,0.02]). - Verify:
deno task test(functions),turbo typecheck --filter=@carbon/database --filter=mes,vitest(mes), lint.
PR A — stock-transfer pick correctness fix(erp): make stock-transfer picks idempotent and lot-aware
-
inventory.models.tsstockTransferLineScanValidator:quantitypositive,storageUnitIdnullable optional. - Route
$id.scan.$lineId.tsx: forward pickerquantity+storageUnitId; action postsvalidated.data.quantity(serial 1) +storageUnitId ?? currentStorageUnitId; fully-picked pre-check;getEdgeFunctionErrorMessage. -
post-stock-transfer/: newpick-guards.ts(resolvePick,PickError); batch case.forUpdate()+ entity over-draw 400 + accumulate pickedQuantity; serial case lock + resolvePick + repeat-scan 400. - Tests:
pick-guards.test.ts(Deno);$id.scan.$lineId.test.ts(vitest).
PR B — zero/negative hygiene fix(production): stop adjustments leaving zero/negative Available lots
-
shared/entity-drain.ts:statusAfterQuantityChange. -
post-inventory-adjustment/index.ts: Consumed-on-0 on negative/set paths;signedQuantity===0new-entity no-op. -
post-inventory-count/index.ts:.forUpdate()+ THROW onqty+delta<0+ Consumed on 0. -
create/index.tsreceipt split +correct-stock-movement/index.ts: conditional Consumed. - Migration:
trackedEntity_quantity_nonnegativeCHECK ... NOT VALID. - Tests:
entity-drain.test.ts; count-guard pure fn + test.
PR D — MES Complete Batch decimals fix(mes): accept decimal quantities and surface errors in Complete Batch
-
apps/mes/app/utils/display.ts:decimalInput(SCALE truncate). -
BatchCompleteModal.tsx: usedecimalInput; field-level validation (useField/aria-invalid + message). -
models.ts: delete stale INTEGER comment;round()at parse. -
batch-operations/index.ts: drop.int(),round()members. - Tests:
display.test.tsdecimal cases;models.batch.test.tsdecimal/round cases.
Follow-up (2026-09-23) — review sweep on top of the four PRs
CodeRabbit's five findings plus a sweep of the PR head for the same defect
classes, and the shared seams the four PRs had created but not reused.
Commits: refactor(database): share the tracked-entity quantity rules as three functions, fix(inventory): round tracked-entity quantity arithmetic at every persist boundary, feat(checks): add no-unrounded-tracked-quantity conformance rule, fix(inventory): surface a pick guard's reason instead of the wrapper text.
- Shared:
pick-guards.ts→shared/;settleQuantity()inshared/entity-drain.ts(round + refuse negative + drain rule, withresolveCountedEntitydelegating);isFullDraw()inshared/batch-split.tsas the one split gate;resolvePickrefuses anempty-pick;receivedByBinrounds per parent. - Rounding + split gates:
issue(both children loops, everyquantityIssuedwrite, the dispatch-item quantity),post-picking(line locks in all seven handlers, entity lock +resolvePickin the three accumulate paths,settleQuantityfor the unpick child),post-stock-transfer(serial entity lock, split operands, unpick),post-shipment(all three split decisions),post-inventory-adjustment(three drain flips →settleQuantity),correct-stock-movement,create, ERPquality-disposition, ERPshipment+/lines.tracking.tsx. -
@carbon/checks:no-unrounded-tracked-quantity, zero findings over the current tree (no baseline entries), six over the pre-fix tree. -
db:check:datasetsskips instead of crashing whenSUPABASE_DB_URLis unset — it blocked commits in a worktree with no.env.localon "Cannot read properties of undefined (reading 'includes')".
Still open
-
VALIDATE CONSTRAINT "trackedEntity_quantity_nonnegative". The CHECK shippedNOT VALIDin20260922191138_tracked-entity-quantity-nonnegative.sqlso the existing prod husks (the ZeroFarms −20) would not fail the deploy. Nothing enforces the invariant on those historical rows until a later migration validates it. The order is: repair the negative rows in prod (a one-off script underscripts/one-off/—ci/src/migrations.tsruns those aftersupabase db pushand records them inscriptRun— or manual corrections throughcorrect-stock-movement), confirmSELECT count(*) FROM "trackedEntity" WHERE quantity < 0is 0, then add a migration withALTER TABLE "trackedEntity" VALIDATE CONSTRAINT "trackedEntity_quantity_nonnegative";(same two-step convention as20260805152353_timezone-validity-check.sql). Until then the constraint only guards NEW and UPDATED rows. - Should
Rejectedbe preserved at zero likeScrapped?statusAfterQuantityChangepreserves onlyScrapped.Rejectedis the other quality marker excluded from on-hand, andcorrect-stock-movementcan drive a Rejected lot to zero (it excludes onlyConsumed), which would flip it toConsumedand lose the disposition. Left as-is deliberately — it is a quality-semantics call, not a rounding one. -
post-picking's serial case still has no repeat-scan guard (the same serial can be scanned twice on one list;resolvePickstops it only oncequantityPickedreachesquantityToPick).post-stock-transferhas one.