Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

7.5 KB
Raw Blame

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 in shared/precision.ts — PR C must add it.
  • greedyFillAllocation lives in apps/mes/app/services/allocation.ts, not shared/.
  • No @carbon/database/allocation export — the MES test extends inventory.greedy.test.ts.
  • issue/index.ts gate sites are :1463 and :4673 (not 1201/4411).

PR C — round at the persist boundary fix(production): round tracked-entity quantities at the persist boundary

  • shared/precision.ts: add equals(a, b, tolerance = EPSILON).
  • shared/batch-split.ts: import round; update header note; round draw/parentQty/remaining in buildBatchSplitRecords (child insert, parentUpdate, both ledger rows, both activity edges, Original/Drawn/Remaining blob); guards draw <= 0/draw >= parentQty. buildMergeRecords: round mergeQuantity/childRemaining; exact === 0 Consumed.
  • shared/batch-merge.ts: import round; sum parents then round once; round receivedByBin outputs + negative rows.
  • apps/mes/app/services/allocation.ts: greedyFillAllocation — remaining = round(quantity) then remaining = round(remaining - take).
  • Gate !== → !equals(...): post-stock-transfer/index.ts:463; issue/index.ts two sites (import equals).
  • 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.ts stockTransferLineScanValidator: quantity positive, storageUnitId nullable optional.
  • Route $id.scan.$lineId.tsx: forward picker quantity+storageUnitId; action posts validated.data.quantity (serial 1) + storageUnitId ?? currentStorageUnitId; fully-picked pre-check; getEdgeFunctionErrorMessage.
  • post-stock-transfer/: new pick-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===0 new-entity no-op.
  • post-inventory-count/index.ts: .forUpdate() + THROW on qty+delta<0 + Consumed on 0.
  • create/index.ts receipt split + correct-stock-movement/index.ts: conditional Consumed.
  • Migration: trackedEntity_quantity_nonnegative CHECK ... 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: use decimalInput; 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.ts decimal cases; models.batch.test.ts decimal/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() in shared/entity-drain.ts (round + refuse negative + drain rule, with resolveCountedEntity delegating); isFullDraw() in shared/batch-split.ts as the one split gate; resolvePick refuses an empty-pick; receivedByBin rounds per parent.
  • Rounding + split gates: issue (both children loops, every quantityIssued write, the dispatch-item quantity), post-picking (line locks in all seven handlers, entity lock + resolvePick in the three accumulate paths, settleQuantity for 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, ERP quality-disposition, ERP shipment+/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:datasets skips instead of crashing when SUPABASE_DB_URL is unset — it blocked commits in a worktree with no .env.local on "Cannot read properties of undefined (reading 'includes')".

Still open

  • VALIDATE CONSTRAINT "trackedEntity_quantity_nonnegative". The CHECK shipped NOT VALID in 20260922191138_tracked-entity-quantity-nonnegative.sql so 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 under scripts/one-off/ — ci/src/migrations.ts runs those after supabase db push and records them in scriptRun — or manual corrections through correct-stock-movement), confirm SELECT count(*) FROM "trackedEntity" WHERE quantity < 0 is 0, then add a migration with ALTER TABLE "trackedEntity" VALIDATE CONSTRAINT "trackedEntity_quantity_nonnegative"; (same two-step convention as 20260805152353_timezone-validity-check.sql). Until then the constraint only guards NEW and UPDATED rows.
  • Should Rejected be preserved at zero like Scrapped? statusAfterQuantityChange preserves only Scrapped. Rejected is the other quality marker excluded from on-hand, and correct-stock-movement can drive a Rejected lot to zero (it excludes only Consumed), which would flip it to Consumed and 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; resolvePick stops it only once quantityPicked reaches quantityToPick). post-stock-transfer has one.