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.

Fix tracked-entity quantity integrity (rounding, picks, zero-hygiene, decimals) (#1709)

Brad Barbin6173be926851
diff --git a/.ai/plans/2026-09-22-tracked-entity-quantity-integrity.md b/.ai/plans/2026-09-22-tracked-entity-quantity-integrity.md
new file mode 100644
index 0000000000..3273d3155e
--- /dev/null
+++ b/.ai/plans/2026-09-22-tracked-entity-quantity-integrity.md
@@ -0,0 +1,107 @@
+# 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`
+
+- [x] `shared/precision.ts`: add `equals(a, b, tolerance = EPSILON)`.
+- [x] `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.
+- [x] `shared/batch-merge.ts`: import `round`; sum parents then round once; round `receivedByBin` outputs + negative rows.
+- [x] `apps/mes/app/services/allocation.ts`: `greedyFillAllocation` — `remaining = round(quantity)` then `remaining = round(remaining - take)`.
+- [x] Gate `!==` → `!equals(...)`: `post-stock-transfer/index.ts:463`; `issue/index.ts` two sites (import `equals`).
+- [x] 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]).
+- [x] 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`
+
+- [x] `inventory.models.ts` `stockTransferLineScanValidator`: `quantity` positive, `storageUnitId` nullable optional.
+- [x] Route `$id.scan.$lineId.tsx`: forward picker `quantity`+`storageUnitId`; action posts `validated.data.quantity` (serial 1) + `storageUnitId ?? currentStorageUnitId`; fully-picked pre-check; `getEdgeFunctionErrorMessage`.
+- [x] `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.
+- [x] 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`
+
+- [x] `shared/entity-drain.ts`: `statusAfterQuantityChange`.
+- [x] `post-inventory-adjustment/index.ts`: Consumed-on-0 on negative/set paths; `signedQuantity===0` new-entity no-op.
+- [x] `post-inventory-count/index.ts`: `.forUpdate()` + THROW on `qty+delta<0` + Consumed on 0.
+- [x] `create/index.ts` receipt split + `correct-stock-movement/index.ts`: conditional Consumed.
+- [x] Migration: `trackedEntity_quantity_nonnegative` CHECK ... NOT VALID.
+- [x] 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`
+
+- [x] `apps/mes/app/utils/display.ts`: `decimalInput` (SCALE truncate).
+- [x] `BatchCompleteModal.tsx`: use `decimalInput`; field-level validation (`useField`/aria-invalid + message).
+- [x] `models.ts`: delete stale INTEGER comment; `round()` at parse.
+- [x] `batch-operations/index.ts`: drop `.int()`, `round()` members.
+- [x] 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`.
+
+- [x] 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.
+- [x] 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`.
+- [x] `@carbon/checks`: `no-unrounded-tracked-quantity`, zero findings over the
+ current tree (no baseline entries), six over the pre-fix tree.
+- [x] `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.
diff --git a/.ai/playbooks/inventory-adjustment-decimal-batch.md b/.ai/playbooks/inventory-adjustment-decimal-batch.md
new file mode 100644
index 0000000000..f8f41bf037
--- /dev/null
+++ b/.ai/playbooks/inventory-adjustment-decimal-batch.md
@@ -0,0 +1,61 @@
+# Inventory Adjustment — decimal quantities on a batch-tracked item
+
+Last tested: 2026-09-23
+Route: `/x/inventory/quantities/<itemId>/details` → "Update Inventory" drawer
+
+## Prerequisites
+- A **batch-tracked** item with a fractional UoM (e.g. `MAT-AL7075-PLT`,
+ `item_JGJDAeYjKqVoJicSCPT8bF`, UoM POUND, in Carbon Development).
+- A storage unit to hold stock (e.g. `A2-L1`).
+- Edge functions healthy (`post-inventory-adjustment` hot).
+
+## Steps
+
+### 1. Open the drawer
+- Item detail page → **Update Inventory** button. A drawer form opens.
+- Fields (by input `name`): `storageUnitId` (combobox), `adjustmentType`
+ (combobox: Set Quantity | Positive Adjustment | Negative Adjustment | Scrap),
+ `readableId` (Batch Number, **free text**), `quantity` (react-aria number),
+ `scrapReasonId` (only when type=Scrap).
+
+### 2. Positive decimal adjustment (creates a lot)
+- Adjustment Type → **Positive Adjustment**.
+- Storage Unit → `A2-L1` (open combobox, filter, click the option).
+- Batch Number → type a NEW value, e.g. `DEC-TEST-A` (free text mints a fresh
+ `trackedEntityId` → a new entity is created).
+- Quantity → `2.5`, then **blur** (click another field) — the react-aria hidden
+ input commits on blur; verify `input[name=quantity].value === "2.5"`.
+- Submit by calling `requestSubmit` on the drawer's FORM, passing the Save
+ button as the submitter — `form.requestSubmit(saveButton)` (or bare
+ `form.requestSubmit()`). `requestSubmit` is a form method, not a button
+ method, and a plain click on Save does nothing.
+- Verify: Quantity on Hand rises by 2.5 (e.g. 60 → 62.5); storage-unit table
+ shows `A2-L1 | 2.5 | <batch>`.
+
+### 3. Negative decimal drain to zero (drain path → Consumed)
+- Adjustment Type → **Negative Adjustment**, Storage Unit → `A2-L1`.
+- Batch Number → the existing lot's readableId (e.g. `DEC-TEST-A`). The negative
+ path resolves the entity BY `readableId`, so free text is fine here.
+- Quantity → the full remaining (e.g. `2.5`). Submit.
+- Verify: on-hand returns to the pre-test value; the lot disappears from the
+ on-hand table; in `/x/inventory/tracked-entities?search=<batch>` the entity
+ shows **quantity 0, status CONSUMED** (NOT a 0-qty Available husk).
+
+## Selector Notes
+- Comboboxes are custom: click to expand, `fill` the inner search combobox, then
+ click the option. Refs shift after each selection (a "Clear" button appears) —
+ re-`snapshot` before the next field.
+- Read committed state via `input[name=...].value` inside `[role=dialog]`, never
+ the visible text.
+- Right after the drawer opens, the first combobox click can time out (open
+ animation) — `sleep 2` and retry once.
+
+## Common Failures
+- **Scrap of an EXISTING batch does not post.** The batch field is free text and
+ mints a NEW `trackedEntityId`; the Scrap path resolves the entity by that id,
+ so it 400s "Tracked entity not found" against the new id and the real lot is
+ untouched. Scrapping an existing lot must be driven from a surface that passes
+ the real entity id (not this drawer's free-text batch field). This is a
+ form/harness limitation, not an edge-function bug.
+- A submit that does nothing → you clicked Save instead of `requestSubmit`, or a
+ react-aria number field never blurred (hidden `quantity` still stale).
diff --git a/.ai/playbooks/stock-transfer-decimal-batch-split.md b/.ai/playbooks/stock-transfer-decimal-batch-split.md
new file mode 100644
index 0000000000..240f7c6895
--- /dev/null
+++ b/.ai/playbooks/stock-transfer-decimal-batch-split.md
@@ -0,0 +1,60 @@
+# Stock Transfer — decimal batch pick (identity-flip split)
+
+Last tested: 2026-09-23
+Route: `/x/inventory/stock-transfers` → transfer → `/x/stock-transfer/<id>/scan/<lineId>`
+
+## Prerequisites
+- A **batch-tracked** item with a fractional UoM (e.g. `MAT-AL7075-PLT`) and an
+ **Available batch lot** with more on-hand than you intend to pick (partial draw
+ is what triggers the split). Create one via a positive inventory adjustment,
+ e.g. lot `XFER-DEC` = 5.5 lb at `A2-L1` (see
+ `inventory-adjustment-decimal-batch.md`).
+- Two storage units in the location (source `A2-L1`, destination `A2-L2`).
+
+## Steps
+
+### 1. Create the transfer with a controllable decimal line
+- The **"Add Stock Transfer"** wizard is demand-driven: its only destinations
+ are bins/locations that already NEED stock, and it creates the transfer as
+ **Released** (non-editable). This makes a clean bin→bin decimal line hard.
+- Reliable path: create ANY transfer via the wizard (pick the demand row as
+ destination, add a source, Create Transfer), then on the transfer page
+ **More options → Reopen** (→ Draft). Reopen reveals **Add Line**.
+- **Add Line**: Item = the batch item; Quantity = your decimal (e.g. `2.25`);
+ From Storage Unit = `A2-L1`; To Storage Unit = `A2-L2`. Save.
+ - The From/To storage-unit dropdown options are rendered in a portal and may
+ NOT appear in `snapshot -i`; read/click them via
+ `document.querySelectorAll('[role=option],[cmdk-item]')`.
+- Re-**Release** (button enabled once a line exists). Release/Complete disabled +
+ no "Add Line" ⇒ it's Released.
+
+### 2. Pick the lot (partial → split)
+- Click the line's **Pick** button (native agent-browser `click @ref`; a
+ synthetic `.click()` may not fire the React navigate). It opens the scan route
+ `.../scan/<lineId>` as a `TrackedEntityPicker` modal.
+- **Select** tab → the lot shows "`XFER-DEC` · N available · A2-L1" with a Pick
+ button. Click it. The picker submits `min(lineQty − pickedQty, lotAvailable)` —
+ here `min(2.25, 5.5) = 2.25`, a PARTIAL of the lot.
+- Success toast: **"Tracked entity scanned and transferred"**.
+
+### 3. Verify the split
+- Item detail storage-unit table shows the lot split across bins:
+ `A2-L1 | 3.25 | XFER-DEC` (parent kept its id, decremented) and
+ `A2-L2 | 2.25 | XFER-DEC` (new child at the destination). Sum = original 5.5.
+- `/x/inventory/tracked-entities?search=XFER-DEC` shows **2 rows, both AVAILABLE**:
+ `2.25` (child) and `3.25` (parent). All clean decimals — no float residue, no
+ Consumed husk. This is the identity-flip split with `buildBatchSplitRecords`
+ rounding at the persist boundary + the `isFullDraw` gate.
+
+## Common Failures
+- **Empty transfer after the wizard.** The wizard's only destination for the item
+ was "No storage unit" (null bin); the header is created but no usable line.
+ Reopen → Add Line as above.
+- **Pick button "does nothing".** Use agent-browser's native `click @ref`, not a
+ DOM `.click()` — the button navigates via React Router.
+- If the draw covers the whole lot it's a FULL draw (no split). The draw is
+ `min(lineQty − pickedQty, lotAvailable)`, so the test is
+ `lineQty − pickedQty ≥ lotAvailable` — the line TOTAL is not the right
+ comparison once something has already been picked (`lineQty=2.25`,
+ `pickedQty=1`, `lotAvailable=2` is a partial draw of `1.25`). To force a
+ split, keep the line's REMAINING quantity below the lot's available.
diff --git a/.claude/rules/traceability-model.md b/.claude/rules/traceability-model.md
index 82a09218b8..3504a0f678 100644
--- a/.claude/rules/traceability-model.md
+++ b/.claude/rules/traceability-model.md
@@ -1,6 +1,7 @@
---
paths:
- "packages/database/supabase/migrations/*tracked*.sql"
+ - "packages/database/supabase/functions/shared/{batch-split,batch-merge,entity-drain,pick-guards}.ts"
- "apps/erp/app/modules/inventory/{lineage.server,inventory.service,types}.ts"
- "apps/erp/app/routes/x+/traceability+/**"
- "apps/mes/app/services/operations.service.ts"
@@ -199,6 +200,76 @@ per jobMaterial:
sweep (the lineside bin is shared per work center). Spec:
`.ai/specs/2026-08-04-picked-material-return-timing.md`.
+## Quantity integrity — the four invariants
+
+`trackedEntity.quantity` is a bare NUMERIC (no declared scale, per the DB
+conventions), so whatever float a writer hands it is what gets stored. A lot
+left holding `0.020000000000000018` after an earlier split reads "0.02" in every
+UI and behaves like 0.02 nowhere. Four rules follow, and they are shared code
+rather than convention because inlining them is how they drifted apart.
+
+**1. Round at the persist boundary.** Every write that moves a quantity rounds
+at internal scale (`round` from `functions/shared/precision.ts`, re-exported
+through `@carbon/utils` for Node). The whole settle is
+`settleQuantity({ quantity, status, refusal? })` in
+`functions/shared/entity-drain.ts` — round, refuse a negative result, then apply
+rule 2 — and it takes the SETTLED figure, not a delta, so one signature serves
+the count path (snapshot delta) and the adjustment/unpick paths alike.
+`resolveCountedEntity` (post-inventory-count) is a thin wrapper that supplies
+its own recount message. Callers: `post-inventory-adjustment` (three drain
+paths), `post-inventory-count`, `create` (receipt split), `post-picking`
+(unpick child).
+
+**2. A drained lot is Consumed, not a husk.** `statusAfterQuantityChange`
+(same file) flips a lot that rounds to zero to `Consumed` — but a `Scrapped`
+lot stays `Scrapped` at zero, because it is a historical record and Unscrap is
+the only way back. **`Rejected` is NOT preserved today**; it is the other
+quality marker excluded from on-hand, and `correct-stock-movement` (which
+excludes only `Consumed`) can drive one to zero. Whether it should be preserved
+is an open question, not an oversight — see
+`.ai/plans/2026-09-22-tracked-entity-quantity-integrity.md`.
+
+**3. One split gate.** `isFullDraw(entityQuantity, drawQuantity)` in
+`functions/shared/batch-split.ts` (`equals` on both rounded values) is how every
+writer decides split-or-take-whole, so a caller's decision and
+`buildBatchSplitRecords`' own refusals (`draw <= 0`, `draw >= parentQty`) can
+never disagree. A raw `===`/`<` on two stored floats can: a residue lot drawn for its
+own 0.02 read as PARTIAL, and the builder then threw `draw >= parentQty` as a
+500 on what the operator saw as a legitimate full pick — or minted a child
+entity holding 1.8e-17. Callers: `issue` (both children loops), `post-picking`,
+`post-stock-transfer`, `post-shipment` (all three split decisions, including an
+ad-hoc `draw + 0.00001 >= entityQty` epsilon that predated the helper),
+`post-inventory-adjustment` (partial scrap). A full draw also books the LOT's
+own rounded quantity, not the requested figure — the entity is flipped
+`Consumed` without its quantity being rewritten, so the ledger row has to agree
+with the lot it just emptied.
+
+**4. A pick accumulates under a lock.** `resolvePick` in
+`functions/shared/pick-guards.ts` returns the NEW running total (never a
+replacement) or throws a typed `PickGuardError` — `already-picked`,
+`over-pick`, or `empty-pick` (a quantity that rounds to zero). The caller turns
+it into a **400**, never a 500, and both apps read the reason out of the
+response BODY (`getEdgeFunctionErrorMessage` in the ERP,
+`getPostPickingErrorMessage` in MES) because supabase-js's own
+`FunctionsHttpError.message` is always the fixed "Edge Function returned a
+non-2xx status code". It is only correct under a row lock: `post-picking` locks
+the `pickingListLine` in every handler and the source lot in the batch pick,
+`post-stock-transfer` locks the line plus the entity (and, in the serial case,
+the entity BEFORE its repeat-scan guard — two concurrent scans would otherwise
+both read "not on this transfer" and both post a Transfer pair).
+`resolveStockTransferPickForward` (`inventory.models.ts`) is the route-side
+pre-check that mirrors the same rounding so the two cannot disagree; the lock
+is what makes the edge function authoritative.
+
+The DB backstop is `trackedEntity_quantity_nonnegative`
+(`20260922191138_tracked-entity-quantity-nonnegative.sql`), a CHECK added
+**`NOT VALID`** so existing negative prod rows would not fail the deploy — so it
+guards new and updated rows only until a later migration `VALIDATE`s it. The
+static backstop is the `no-unrounded-tracked-quantity` conformance rule in
+`@carbon/checks`, which flags inline unrounded arithmetic in a
+`.updateTable("trackedEntity")` quantity set and a raw compare against a
+quantity read straight off a row. It has no baseline entries.
+
**Gotcha:** the older `get_item_quantities_by_tracking_id` (`20260101163400`) still emits
legacy `shelfId` / `shelfName` and joins the `shelf` table — both column sets exist; check
which RPC you are calling.
diff --git a/apps/erp/app/modules/inventory/inventory.models.test.ts b/apps/erp/app/modules/inventory/inventory.models.test.ts
index 5e27607ad5..573b802d11 100644
--- a/apps/erp/app/modules/inventory/inventory.models.test.ts
+++ b/apps/erp/app/modules/inventory/inventory.models.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from "vitest";
-import { storageTypeValidator, storageUnitValidator } from "./inventory.models";
+import {
+ resolveStockTransferPickForward,
+ storageTypeValidator,
+ storageUnitValidator
+} from "./inventory.models";
describe("storageTypeValidator", () => {
it("trims surrounding whitespace from the name", () => {
@@ -32,3 +36,95 @@ describe("storageUnitValidator", () => {
expect(r.success).toBe(false);
});
});
+
+describe("resolveStockTransferPickForward", () => {
+ const base = {
+ storageUnitId: "bin-chosen" as string | null,
+ currentStorageUnitId: "bin-default" as string | null,
+ lineQuantity: 10,
+ pickedQuantity: 0
+ };
+
+ it("forwards the picker quantity and chosen bin for a batch scan", () => {
+ const r = resolveStockTransferPickForward({
+ ...base,
+ transferType: "batch",
+ quantity: 3
+ });
+ expect(r).toEqual({
+ ok: true,
+ quantity: 3,
+ fromStorageUnitId: "bin-chosen"
+ });
+ });
+
+ it("posts quantity 1 for a serial scan regardless of the picker quantity", () => {
+ const r = resolveStockTransferPickForward({
+ ...base,
+ transferType: "serial",
+ quantity: 4
+ });
+ expect(r).toEqual({
+ ok: true,
+ quantity: 1,
+ fromStorageUnitId: "bin-chosen"
+ });
+ });
+
+ it("falls back to the highest-quantity bin when the picker sends none", () => {
+ const r = resolveStockTransferPickForward({
+ ...base,
+ transferType: "batch",
+ quantity: 3,
+ storageUnitId: null
+ });
+ expect(r.ok && r.fromStorageUnitId).toBe("bin-default");
+ });
+
+ it("refuses a pick on a fully-picked line", () => {
+ const r = resolveStockTransferPickForward({
+ ...base,
+ transferType: "batch",
+ quantity: 1,
+ pickedQuantity: 10
+ });
+ expect(r).toEqual({
+ ok: false,
+ message: "This line is already fully picked"
+ });
+ });
+
+ it("names the outstanding quantity when a batch pick exceeds it", () => {
+ // Not "already fully picked" — there are 5 left, the operator asked for 8.
+ const r = resolveStockTransferPickForward({
+ ...base,
+ transferType: "batch",
+ quantity: 8,
+ pickedQuantity: 5
+ });
+ expect(r).toEqual({
+ ok: false,
+ message: "Only 5 left to pick on this line"
+ });
+ });
+
+ it("refuses a batch pick that rounds to nothing", () => {
+ const r = resolveStockTransferPickForward({
+ ...base,
+ transferType: "batch",
+ quantity: 0.000001
+ });
+ expect(r).toEqual({ ok: false, message: "Enter a quantity to pick" });
+ });
+
+ it("allows an equal-at-scale full pick (0.98 + 0.02)", () => {
+ const r = resolveStockTransferPickForward({
+ ...base,
+ transferType: "batch",
+ quantity: 1 - 0.98,
+ lineQuantity: 1,
+ pickedQuantity: 0.98
+ });
+ expect(r.ok).toBe(true);
+ });
+});
diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.ts
index 414bc66015..bbe4c53f07 100644
--- a/apps/erp/app/modules/inventory/inventory.models.ts
+++ b/apps/erp/app/modules/inventory/inventory.models.ts
@@ -1,8 +1,10 @@
import {
conditionAstFormField,
+ equals,
getFieldDef,
isFieldAvailableOnSurfaces,
RULE_SEVERITIES,
+ round,
SURFACES_BY_TARGET_TYPE,
TARGET_TYPES,
TRANSACTION_SURFACES
@@ -579,9 +581,65 @@ export const stockTransferLineScanValidator = z.object({
stockTransferId: z.string().min(1, { message: "Stock transfer is required" }),
trackedEntityId: z
.string()
- .min(1, { message: "Tracked entity ID is required" })
+ .min(1, { message: "Tracked entity ID is required" }),
+ // The picker sends the clamped pick quantity and the bin the user chose; the
+ // action forwards both to the edge function (serial always posts 1).
+ quantity: z.number().positive({ message: "Quantity must be greater than 0" }),
+ storageUnitId: z.string().nullable().optional()
});
+/**
+ * Decide what a stock-transfer scan forwards to the post-stock-transfer edge
+ * function, or refuse the pick before invoking it. Pure so the route's parsing
+ * is testable without the edge function or the client graph — the edge function
+ * re-checks the same limits under a row lock (see post-stock-transfer/pick-guards).
+ * - A serial scan always moves one unit; a batch scan moves the picker's
+ * clamped quantity.
+ * - The bin the user chose wins; the highest-quantity bin is only a fallback.
+ * - A line with no outstanding quantity (or a pick that exceeds it) is refused.
+ */
+export function resolveStockTransferPickForward(input: {
+ transferType: "batch" | "serial";
+ quantity: number;
+ storageUnitId: string | null | undefined;
+ currentStorageUnitId: string | null;
+ lineQuantity: number;
+ pickedQuantity: number;
+}):
+ | { ok: true; quantity: number; fromStorageUnitId: string | null }
+ | { ok: false; message: string } {
+ // Round like the edge function's resolvePick does, so the pre-check and the
+ // post-lock re-check cannot disagree about a residue pick.
+ const pickQuantity = round(
+ input.transferType === "batch" ? input.quantity : 1
+ );
+ const outstanding = round(
+ round(input.lineQuantity) - round(input.pickedQuantity)
+ );
+ // Checked first, matching resolvePick's order, so the pre-check and the
+ // edge function name the same refusal for the same input.
+ if (pickQuantity <= 0) {
+ return { ok: false, message: "Enter a quantity to pick" };
+ }
+ if (equals(outstanding, 0) || outstanding < 0) {
+ return { ok: false, message: "This line is already fully picked" };
+ }
+ // Two different refusals: nothing left to pick, versus more than is left.
+ // One message for both told an operator with 2 outstanding that the line was
+ // fully picked.
+ if (!equals(pickQuantity, outstanding) && pickQuantity > outstanding) {
+ return {
+ ok: false,
+ message: `Only ${outstanding} left to pick on this line`
+ };
+ }
+ return {
+ ok: true,
+ quantity: pickQuantity,
+ fromStorageUnitId: input.storageUnitId ?? input.currentStorageUnitId
+ };
+}
+
export const pickingListStatusType = [
"Draft",
"In Progress",
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 2185979214..01d4b3f23a 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -3020,19 +3020,13 @@ export async function setPickingListLineTrackedEntity(
const result = await client.functions.invoke("post-picking", { body });
if (result.error) {
- const ctx = (result.error as { context?: Response })?.context;
- let message = "Failed to pick material";
- if (ctx && typeof ctx.json === "function") {
- try {
- const parsed = await ctx.clone().json();
- if (parsed?.message) message = parsed.message;
- } catch {
- /* fall through */
- }
- } else if ((result.error as { message?: string }).message) {
- message = (result.error as { message: string }).message;
- }
- return { data: null, error: message };
+ return {
+ data: null,
+ error: await getEdgeFunctionErrorMessage(
+ result.error,
+ "Failed to pick material"
+ )
+ };
}
return { data: { id: args.pickingListLineId }, error: null };
@@ -4027,19 +4021,13 @@ export async function pickPickingListLine(
const result = await client.functions.invoke("post-picking", { body });
if (result.error) {
- const ctx = (result.error as { context?: Response })?.context;
- let message = "Failed to pick material";
- if (ctx && typeof ctx.json === "function") {
- try {
- const parsed = await ctx.clone().json();
- if (parsed?.message) message = parsed.message;
- } catch {
- /* fall through */
- }
- } else if ((result.error as { message?: string }).message) {
- message = (result.error as { message: string }).message;
- }
- return { data: null, error: message };
+ return {
+ data: null,
+ error: await getEdgeFunctionErrorMessage(
+ result.error,
+ "Failed to pick material"
+ )
+ };
}
}
diff --git a/apps/erp/app/modules/quality/quality-disposition.server.ts b/apps/erp/app/modules/quality/quality-disposition.server.ts
index c55aa183eb..4643275d4a 100644
--- a/apps/erp/app/modules/quality/quality-disposition.server.ts
+++ b/apps/erp/app/modules/quality/quality-disposition.server.ts
@@ -91,13 +91,17 @@ export async function assignEntitiesToIssueItem(args: {
.where("companyId", "=", companyId)
.execute();
- const existingQty = existingLinks.reduce(
- (acc, l) => acc + Number(l.quantity ?? 0),
- 0
+ // Round PER LINK, then round the sum: each link quantity is itself a
+ // persisted value, so the row totals below must net exactly against the
+ // link rows rather than against their raw float sum.
+ const existingQty = round(
+ existingLinks.reduce(
+ (acc, l) => acc + round(Number(l.quantity ?? 0)),
+ 0
+ )
);
- const movingQty = assignments.reduce(
- (acc, a) => acc + Number(a.quantity),
- 0
+ const movingQty = round(
+ assignments.reduce((acc, a) => acc + round(Number(a.quantity)), 0)
);
await trx
@@ -114,7 +118,7 @@ export async function assignEntitiesToIssueItem(args: {
nonConformanceItemId: targetItemId,
nonConformanceId: target.nonConformanceId,
trackedEntityId: a.trackedEntityId,
- quantity: Number(a.quantity),
+ quantity: round(Number(a.quantity)),
companyId,
createdBy: userId
}))
@@ -124,7 +128,10 @@ export async function assignEntitiesToIssueItem(args: {
await trx
.updateTable("nonConformanceItem")
.set({
- quantity: Math.max(0, Number(source.quantity ?? 0) - existingQty),
+ quantity: Math.max(
+ 0,
+ round(round(Number(source.quantity ?? 0)) - existingQty)
+ ),
updatedBy: userId,
updatedAt: nowIso
})
@@ -135,7 +142,7 @@ export async function assignEntitiesToIssueItem(args: {
await trx
.updateTable("nonConformanceItem")
.set({
- quantity: Number(target.quantity ?? 0) + movingQty,
+ quantity: round(round(Number(target.quantity ?? 0)) + movingQty),
updatedBy: userId,
updatedAt: nowIso
})
@@ -338,18 +345,18 @@ export async function linkEntitiesToIssueItemRow(
nonConformanceItemId: row.id,
nonConformanceId,
trackedEntityId: e.id,
- quantity: e.quantity,
+ quantity: round(e.quantity),
companyId,
createdBy: userId
}))
)
.execute();
- const addedQty = toLink.reduce((acc, e) => acc + e.quantity, 0);
+ const addedQty = round(toLink.reduce((acc, e) => acc + round(e.quantity), 0));
await trx
.updateTable("nonConformanceItem")
.set({
- quantity: currentQty + addedQty,
+ quantity: round(round(currentQty) + addedQty),
updatedBy: userId,
updatedAt: nowIso
})
@@ -367,7 +374,8 @@ export async function linkEntitiesToIssueItemRow(
// Physically subdivides a batch tracked entity, mirroring the MES issue split:
// creates a new lot for `moveQty` linked to `newRowId`, decrements the original
-// lot to `keepQty` (kept on its existing row), and writes split genealogy
+// lot to the builder's remaining quantity (kept on its existing row), and
+// writes split genealogy
// (trackedActivity "Split" + input/output + net-zero "Batch Split" itemLedger,
// which leaves on-hand unchanged).
//
@@ -429,7 +437,6 @@ async function subdivideBatchEntity(
locationId: string | null;
entityQty: number;
moveQty: number;
- keepQty: number;
companyId: string;
userId: string;
nowIso: string;
@@ -445,7 +452,6 @@ async function subdivideBatchEntity(
locationId,
entityQty,
moveQty,
- keepQty,
companyId,
userId,
nowIso
@@ -504,17 +510,23 @@ async function subdivideBatchEntity(
.execute();
// The retained lot is only decremented — no pointer is written on it; the
- // child carries "Split From Entity ID" instead.
+ // child carries "Split From Entity ID" instead. The remaining quantity comes
+ // from the builder (rounded at the persist boundary), never from a separately
+ // derived entityQty − moveQty that could round differently.
await trx
.updateTable("trackedEntity")
- .set({ quantity: keepQty })
+ .set(split.parentUpdate)
.where("id", "=", source.id)
.where("companyId", "=", companyId)
.execute();
await trx
.updateTable("nonConformanceItemTrackedEntity")
- .set({ quantity: keepQty, updatedBy: userId, updatedAt: nowIso })
+ .set({
+ quantity: split.parentUpdate.quantity,
+ updatedBy: userId,
+ updatedAt: nowIso
+ })
.where("id", "=", linkId)
.where("companyId", "=", companyId)
.execute();
@@ -525,7 +537,7 @@ async function subdivideBatchEntity(
nonConformanceItemId: newRowId,
nonConformanceId,
trackedEntityId: newEntityId,
- quantity: moveQty,
+ quantity: split.childEntityInsert.quantity,
companyId,
createdBy: userId
})
@@ -644,9 +656,13 @@ export async function splitIssueItem(args: {
// (e.g. scrap N, use-as-is the rest). Create a new Pending row for the
// split-off quantity and shrink the original — no entity subdivision.
if (links.length === 0) {
- const current = Number(item.quantity ?? 0);
- const splitQty =
- typeof splitQuantity === "number" ? splitQuantity : NaN;
+ // Compare at the SAME scale the writes below persist at. Raw operands
+ // let a 0.999996 split of a 1 pass this gate and then round to a full
+ // draw: the new row takes 1 and the original is set to 0.
+ const current = round(Number(item.quantity ?? 0));
+ const splitQty = round(
+ typeof splitQuantity === "number" ? splitQuantity : NaN
+ );
if (!(splitQty > 0)) {
throw new Error("Missing split parameters");
}
@@ -661,7 +677,7 @@ export async function splitIssueItem(args: {
.values({
nonConformanceId: item.nonConformanceId,
itemId: item.itemId,
- quantity: splitQty,
+ quantity: round(splitQty),
disposition: "Pending",
companyId,
createdBy: userId
@@ -672,7 +688,7 @@ export async function splitIssueItem(args: {
await trx
.updateTable("nonConformanceItem")
.set({
- quantity: current - splitQty,
+ quantity: round(round(current) - round(splitQty)),
updatedBy: userId,
updatedAt: nowIso
})
@@ -725,8 +741,10 @@ export async function splitIssueItem(args: {
throw new Error("Missing split parameters");
}
- const effectiveSplitQty = moves.reduce((acc, m) => acc + m.moveQty, 0);
- const current = Number(item.quantity ?? 0);
+ const effectiveSplitQty = round(
+ moves.reduce((acc, m) => acc + round(m.moveQty), 0)
+ );
+ const current = round(Number(item.quantity ?? 0));
if (effectiveSplitQty >= current) {
throw new Error(
`Split quantity (${effectiveSplitQty}) must be less than the current quantity (${current})`
@@ -784,7 +802,6 @@ export async function splitIssueItem(args: {
locationId,
entityQty,
moveQty,
- keepQty: entityQty - moveQty,
companyId,
userId,
nowIso
@@ -795,7 +812,7 @@ export async function splitIssueItem(args: {
await trx
.updateTable("nonConformanceItem")
.set({
- quantity: current - effectiveSplitQty,
+ quantity: round(round(current) - effectiveSplitQty),
updatedBy: userId,
updatedAt: nowIso
})
diff --git a/apps/erp/app/routes/x+/shipment+/lines.tracking.tsx b/apps/erp/app/routes/x+/shipment+/lines.tracking.tsx
index b96f041619..d9e248d08a 100644
--- a/apps/erp/app/routes/x+/shipment+/lines.tracking.tsx
+++ b/apps/erp/app/routes/x+/shipment+/lines.tracking.tsx
@@ -2,6 +2,7 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
+import { round } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
@@ -159,7 +160,9 @@ export async function action({ request }: ActionFunctionArgs) {
if (trackingType === "batch") {
const quantity = Number(formData.get("quantity"));
- if (trackedEntity.quantity < quantity) {
+ // Rounded: a lot holding 0.020000000000000018 after an earlier split has
+ // enough for a 0.02 assignment, and a raw compare rejects it.
+ if (round(trackedEntity.quantity) < round(quantity)) {
return data(
{ success: false, error: "Batch has insufficient quantity" },
await flash(request, error("Batch has insufficient quantity"))
diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx
index fb4511f1f1..f890b8a863 100644
--- a/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx
+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx
@@ -4,7 +4,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
-import { TrackedEntityPicker, toast } from "@carbon/react";
+import {
+ TrackedEntityPicker,
+ type TrackedEntitySelection,
+ toast
+} from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
import { useEffect, useMemo } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
@@ -21,10 +25,12 @@ import type { StockTransfer, StockTransferLine } from "~/modules/inventory";
import {
getAvailableTrackedEntities,
getStockTransfer,
+ resolveStockTransferPickForward,
stockTransferLineScanValidator
} from "~/modules/inventory";
import { getItemStorageUnitQuantities } from "~/modules/items";
import { getCompanySettings } from "~/modules/settings";
+import { getEdgeFunctionErrorMessage } from "~/utils/error";
import { requireUnlocked } from "~/utils/lockedGuard.server";
import { path } from "~/utils/path";
@@ -122,7 +128,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
stockTransferId,
itemId,
locationId,
- trackedEntityId
+ trackedEntityId,
+ quantity,
+ storageUnitId
} = validated.data;
const [stockTransferLine, itemStorageUnitQuantities] = await Promise.all([
@@ -158,15 +166,31 @@ export async function action({ request, params }: ActionFunctionArgs) {
? "batch"
: "serial";
- // Prepare the payload for the post-stock-transfer function
+ // The edge function re-checks this under a row lock, but refusing an already-
+ // full line here avoids a round trip and a raw failure.
+ const forward = resolveStockTransferPickForward({
+ transferType,
+ quantity,
+ storageUnitId,
+ currentStorageUnitId,
+ lineQuantity: Number(stockTransferLine.data?.quantity ?? 0),
+ pickedQuantity: Number(stockTransferLine.data?.pickedQuantity ?? 0)
+ });
+ if (!forward.ok) {
+ return data(
+ { success: false, message: forward.message },
+ await flash(request, error(forward.message, forward.message))
+ );
+ }
+
+ // Prepare the payload for the post-stock-transfer function.
const functionPayload: any = {
type: transferType,
stockTransferId,
stockTransferLineId: lineId,
trackedEntityId,
- quantity:
- transferType === "batch" ? (stockTransferLine.data?.quantity ?? 1) : 1,
- fromStorageUnitId: currentStorageUnitId,
+ quantity: forward.quantity,
+ fromStorageUnitId: forward.fromStorageUnitId,
locationId: locationId,
userId,
companyId
@@ -178,15 +202,16 @@ export async function action({ request, params }: ActionFunctionArgs) {
});
if (functionError) {
+ // The edge function returns its guard failures (over-pick, already picked)
+ // as a 400 with the real reason in the body; surface that, not the generic
+ // "non-2xx" wrapper text.
+ const message = await getEdgeFunctionErrorMessage(
+ functionError,
+ "Failed to pick line"
+ );
return data(
- { success: false, message: "Failed to pick line" },
- await flash(
- request,
- error(
- functionError.message || "Failed to pick line",
- "Failed to pick line"
- )
- )
+ { success: false, message },
+ await flash(request, error(functionError, message))
);
}
@@ -280,14 +305,18 @@ export default function StockTransferScan() {
[entities, pickedElsewhere]
);
- const onPick = (trackedEntityId: string) => {
+ const onPick = (selection: TrackedEntitySelection) => {
fetcher.submit(
{
id: stockTransferLine.id!,
stockTransferId: stockTransferLine.stockTransferId!,
- trackedEntityId,
+ trackedEntityId: selection.trackedEntityId,
itemId: stockTransferLine.itemId!,
- locationId
+ locationId,
+ // Forward the picker's clamped quantity and chosen bin — the host
+ // picking-list scanner does the same.
+ quantity: selection.quantity,
+ storageUnitId: selection.storageUnitId ?? null
},
{
method: "POST",
@@ -309,7 +338,7 @@ export default function StockTransferScan() {
}
nearExpiryWarningDays={nearExpiryWarningDays}
expiredEntityPolicy={expiredEntityPolicy}
- onSelect={(selection) => onPick(selection.trackedEntityId)}
+ onSelect={onPick}
onClose={onClose}
/>
);
diff --git a/apps/mes/app/components/JobOperation/components/BatchCompleteModal.tsx b/apps/mes/app/components/JobOperation/components/BatchCompleteModal.tsx
index 8565e63ce7..12963db230 100644
--- a/apps/mes/app/components/JobOperation/components/BatchCompleteModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/BatchCompleteModal.tsx
@@ -1,4 +1,10 @@
-import { Hidden, Submit, ValidatedForm } from "@carbon/form";
+import {
+ Hidden,
+ Submit,
+ useField,
+ useFormContext,
+ ValidatedForm
+} from "@carbon/form";
import {
Alert,
AlertDescription,
@@ -19,6 +25,7 @@ import type { useFetcher } from "react-router";
import type { z } from "zod";
import { completeJobOperationBatchValidator } from "~/services/models";
import type { JobOperationBatch } from "~/services/operations.service";
+import { decimalInput } from "~/utils/display";
import { path } from "~/utils/path";
// Spreadsheet-style numeric cell — a bare input (no react-aria stepper arrows),
@@ -27,18 +34,59 @@ import { path } from "~/utils/path";
const cellInputClass =
"block h-full min-h-12 w-full bg-transparent px-3 text-right font-mono text-base tabular-nums outline-none transition-colors focus:ring-2 focus:ring-inset focus:ring-ring disabled:cursor-not-allowed disabled:opacity-40";
-// Allow a decimal quantity — a job's operation quantity can be fractional (any
-// non-discrete unit of measure). Keep digits and a single leading decimal point;
-// strip everything else and any extra dots.
-const numericOnly = (value: string) => {
- const cleaned = value.replace(/[^0-9.]/g, "");
- const dot = cleaned.indexOf(".");
- return dot === -1
- ? cleaned
- : cleaned.slice(0, dot + 1) + cleaned.slice(dot + 1).replace(/\./g, "");
-};
const toNumber = (value: string) => Number(value) || 0;
+// A spreadsheet cell wired to the ValidatedForm: it stays visually controlled by
+// the parent's local string state, but reads its validation error from the form
+// (keyed by the same `name` the zod path serializes to) so a bad quantity gets a
+// destructive ring + aria-invalid instead of failing silently on submit.
+function CellInput({
+ name,
+ value,
+ ariaLabel,
+ onChange
+}: {
+ name: string;
+ value: string;
+ ariaLabel: string;
+ onChange: (value: string) => void;
+}) {
+ const { error } = useField(name);
+ return (
+ <input
+ type="text"
+ inputMode="decimal"
+ name={name}
+ aria-label={ariaLabel}
+ aria-invalid={error ? true : undefined}
+ value={value}
+ onFocus={(e) => e.currentTarget.select()}
+ onChange={(e) => onChange(e.target.value)}
+ className={cn(
+ cellInputClass,
+ error && "ring-2 ring-inset ring-destructive"
+ )}
+ />
+ );
+}
+
+// One line under the table when any member quantity failed validation — the grid
+// cells only ring, so this names that something needs fixing.
+function BatchErrorSummary() {
+ const { fieldErrors } = useFormContext() as {
+ fieldErrors?: Record<string, string>;
+ };
+ const hasMemberError = Object.keys(fieldErrors ?? {}).some((key) =>
+ key.startsWith("members")
+ );
+ if (!hasMemberError) return null;
+ return (
+ <p className="mt-2 text-sm text-destructive">
+ <Trans>Fix the highlighted quantities before completing.</Trans>
+ </p>
+ );
+}
+
// The batch completion form, opened from the batched operation view. Posts to
// batch.$batchId.complete (the same action the retired batch page used), which
// invokes the batch-operations edge fn: slice the shared timers per member,
@@ -89,7 +137,7 @@ export function BatchCompleteModal({
);
const setRow = (i: number, key: "quantity" | "scrapQuantity", v: string) =>
setRows((prev) =>
- prev.map((r, idx) => (idx === i ? { ...r, [key]: numericOnly(v) } : r))
+ prev.map((r, idx) => (idx === i ? { ...r, [key]: decimalInput(v) } : r))
);
const isExcludedRow = (i: number) =>
@@ -236,17 +284,11 @@ export function BatchCompleteModal({
!isLast && "border-b"
)}
>
- <input
- type="text"
- inputMode="decimal"
+ <CellInput
name={`members[${i}].quantity`}
- aria-label={t`Quantity`}
+ ariaLabel={t`Quantity`}
value={rows[i]?.quantity ?? ""}
- onFocus={(e) => e.currentTarget.select()}
- onChange={(e) =>
- setRow(i, "quantity", e.target.value)
- }
- className={cellInputClass}
+ onChange={(v) => setRow(i, "quantity", v)}
/>
</td>
<td
@@ -256,17 +298,11 @@ export function BatchCompleteModal({
!isLast && "border-b"
)}
>
- <input
- type="text"
- inputMode="decimal"
+ <CellInput
name={`members[${i}].scrapQuantity`}
- aria-label={t`Scrap`}
+ ariaLabel={t`Scrap`}
value={rows[i]?.scrapQuantity ?? ""}
- onFocus={(e) => e.currentTarget.select()}
- onChange={(e) =>
- setRow(i, "scrapQuantity", e.target.value)
- }
- className={cellInputClass}
+ onChange={(v) => setRow(i, "scrapQuantity", v)}
/>
</td>
{showLotColumn && (
@@ -288,6 +324,7 @@ export function BatchCompleteModal({
</tbody>
</table>
</div>
+ <BatchErrorSummary />
<p className="mt-3 text-pretty text-xs text-muted-foreground">
<Trans>
Leave an operation at 0 to skip it — it returns to the schedule
diff --git a/apps/mes/app/services/allocation.ts b/apps/mes/app/services/allocation.ts
index cfef23e472..046405e00b 100644
--- a/apps/mes/app/services/allocation.ts
+++ b/apps/mes/app/services/allocation.ts
@@ -3,6 +3,7 @@
* can be unit-tested without booting env validation. Re-exported from
* `inventory.service.ts` for call sites.
*/
+import { round } from "@carbon/utils";
export type SuggestedAllocationLot = {
trackedEntityId: string;
@@ -87,7 +88,10 @@ export function greedyFillAllocation(
quantity: number
): SuggestedAllocationLot[] {
const picks: SuggestedAllocationLot[] = [];
- let remaining = quantity;
+ // Round at each step so a spilled remainder is a clean 5dp quantity: filling
+ // 1 from a 0.98 lot leaves round(1 - 0.98) = 0.02, not 0.020000000000000018,
+ // and the last lot's take is that exact 0.02.
+ let remaining = round(quantity);
for (const lot of pool) {
if (remaining <= 0) break;
const available = Number(lot.availableQuantity ?? 0);
@@ -101,7 +105,7 @@ export function greedyFillAllocation(
storageUnitId: lot.storageUnitId ?? null,
storageUnitName: lot.storageUnitName ?? null
});
- remaining -= take;
+ remaining = round(remaining - take);
}
return picks;
}
diff --git a/apps/mes/app/services/inventory.greedy.test.ts b/apps/mes/app/services/inventory.greedy.test.ts
index dc1bf47112..1cdf04a831 100644
--- a/apps/mes/app/services/inventory.greedy.test.ts
+++ b/apps/mes/app/services/inventory.greedy.test.ts
@@ -72,6 +72,12 @@ describe("greedyFillAllocation", () => {
const picks = greedyFillAllocation([lot("B", 1), lot("A", 1)], 2);
expect(picks.map((p) => p.trackedEntityId)).toEqual(["B", "A"]);
});
+
+ it("rounds the spilled remainder at the persist boundary (0.98 + 0.02)", () => {
+ // Raw float would spill round(1 - 0.98) = 0.020000000000000018 onto B.
+ const picks = greedyFillAllocation([lot("A", 0.98), lot("B", 5)], 1);
+ expect(picks.map((p) => p.quantity)).toEqual([0.98, 0.02]);
+ });
});
describe("sortLotsByPickMethod", () => {
diff --git a/apps/mes/app/services/models.batch.test.ts b/apps/mes/app/services/models.batch.test.ts
index 675c723765..6232740780 100644
--- a/apps/mes/app/services/models.batch.test.ts
+++ b/apps/mes/app/services/models.batch.test.ts
@@ -109,3 +109,34 @@ describe("completeJobOperationBatchValidator", () => {
}
});
});
+
+describe("completeJobOperationBatchValidator — decimals", () => {
+ const parseMember = (member: Record<string, unknown>) =>
+ completeJobOperationBatchValidator.safeParse({
+ batchId: "bat_1",
+ members: [{ jobOperationId: "op_1", ...member }]
+ });
+
+ it("accepts a fractional quantity", () => {
+ const result = parseMember({ quantity: 0.5 });
+ expect(result.success).toBe(true);
+ if (result.success) expect(result.data.members[0]!.quantity).toBe(0.5);
+ });
+
+ it("rounds quantity to internal precision at parse", () => {
+ const result = parseMember({ quantity: 0.123456 });
+ expect(result.success).toBe(true);
+ if (result.success) expect(result.data.members[0]!.quantity).toBe(0.12346);
+ });
+
+ it("accepts a fractional scrap quantity", () => {
+ const result = parseMember({ quantity: 1, scrapQuantity: 0.25 });
+ expect(result.success).toBe(true);
+ if (result.success)
+ expect(result.data.members[0]!.scrapQuantity).toBe(0.25);
+ });
+
+ it("rejects a negative quantity", () => {
+ expect(parseMember({ quantity: -1 }).success).toBe(false);
+ });
+});
diff --git a/apps/mes/app/services/models.ts b/apps/mes/app/services/models.ts
index 31c087669b..7398b73ae5 100644
--- a/apps/mes/app/services/models.ts
+++ b/apps/mes/app/services/models.ts
@@ -1,6 +1,14 @@
+import { round } from "@carbon/utils";
import { z } from "zod";
import { zfd } from "zod-form-data";
+// Round an optional produced/scrap quantity to internal precision at parse, so a
+// decimal typed on the floor is stored at the same scale everywhere.
+const roundedOptionalQuantity = () =>
+ zfd
+ .numeric(z.number().min(0).optional())
+ .transform((v) => (v === undefined ? v : round(v)));
+
export const documentTypes = [
"Archive",
"Document",
@@ -242,9 +250,10 @@ export const scrapTrackedEntityValidator = z.object({
notes: zfd.text(z.string().optional())
});
-// Complete a job operation batch: per-member produced quantity (pre-filled with the
-// operation quantity) + optional per-member scrap. quantity is int —
-// productionQuantity.quantity is INTEGER. See
+// Complete a job operation batch: per-member produced quantity (pre-filled with
+// the operation quantity) + optional per-member scrap. Quantities are decimal —
+// productionQuantity.quantity is NUMERIC (widened for weight/length UoMs) — and
+// are rounded to internal precision at parse. See
// .ai/specs/2026-08-21-job-operation-batching.md.
export const completeJobOperationBatchValidator = z.object({
batchId: z.string().min(1, { message: "Batch is required" }),
@@ -260,9 +269,9 @@ export const completeJobOperationBatchValidator = z.object({
// non-discrete unit of measure), so the pre-filled remainder — and the
// operator's edit — must accept decimals, matching single-op completion
// (baseQuantityValidator). An `.int()` here silently failed validation
- // and the modal never submitted.
- quantity: zfd.numeric(z.number().min(0).optional()),
- scrapQuantity: zfd.numeric(z.number().min(0).optional()),
+ // and the modal never submitted. Rounded to internal precision at parse.
+ quantity: roundedOptionalQuantity(),
+ scrapQuantity: roundedOptionalQuantity(),
// Batch-tracked output: the member's WIP entity finalized as the
// produced lot. Its lot number was planned at batch creation and is
// resolved server-side — never an operator input.
diff --git a/apps/mes/app/services/picking.service.ts b/apps/mes/app/services/picking.service.ts
index 453b119a0d..b115ab9e74 100644
--- a/apps/mes/app/services/picking.service.ts
+++ b/apps/mes/app/services/picking.service.ts
@@ -148,8 +148,34 @@ export async function getUnresolvedPickingListLines(
return { unresolved, hasShort, error: null };
}
-function getPostPickingErrorMessage(error: unknown): string {
- return (error as { message?: string })?.message ?? "Failed to pick material";
+async function getPostPickingErrorMessage(error: unknown): Promise<string> {
+ // supabase-js wraps a non-2xx edge-function response in FunctionsHttpError,
+ // whose own `.message` is always the fixed "Edge Function returned a non-2xx
+ // status code". post-picking's pick guards ("This line is already fully
+ // picked") come back as a 400 with the reason in the body, so reading
+ // `.message` alone showed the kitter the wrapper text instead of the reason.
+ // Same pattern as x+/issue-tracked-entity.tsx and the ERP's
+ // getEdgeFunctionErrorMessage.
+ const ctx = (error as { context?: Response })?.context;
+ if (ctx && typeof ctx.clone === "function") {
+ try {
+ const body = await ctx.clone().json();
+ if (typeof body?.message === "string" && body.message !== "") {
+ return body.message;
+ }
+ } catch {
+ // body wasn't JSON or was already consumed — fall through
+ }
+ }
+ const message = (error as { message?: string })?.message;
+ if (
+ typeof message === "string" &&
+ message !== "" &&
+ message !== "Edge Function returned a non-2xx status code"
+ ) {
+ return message;
+ }
+ return "Failed to pick material";
}
/**
@@ -256,7 +282,10 @@ export async function setPickingListLineQuantity(
const result = await client.functions.invoke("post-picking", { body });
if (result.error) {
- return { data: null, error: getPostPickingErrorMessage(result.error) };
+ return {
+ data: null,
+ error: await getPostPickingErrorMessage(result.error)
+ };
}
}
@@ -361,7 +390,10 @@ export async function setPickingListLineTrackedEntity(
const result = await client.functions.invoke("post-picking", { body });
if (result.error) {
- return { data: null, error: getPostPickingErrorMessage(result.error) };
+ return {
+ data: null,
+ error: await getPostPickingErrorMessage(result.error)
+ };
}
return { data: { id: args.pickingListLineId }, error: null };
diff --git a/apps/mes/app/utils/display.test.ts b/apps/mes/app/utils/display.test.ts
index ecedfe5526..fb12eb60cb 100644
--- a/apps/mes/app/utils/display.test.ts
+++ b/apps/mes/app/utils/display.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import type { DisplayDispatch, DisplaySchedule } from "./display";
import {
+ decimalInput,
formatElapsed,
formatRelativeDue,
getInitials,
@@ -393,3 +394,26 @@ describe("getProgress", () => {
expect(getProgress(5, null)).toBeNull();
});
});
+
+describe("decimalInput", () => {
+ it("keeps a valid decimal", () => {
+ expect(decimalInput("0.5")).toBe("0.5");
+ });
+
+ it("keeps only the first decimal point", () => {
+ expect(decimalInput("1.2.3")).toBe("1.23");
+ });
+
+ it("strips non-numeric characters", () => {
+ expect(decimalInput("abc")).toBe("");
+ expect(decimalInput("1a2b")).toBe("12");
+ });
+
+ it("truncates the fraction to 5 decimal places", () => {
+ expect(decimalInput("1.1234567")).toBe("1.12345");
+ });
+
+ it("leaves a whole number untouched", () => {
+ expect(decimalInput("42")).toBe("42");
+ });
+});
diff --git a/apps/mes/app/utils/display.ts b/apps/mes/app/utils/display.ts
index d6d8bc7c90..0c1de3c653 100644
--- a/apps/mes/app/utils/display.ts
+++ b/apps/mes/app/utils/display.ts
@@ -8,8 +8,28 @@
* routes stay thin and the thresholds are unit-testable without a database.
*/
+import { SCALE } from "@carbon/utils";
import { fromDate, getLocalTimeZone } from "@internationalized/date";
+/**
+ * Sanitize a numeric text input for a bare (non-react-aria) cell: keep digits
+ * and a single leading decimal point, drop everything else and any extra dots,
+ * and truncate the fraction to SCALE (5) places — the internal storage
+ * precision, so a typed value never carries more decimals than the database can
+ * hold. `decimalInput("1.2.3") === "1.23"`, `decimalInput("1.1234567") === "1.12345"`.
+ */
+export function decimalInput(value: string): string {
+ const cleaned = value.replace(/[^0-9.]/g, "");
+ const dot = cleaned.indexOf(".");
+ if (dot === -1) return cleaned;
+ const whole = cleaned.slice(0, dot);
+ const fraction = cleaned
+ .slice(dot + 1)
+ .replace(/\./g, "")
+ .slice(0, SCALE);
+ return `${whole}.${fraction}`;
+}
+
export type DisplayStatus = "ok" | "alert";
export type MaintenanceAlertReason =
diff --git a/packages/checks/AGENTS.md b/packages/checks/AGENTS.md
index 179e829d08..09b0d0733b 100644
--- a/packages/checks/AGENTS.md
+++ b/packages/checks/AGENTS.md
@@ -32,7 +32,7 @@ pnpm --filter @carbon/checks baseline # regenerate baseline (careful!)
## Key Patterns
- **Conformance checks**: `noNumericPrecision`, `noLegacyRls`, `noDerivedPercentColumn` — scan SQL migrations for anti-patterns (`noDerivedPercentColumn` flags a `*Percent`/`*Rate` column `GENERATED ALWAYS AS` an expression that divides — a percentage is an entered fact, never a lossy echo of a rounded amount); `noLocalTimezone` (in `SERVER_CHECKS`) scans server TS (`sources/server-files.ts`) for `getLocalTimeZone()`, UTC day-slicing, local date-parts of now (`new Date().getDay()` etc.), and `setHours(0,0,0,0)` midnights. Scanned files: MES services, `packages/jobs`, edge functions, ERP module `.service.ts`/`.server.ts`, **plus both apps' route trees** — route modules are server AND client in one file, so `maskClientCode` blanks the browser half (default export, `clientLoader`/`clientAction`, PascalCase/`use*` declarations) while keeping loaders, actions, and the module-level helpers they call
-- **Numeric-precision checks** (in `TS_CHECKS`, over `sources/typescript.ts`): `noRawRounding` flags `Math.round/ceil/floor` and `.toFixed` on value-bearing numbers (use `round`/`scrapAllowance`/`applyRate`/`deriveRate` from `@carbon/utils`); `noInlineFractionDigits` flags `minimum`/`maximumFractionDigits` at a call site (pick a named kind from `@carbon/utils` `format.ts`, and `INPUT_FORMAT.*` for anything editable). `sources/typescript.ts` walks `apps/erp/app/{components,hooks,modules,routes}`, `apps/mes/app`, `packages/database/supabase/functions`, `packages/{ee,jobs}/src`, `packages/documents/src/{pdf,utils}` and the shared packages `packages/{utils,form,react,printing,workflows}/src` — tests and the image/logo resizers excluded. The shared packages matter: `@carbon/utils` is where the standard's own helpers live, and `form`/`react` own the number inputs whose `formatOptions` are part of the storage round-trip. See `.claude/rules/numeric-precision.md`
+- **Numeric-precision checks** (in `TS_CHECKS`, over `sources/typescript.ts`): `noRawRounding` flags `Math.round/ceil/floor` and `.toFixed` on value-bearing numbers (use `round`/`scrapAllowance`/`applyRate`/`deriveRate` from `@carbon/utils`); `noInlineFractionDigits` flags `minimum`/`maximumFractionDigits` at a call site (pick a named kind from `@carbon/utils` `format.ts`, and `INPUT_FORMAT.*` for anything editable); `noUnroundedTrackedQuantity` flags inline unrounded arithmetic inside a `.updateTable("trackedEntity")` statement's `quantity:` set, and a raw `===`/`!==`/`<` compare against a `*[Ee]ntity*.quantity` read (use `round`/`settleQuantity` at the write, `isFullDraw` at a split gate — see `.claude/rules/traceability-model.md`). It is scoped to what one file can prove: a `quantity:` set from an already-rounded variable is unflaggable either way, and a compare of two locals is presumed rounded where they were defined. It has **no baseline entries** — the whole tree was fixed in the pass that added it, so any finding is new. `sources/typescript.ts` walks `apps/erp/app/{components,hooks,modules,routes}`, `apps/mes/app`, `packages/database/supabase/functions`, `packages/{ee,jobs}/src`, `packages/documents/src/{pdf,utils}` and the shared packages `packages/{utils,form,react,printing,workflows}/src` — tests and the image/logo resizers excluded. The shared packages matter: `@carbon/utils` is where the standard's own helpers live, and `form`/`react` own the number inputs whose `formatOptions` are part of the storage round-trip. See `.claude/rules/numeric-precision.md`
- **Structure checks**: `moduleShape` — validates ERP modules have `types.ts`, `ui/`, `index.ts`, `<name>.service.ts`, `<name>.models.ts`
- **Clobber detection**: `findClobbers(branch, main)` — identifies DB objects redefined on both sides
- **Baseline**: `src/baseline.ts` — grandfathered violations keyed by `checkId + file + line + snippet`
diff --git a/packages/checks/src/conformance/no-unrounded-tracked-quantity.test.ts b/packages/checks/src/conformance/no-unrounded-tracked-quantity.test.ts
new file mode 100644
index 0000000000..a9b4b5ba54
--- /dev/null
+++ b/packages/checks/src/conformance/no-unrounded-tracked-quantity.test.ts
@@ -0,0 +1,250 @@
+import { describe, expect, it } from "vitest";
+import { noUnroundedTrackedQuantity } from "./no-unrounded-tracked-quantity";
+
+const scan = (src: string, file = "a.ts") =>
+ noUnroundedTrackedQuantity.scan(file, src);
+
+describe("no-unrounded-tracked-quantity — the write", () => {
+ it("flags inline arithmetic in a trackedEntity quantity set", () => {
+ const src = [
+ "await trx",
+ ' .updateTable("trackedEntity")',
+ " .set({ quantity: Number(parent.quantity) + unpickQuantity })",
+ ' .where("id", "=", parent.id)',
+ " .execute();"
+ ].join("\n");
+ const violations = scan(src);
+ expect(violations).toHaveLength(1);
+ expect(violations[0]?.line).toBe(3);
+ expect(violations[0]?.message).toMatch(/settleQuantity/);
+ });
+
+ it("accepts a statement that rounds, wherever the round sits", () => {
+ const rounded = [
+ "await trx",
+ ' .updateTable("trackedEntity")',
+ " .set({ quantity: round(Number(parent.quantity) + unpickQuantity) })",
+ " .execute();"
+ ].join("\n");
+ expect(scan(rounded)).toHaveLength(0);
+
+ // The common real shape: the arithmetic is an argument to settleQuantity on
+ // an earlier line than the `quantity:` property it produces.
+ const settled = [
+ "await trx",
+ ' .updateTable("trackedEntity")',
+ " .set(",
+ " settleQuantity({",
+ " quantity: targetQty - adjustmentQuantity,",
+ " status: currentStatus",
+ " })",
+ " )",
+ " .execute();"
+ ].join("\n");
+ expect(scan(settled)).toHaveLength(0);
+ });
+
+ it("accepts a quantity taken from a variable or the split builder", () => {
+ const src = [
+ "await trx",
+ ' .updateTable("trackedEntity")',
+ " .set(split.parentUpdate)",
+ " .execute();",
+ "await trx",
+ ' .updateTable("trackedEntity")',
+ " .set({ quantity: drainedQty, status: settledStatus })",
+ " .execute();"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(0);
+ });
+
+ it("does not read a quoted operator as arithmetic", () => {
+ // eb("quantity", "+", delta) delegates the arithmetic to SQL; the operand
+ // is a variable the caller rounded, and the "+" is a string literal.
+ const src = [
+ "await trx",
+ ' .updateTable("trackedEntity")',
+ ' .set((eb) => ({ quantity: eb("quantity", "+", delta) }))',
+ " .execute();"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(0);
+ });
+
+ it("stops at the statement's own execute, so a later ledger insert is not blamed", () => {
+ const src = [
+ "await trx",
+ ' .updateTable("trackedEntity")',
+ " .set({ quantity: drainedQty })",
+ " .execute();",
+ "itemLedgerInserts.push({",
+ " quantity: -Math.abs(adjustmentQuantity),",
+ "});"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(0);
+ });
+
+ it("ignores commented-out arithmetic", () => {
+ const src = [
+ "await trx",
+ ' .updateTable("trackedEntity")',
+ " // was: quantity: a - b",
+ " .set({ quantity: settled })",
+ " .execute();"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(0);
+ });
+
+ it("does not scan the modules that implement the standard", () => {
+ const src = [
+ "await trx",
+ ' .updateTable("trackedEntity")',
+ " .set({ quantity: a - b })",
+ " .execute();"
+ ].join("\n");
+ expect(
+ scan(src, "packages/database/supabase/functions/shared/entity-drain.ts")
+ ).toHaveLength(0);
+ });
+});
+
+describe("no-unrounded-tracked-quantity — the split gate", () => {
+ it("flags a raw compare on a stored entity quantity, either operand order", () => {
+ const src = [
+ "if (entityQuantity !== transferQuantity) {",
+ "if (trackedEntity.quantity < quantity) {",
+ "if (shipmentLine.shippedQuantity < trackedEntity.quantity) {"
+ ].join("\n");
+ const violations = scan(src);
+ // Line 1 compares two locals — presumed rounded where they were defined.
+ expect(violations.map((v) => v.line)).toEqual([2, 3]);
+ expect(violations[0]?.message).toMatch(/isFullDraw/);
+ });
+
+ it("accepts the sanctioned gates", () => {
+ const src = [
+ "if (!isFullDraw(entityQuantity, transferQuantity)) {",
+ "if (equals(Number(trackedEntity.quantity), quantity)) {",
+ "if (round(onHand) <= round(Number(entity.quantity))) {"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(0);
+ });
+
+ it("does not flag literal or nullish tests", () => {
+ // "has any stock", "is this a serial", "was it selected" — not split gates.
+ const src = [
+ "if (entity.quantity > 0) {",
+ "if (entity.quantity !== 1) {",
+ "if (newEntityQuantity <= 0) {",
+ "if (trackedEntity.quantity !== undefined) {",
+ "if (entity.quantity === null) {"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(0);
+ });
+
+ it("does not flag a non-entity row that happens to have a quantity", () => {
+ // costLedger children, BOM lines, shipment lines — same property name,
+ // different shape, and none of them are lots on a shelf.
+ const src = [
+ "if (Number(child.remainingQuantity ?? 0) === Number(child.quantity)) {",
+ "if (!(parent.quantity > 0)) {",
+ "if (line.quantity < required) {"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(0);
+ });
+});
+
+describe("no-unrounded-tracked-quantity — shapes that only look like compares", () => {
+ it("does not read an arrow function's => as a > comparison", () => {
+ const src = [
+ "receivable.some((entity) => entity.quantity !== 1 || !entity.readableId)",
+ "const qty = (entity) => entity.quantity;"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(0);
+ });
+
+ it("still flags a real compare inside an arrow body", () => {
+ const src = "entities.filter((e) => e.quantity < required)";
+ // `e.quantity` is not entity-shaped; the entity-named one is.
+ expect(scan(src)).toHaveLength(0);
+ expect(
+ scan("entities.filter((x) => x.entityQuantity > threshold)")
+ ).toHaveLength(0);
+ expect(
+ scan("entities.filter((x) => x.trackedEntity.quantity > threshold)")
+ ).toHaveLength(1);
+ });
+});
+
+describe("no-unrounded-tracked-quantity — the exemption is operand-scoped", () => {
+ it("an unrelated round() elsewhere in the statement does not exempt the quantity", () => {
+ // The sibling property rounds; `quantity` does not. Must still flag.
+ const src = [
+ "await trx",
+ ' .updateTable("trackedEntity")',
+ " .set({ quantity: parent.quantity - drawnQuantity, readableId: round(x) })",
+ " .execute();"
+ ].join("\n");
+ const violations = scan(src);
+ expect(violations).toHaveLength(1);
+ expect(violations[0]?.line).toBe(3);
+ });
+
+ it("an unrelated round() on a LATER line does not exempt the quantity", () => {
+ const src = [
+ "await trx",
+ ' .updateTable("trackedEntity")',
+ " .set({",
+ " quantity: parent.quantity - drawnQuantity,",
+ " readableId: round(x)",
+ " })",
+ " .execute();"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(1);
+ expect(scan(src)[0]?.line).toBe(4);
+ });
+
+ it("still exempts a quantity the settleQuantity wrapper encloses", () => {
+ const src = [
+ "await trx",
+ ' .updateTable("trackedEntity")',
+ " .set(",
+ " settleQuantity({",
+ " quantity: targetQty - adjustmentQuantity,",
+ " status: currentStatus",
+ " })",
+ " )",
+ " .execute();"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(0);
+ });
+
+ it("an unrelated round() on the other side of a compare does not exempt it", () => {
+ // `entity.quantity` itself is raw — the round() is on the other operand.
+ const src = "if (round(requested) < entity.quantity) {";
+ const violations = scan(src);
+ expect(violations).toHaveLength(1);
+ expect(violations[0]?.message).toMatch(/isFullDraw/);
+ });
+
+ it("still exempts a compare whose entity-quantity operand IS wrapped", () => {
+ const src = [
+ "if (round(onHand) <= round(Number(entity.quantity))) {",
+ "if (equals(Number(trackedEntity.quantity), quantity)) {"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(0);
+ });
+
+ it("flags each offending quantity write once, not once per statement", () => {
+ const src = [
+ "await trx",
+ ' .updateTable("trackedEntity")',
+ " .set({ quantity: a - b })",
+ " .execute();",
+ "await trx",
+ ' .updateTable("trackedEntity")',
+ " .set({ quantity: c - d })",
+ " .execute();"
+ ].join("\n");
+ expect(scan(src).map((v) => v.line)).toEqual([3, 7]);
+ });
+});
diff --git a/packages/checks/src/conformance/no-unrounded-tracked-quantity.ts b/packages/checks/src/conformance/no-unrounded-tracked-quantity.ts
new file mode 100644
index 0000000000..0247ec3e28
--- /dev/null
+++ b/packages/checks/src/conformance/no-unrounded-tracked-quantity.ts
@@ -0,0 +1,231 @@
+import type { ConformanceCheck, Violation } from "../check";
+
+/**
+ * A tracked entity's quantity is the physical truth about a lot on a shelf, and
+ * `trackedEntity.quantity` is a bare NUMERIC — so whatever float a writer hands
+ * it is what is stored. Two defect classes follow from that, and both shipped:
+ *
+ * 1. **Unrounded arithmetic reaching storage.** A lot left holding
+ * `0.020000000000000018` after an earlier split reads "0.02" in every UI and
+ * behaves like 0.02 nowhere. Round at the persist boundary — via `round()`
+ * from `functions/shared/precision.ts` / `@carbon/utils`, or (better) via
+ * `settleQuantity()` from `functions/shared/entity-drain.ts`, which rounds,
+ * refuses a negative, and applies the drain-to-Consumed rule in one step.
+ *
+ * 2. **A raw compare on that stored float deciding a split.** `entity.quantity
+ * !== drawn` reads a residue full draw as PARTIAL, and the split builder then
+ * throws its own `draw >= parentQty` guard as a 500 on a legitimate full
+ * pick — or mints a child entity holding 1.8e-17. Use `isFullDraw()` from
+ * `functions/shared/batch-split.ts` (the one split gate, so a caller's
+ * decision and the builder's guard can never disagree) or `equals()` on
+ * rounded values.
+ *
+ * Scope is deliberately what a single file can PROVE, not everything that could
+ * be wrong:
+ *
+ * - The write rule asks whether THIS `quantity:` expression went through the
+ * standard — either the value itself calls a sanctioned helper, or the
+ * property sits inside one (the `settleQuantity({ quantity: a - b, … })`
+ * shape, where the helper opens on an earlier line). A sanctioned call
+ * elsewhere in the same statement does NOT exempt it: `quantity: a - b`
+ * beside a `readableId: round(x)` is still a finding. A `quantity:` set from
+ * a variable rounded three lines up is fine and unflaggable either way; what
+ * it catches is arithmetic spelled out inline in the `.set`.
+ * - The compare rule only fires on a `.quantity` read straight off a row, which
+ * is unrounded BY CONSTRUCTION, and only when THAT operand is not itself
+ * wrapped in a sanctioned call — an unrelated `round()` on the other side of
+ * the comparison does not exempt it. A comparison of two locals is presumed
+ * to have been rounded where they were defined; comparisons against a literal
+ * (`> 0`, `!== 1`, `<= 0`) are "is there any stock" / "is this a serial"
+ * tests, not split gates, and are not flagged.
+ *
+ * See `.claude/rules/traceability-model.md` and `.claude/rules/numeric-precision.md`.
+ */
+
+const MESSAGE_WRITE =
+ "Unrounded arithmetic written to trackedEntity.quantity — the column is bare NUMERIC, so this float is what gets stored. Round at the persist boundary with round(), or settle the whole write with settleQuantity() from shared/entity-drain.ts.";
+
+const MESSAGE_COMPARE =
+ "Raw compare on a stored tracked-entity quantity — a residue value (0.020000000000000018) makes a full draw read as partial. Use isFullDraw() from shared/batch-split.ts for a split gate, or round both sides.";
+
+/** The helpers that satisfy the standard. `equals`/`isFullDraw` are compare-side. */
+const SANCTIONED =
+ /\bround\s*\(|\bsettleQuantity\s*\(|\bresolveCountedEntity\s*\(/;
+
+/** The modules that IMPLEMENT the standard; they are where the rounding lives. */
+const EXCLUDED_FILES = new Set([
+ "packages/database/supabase/functions/shared/precision.ts",
+ "packages/database/supabase/functions/shared/batch-split.ts",
+ "packages/database/supabase/functions/shared/batch-merge.ts",
+ "packages/database/supabase/functions/shared/entity-drain.ts"
+]);
+
+const isComment = (text: string) => /^\s*(?:\/\/|\/\*|\*)/.test(text);
+
+/** Blank out string and template contents so `eb("quantity", "+", delta)`'s
+ * operator literal is not read as arithmetic. */
+const withoutStrings = (text: string) =>
+ text
+ .replace(/"(?:[^"\\]|\\.)*"/g, '""')
+ .replace(/'(?:[^'\\]|\\.)*'/g, "''")
+ .replace(/`(?:[^`\\]|\\.)*`/g, "``");
+
+const hasArithmetic = (text: string) => /[-+*/]/.test(text);
+
+/** Helper NAMES (no trailing paren) used for the enclosure scan below. */
+const SANCTIONED_CALL = /(?:round|settleQuantity|resolveCountedEntity)$/;
+const SANCTIONED_COMPARE_CALL = /(?:round|equals|isFullDraw)$/;
+
+/**
+ * Is `index` lexically inside a still-open call to one of `names`?
+ *
+ * This is what scopes the exemption to the operand instead of the whole line:
+ * `round(Number(entity.quantity))` encloses its read, while
+ * `round(onHand) < entity.quantity` does not. Walks the (string-blanked) text
+ * keeping a stack of open parens, each tagged with whether the identifier
+ * immediately before it is a sanctioned helper.
+ */
+function enclosedBySanctioned(
+ text: string,
+ index: number,
+ names: RegExp
+): boolean {
+ const stack: boolean[] = [];
+ for (let i = 0; i < index && i < text.length; i++) {
+ const ch = text[i];
+ if (ch === "(") {
+ const before = text.slice(0, i).match(/[A-Za-z_$][\w$]*$/);
+ stack.push(before ? names.test(before[0]) : false);
+ } else if (ch === ")") {
+ stack.pop();
+ }
+ }
+ return stack.some(Boolean);
+}
+
+/**
+ * The value expression of an object property starting at `from` — up to the
+ * comma that ends it AT THE SAME paren/brace depth, or end of line. Bounding by
+ * depth is what stops a sibling property's `round()` from exempting this one.
+ */
+function propertyValue(text: string, from: number): string {
+ let depth = 0;
+ for (let i = from; i < text.length; i++) {
+ const ch = text[i];
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
+ else if (ch === ")" || ch === "]" || ch === "}") {
+ if (depth === 0) return text.slice(from, i);
+ depth--;
+ } else if (ch === "," && depth === 0) return text.slice(from, i);
+ }
+ return text.slice(from);
+}
+
+/** `entity.quantity`, `trackedEntity.quantity`, `parentEntity.quantity` — a
+ * quantity read straight off a row. Bare `parent`/`child` are deliberately NOT
+ * matched: they are also cost-ledger and BOM-line shapes. */
+const ENTITY_QUANTITY = String.raw`\w*[Ee]ntity\w*\.quantity`;
+const COMPARATOR = String.raw`===|!==|<=|>=|<|>`;
+/** Anything that is not a number literal, `undefined` or `null`. */
+const NOT_A_LITERAL = String.raw`(?!\s*(?:-?\d|undefined|null)\b)`;
+
+/** `=>` ends in `>`, so an arrow function reads as "compared against whatever
+ * the body starts with". Require the operator not to continue one. */
+const NOT_AN_ARROW = String.raw`(?<![=!<>])`;
+
+const COMPARE_PATTERNS = [
+ // entity.quantity <op> <non-literal>
+ new RegExp(`${ENTITY_QUANTITY}\\s*(?:${COMPARATOR})${NOT_A_LITERAL}`),
+ // <anything> <op> entity.quantity (the operand order post-shipment used)
+ new RegExp(
+ `${NOT_AN_ARROW}(?:${COMPARATOR})\\s*(?:Number\\()?\\s*${ENTITY_QUANTITY}`
+ )
+];
+
+export const noUnroundedTrackedQuantity: ConformanceCheck = {
+ id: "no-unrounded-tracked-quantity",
+ description:
+ "A tracked entity's quantity is rounded at the persist boundary (round/settleQuantity) and split gates compare through isFullDraw — never raw float arithmetic or a raw ===/< on a stored quantity.",
+ provenance: {
+ deprecates:
+ 'inline unrounded arithmetic in .updateTable("trackedEntity").set({ quantity }) and raw ===/!==/< split gates on trackedEntity.quantity',
+ replacedBy:
+ "round() / settleQuantity() (functions/shared/entity-drain.ts) at the write, isFullDraw() (functions/shared/batch-split.ts) at the gate",
+ since: "2026-09-23"
+ },
+ scan(file: string, contents: string): Violation[] {
+ if (EXCLUDED_FILES.has(file)) return [];
+ const violations: Violation[] = [];
+ const lines = contents.split("\n");
+
+ // --- Rule 1: the write. One `.updateTable("trackedEntity")` statement at a
+ // time, ending at its `.execute(`. Each `quantity:` property is judged on
+ // its OWN expression, not on whether the statement rounds something else.
+ for (let i = 0; i < lines.length; i++) {
+ if (!lines[i]!.includes('.updateTable("trackedEntity")')) continue;
+ const stmt: { line: number; text: string }[] = [];
+ for (let j = i; j < lines.length; j++) {
+ stmt.push({ line: j + 1, text: lines[j]! });
+ if (lines[j]!.includes(".execute(")) break;
+ }
+
+ // Statement text with strings blanked, so a helper that opens on an
+ // earlier line (`settleQuantity({` …) is still visible as an enclosure.
+ const bareLines = stmt.map(({ text }) =>
+ isComment(text) ? "" : withoutStrings(text)
+ );
+
+ for (let k = 0; k < stmt.length; k++) {
+ const bare = bareLines[k]!;
+ const prefix = bareLines.slice(0, k).join("\n");
+ for (const match of bare.matchAll(/\bquantity:/g)) {
+ const at = match.index ?? 0;
+ // Inside `settleQuantity({ … })` / `round( … )` opened earlier?
+ if (
+ enclosedBySanctioned(
+ prefix + "\n" + bare,
+ prefix.length + 1 + at,
+ SANCTIONED_CALL
+ )
+ ) {
+ continue;
+ }
+ const value = propertyValue(bare, at + match[0].length);
+ if (SANCTIONED.test(value)) continue;
+ if (!hasArithmetic(value)) continue;
+ violations.push({
+ file,
+ line: stmt[k]!.line,
+ snippet: stmt[k]!.text.trim(),
+ message: MESSAGE_WRITE
+ });
+ }
+ }
+ }
+
+ // --- Rule 2: the compare. Judged per OPERAND: the entity-quantity read
+ // must itself be wrapped in a sanctioned call.
+ lines.forEach((text, i) => {
+ if (isComment(text)) return;
+ const bare = withoutStrings(text);
+ for (const pattern of COMPARE_PATTERNS) {
+ const match = pattern.exec(bare);
+ if (!match) continue;
+ // Locate the `.quantity` read inside the match and ask whether THAT
+ // operand is wrapped — not whether the line mentions a helper at all.
+ const local = match[0].search(/\.quantity/);
+ const at = (match.index ?? 0) + (local >= 0 ? local : 0);
+ if (enclosedBySanctioned(bare, at, SANCTIONED_COMPARE_CALL)) continue;
+ violations.push({
+ file,
+ line: i + 1,
+ snippet: text.trim(),
+ message: MESSAGE_COMPARE
+ });
+ return;
+ }
+ });
+
+ return violations;
+ }
+};
diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.ts
index 06f0d23c87..b1bf53b910 100644
--- a/packages/checks/src/run.ts
+++ b/packages/checks/src/run.ts
@@ -16,6 +16,7 @@ import { noLocalTimezone } from "./conformance/no-local-timezone";
import { noNumericPrecision } from "./conformance/no-numeric-precision";
import { noRawRounding } from "./conformance/no-raw-rounding";
import { noRequiredColumnWithoutDefault } from "./conformance/no-required-column-without-default";
+import { noUnroundedTrackedQuantity } from "./conformance/no-unrounded-tracked-quantity";
import { noZeroConcurrency } from "./conformance/no-zero-concurrency";
import { loadSqlFiles, migrationsDir, repoRoot } from "./sources/migrations";
import { loadModules, modulesDir } from "./sources/modules";
@@ -40,7 +41,8 @@ export const TS_CHECKS: ConformanceCheck[] = [
noRawRounding,
noInlineFractionDigits,
noDbClientInService,
- noDefaultOnEffects
+ noDefaultOnEffects,
+ noUnroundedTrackedQuantity
];
export const STRUCTURE_CHECKS: StructureCheck[] = [moduleShape];
diff --git a/packages/database/src/check-datasets.ts b/packages/database/src/check-datasets.ts
index 6006334d83..bc2b5559d4 100644
--- a/packages/database/src/check-datasets.ts
+++ b/packages/database/src/check-datasets.ts
@@ -99,6 +99,14 @@ async function main() {
}
}
+ // No connection string configured at all (fresh worktree, no .env.local).
+ // getPostgresConnectionPool dereferences it before any connect() can fail,
+ // so without this the hook blocks the commit on "Cannot read properties of
+ // undefined (reading 'includes')" — the least actionable message there is.
+ if (!process.env.SUPABASE_DB_URL) {
+ skip("SUPABASE_DB_URL is not set (no .env.local in this worktree?)");
+ }
+
const pool = getPostgresConnectionPool(1);
let client: PoolClient;
try {
diff --git a/packages/database/supabase/functions/batch-operations/index.ts b/packages/database/supabase/functions/batch-operations/index.ts
index 757a7740e0..1e467bbe4a 100644
--- a/packages/database/supabase/functions/batch-operations/index.ts
+++ b/packages/database/supabase/functions/batch-operations/index.ts
@@ -20,6 +20,7 @@ import {
resolveBatchRules
} from "../shared/batch-compatibility.ts";
import { getNextSequence } from "../shared/get-next-sequence.ts";
+import { round } from "../shared/precision.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -97,8 +98,15 @@ const payloadValidator = z.discriminatedUnion("type", [
.array(
z.object({
jobOperationId: z.string(),
- quantity: z.number().int().min(0),
- scrapQuantity: z.number().int().min(0).optional(),
+ // Decimal, matching the MES validator: productionQuantity.quantity is
+ // NUMERIC. An `.int()` here rejected every fractional completion the
+ // (already decimal) MES validator let through. Rounded at parse.
+ quantity: z.number().min(0).transform((v) => round(v)),
+ scrapQuantity: z
+ .number()
+ .min(0)
+ .transform((v) => round(v))
+ .optional(),
// Batch-tracked output: the member's WIP entity to finalize as the
// produced lot, and the batch number to stamp on it.
trackedEntityId: z.string().optional().nullable(),
diff --git a/packages/database/supabase/functions/correct-stock-movement/index.ts b/packages/database/supabase/functions/correct-stock-movement/index.ts
index b634d9cca8..3ec6f3b715 100644
--- a/packages/database/supabase/functions/correct-stock-movement/index.ts
+++ b/packages/database/supabase/functions/correct-stock-movement/index.ts
@@ -7,6 +7,8 @@ import { requirePermissions } from "../lib/supabase.ts";
import { getAccountingPeriodForDate } from "../shared/get-accounting-period.ts";
import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";
import { bookAdjustment } from "../shared/post-adjustment.ts";
+import { statusAfterQuantityChange } from "../shared/entity-drain.ts";
+import { equals, round } from "../shared/precision.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -106,8 +108,13 @@ serve(async (req: Request) => {
}
}
- const delta = correctedQuantity - effectiveQuantity;
- if (delta === 0) {
+ // Round the delta ONCE, here: it is persisted twice — into the entity via
+ // eb("quantity", "+", delta) and into the correction's own itemLedger row —
+ // and both must carry the same value at internal scale. A raw `=== 0` no-op
+ // gate also lets float residue (correcting a -5 line back to exactly its
+ // effective -4.99999999999999 sum) through as a 1e-14 correction row.
+ const delta = round(correctedQuantity - effectiveQuantity);
+ if (equals(delta, 0)) {
throw new ValidationError(
"Corrected quantity matches the current effective quantity — nothing to correct"
);
@@ -219,7 +226,9 @@ serve(async (req: Request) => {
"Cannot correct a movement of a consumed tracked entity"
);
}
- if (Number(entity.data.quantity) + delta < 0) {
+ // Round before comparing: a correction that lands the lot exactly on
+ // zero can read as −1e-17 raw and refuse a legitimate full correction.
+ if (round(Number(entity.data.quantity) + delta) < 0) {
throw new ValidationError(
"Correction would make the tracked entity quantity negative"
);
@@ -299,13 +308,27 @@ serve(async (req: Request) => {
.where((eb) => eb("quantity", ">=", -delta))
// Serial ceiling re-checked atomically: resulting quantity ≤ 1.
.$if(isSerial, (qb) => qb.where((eb) => eb("quantity", "<=", 1 - delta)))
- .returning(["id"])
+ .returning(["id", "quantity", "status"])
.executeTakeFirst();
if (!updated) {
throw new ValidationError(
"Tracked entity changed while correcting — try again"
);
}
+ // If the correction drove the lot to zero, Consume it (a Scrapped lot
+ // stays Scrapped). `updated.status` is the unchanged pre-flip status.
+ const settledStatus = statusAfterQuantityChange(
+ Number(updated.quantity),
+ updated.status
+ );
+ if (settledStatus !== updated.status) {
+ await trx
+ .updateTable("trackedEntity")
+ .set({ status: settledStatus })
+ .where("id", "=", root.trackedEntityId!)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
}
const booked = await bookAdjustment(trx, {
diff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.ts
index 0a9127f3c1..5317d87251 100644
--- a/packages/database/supabase/functions/create/index.ts
+++ b/packages/database/supabase/functions/create/index.ts
@@ -9,6 +9,8 @@ import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import { Database, Json } from "../lib/types.ts";
import { getNextSequence } from "../shared/get-next-sequence.ts";
+import { settleQuantity } from "../shared/entity-drain.ts";
+import { round } from "../shared/precision.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -1693,7 +1695,7 @@ serve(async (req: Request) => {
.insertInto("trackedEntity")
.values({
id: nanoid(),
- quantity: quantity,
+ quantity: round(quantity),
status: entity.status,
sourceDocument: entity.sourceDocument,
sourceDocumentId: entity.sourceDocumentId,
@@ -1709,9 +1711,17 @@ serve(async (req: Request) => {
await trx
.updateTable("trackedEntity")
- .set({
- quantity: Math.max(0, (entity.quantity ?? 0) - quantity),
- })
+ // A parent drained to zero by the split is Consumed, not a
+ // zero-quantity Available husk; a Scrapped parent stays so.
+ // The Math.max clamp is kept deliberately: a receipt-line
+ // split over the parent's quantity has always clamped here
+ // rather than refused, and that is not this change to make.
+ .set(
+ settleQuantity({
+ quantity: Math.max(0, (entity.quantity ?? 0) - quantity),
+ status: entity.status,
+ })
+ )
.where("id", "=", entity.id)
.execute();
}
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.ts
index 70feca3bd9..96e96f22b8 100644
--- a/packages/database/supabase/functions/issue/index.ts
+++ b/packages/database/supabase/functions/issue/index.ts
@@ -18,8 +18,9 @@ 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 { buildBatchSplitRecords, isFullDraw } from "../shared/batch-split.ts";
import { buildBatchMergeRecords } from "../shared/batch-merge.ts";
+import { round } from "../shared/precision.ts";
import { splitPickAcrossMembers } from "../shared/batch-pick-split.ts";
import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
import { bookAdjustment } from "../shared/post-adjustment.ts";
@@ -368,8 +369,9 @@ async function issueJobOperationMaterials(
await trx
.updateTable("jobMaterial")
.set({
- quantityIssued:
- (Number(material.quantityIssued) ?? 0) + quantityToIssue,
+ quantityIssued: round(
+ round(Number(material.quantityIssued) ?? 0) + round(quantityToIssue)
+ ),
})
.where("id", "=", material.id)
.execute();
@@ -861,6 +863,18 @@ async function createMaterialWipEntries(
}
}
+// Each child's quantity is its own persist boundary — it becomes one
+// Consumption ledger row — so round PER CHILD and then round the sum. That is
+// what makes jobMaterial.quantityIssued net exactly against those rows; a
+// single round of the raw sum can differ from them by a minor unit.
+function roundedChildTotal(
+ children: { quantity: number | string }[]
+): number {
+ return round(
+ children.reduce((sum, child) => sum + round(Number(child.quantity)), 0)
+ );
+}
+
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
const logger = getFunctionLogger("issue");
@@ -1239,9 +1253,7 @@ async function consumeTrackedEntitiesIntoOperation(
firstTrackedEntity.sourceDocumentId !== jobMaterial.itemId
) {
// Create a new jobMaterial for the tracked entity's item
- const totalChildQuantity = children.reduce((sum, child) => {
- return sum + Number(child.quantity);
- }, 0);
+ const totalChildQuantity = roundedChildTotal(children);
const itemCost = await trx
.selectFrom("itemCost")
@@ -1302,9 +1314,7 @@ async function consumeTrackedEntitiesIntoOperation(
throw new Error("Item not found");
}
- const totalChildQuantity = children.reduce((sum, child) => {
- return sum + Number(child.quantity);
- }, 0);
+ const totalChildQuantity = roundedChildTotal(children);
const itemCost = await trx
.selectFrom("itemCost")
@@ -1452,7 +1462,16 @@ async function consumeTrackedEntitiesIntoOperation(
if (!trackedEntity) {
throw new Error("Tracked entity not found");
}
- const { trackedEntityId, quantity } = child;
+ const { trackedEntityId } = child;
+
+ // ONE canonical quantity for this child, rounded at the persist
+ // boundary. On a FULL draw it is the lot's own on-hand: the entity
+ // is flipped Consumed without its quantity being rewritten, so
+ // booking the requested figure instead would leave the Consumption
+ // ledger row disagreeing with the lot it just emptied.
+ const entityQuantity = round(Number(trackedEntity.quantity));
+ const fullDraw = isFullDraw(entityQuantity, child.quantity);
+ const quantity = fullDraw ? entityQuantity : round(child.quantity);
// Partial consume → split: the lineside entity keeps its id and
// is decremented; a NEW child entity carries the consumed
@@ -1460,7 +1479,7 @@ async function consumeTrackedEntitiesIntoOperation(
// Consumption ledger) books against the child — flipping the
// entity half without the ledger half would double-count on-hand.
let consumedEntityId = trackedEntityId;
- if (Number(trackedEntity.quantity) !== quantity) {
+ if (!fullDraw) {
const consumedChildId = nanoid();
consumedEntityId = consumedChildId;
@@ -1468,7 +1487,7 @@ async function consumeTrackedEntitiesIntoOperation(
parent: {
id: trackedEntity.id!,
readableId: trackedEntity.readableId,
- quantity: Number(trackedEntity.quantity),
+ quantity: entityQuantity,
sourceDocument: trackedEntity.sourceDocument,
sourceDocumentId: trackedEntity.sourceDocumentId,
sourceDocumentReadableId:
@@ -1639,16 +1658,16 @@ async function consumeTrackedEntitiesIntoOperation(
}
}
- const totalChildQuantity = children.reduce((sum, child) => {
- return sum + Number(child.quantity);
- }, 0);
+ const totalChildQuantity = roundedChildTotal(children);
// Only update if we didn't create a new jobMaterial (in which case it's already set)
if (actualMaterialId === materialId) {
- const currentQuantityIssued =
- Number(jobMaterial?.quantityIssued) || 0;
- const newQuantityIssued =
- currentQuantityIssued + totalChildQuantity;
+ const currentQuantityIssued = round(
+ Number(jobMaterial?.quantityIssued) || 0
+ );
+ const newQuantityIssued = round(
+ currentQuantityIssued + totalChildQuantity
+ );
await trx
.updateTable("jobMaterial")
@@ -2745,12 +2764,16 @@ serve(async (req: Request) => {
);
}
- const quantityToIssue =
+ // Rounded once here: it drives the ledger rows, the budget
+ // allocation and the quantityIssued write below.
+ const quantityToIssue = round(
adjustmentType === "Positive Adjmt."
? Number(quantity)
: adjustmentType === "Negative Adjmt."
? Number(quantity)
- : Number(quantity) - Number(material?.quantityIssued); // set quantity
+ : round(Number(quantity)) -
+ round(Number(material?.quantityIssued)) // set quantity
+ );
if (material && material.methodType !== "Make to Order") {
let remaining = Number(quantityToIssue);
@@ -2816,11 +2839,12 @@ serve(async (req: Request) => {
// A positive adjustment returns material to inventory, so it
// reduces quantityIssued — otherwise the backflush cap sees
// returned material as still issued.
- quantityIssued:
- (Number(material?.quantityIssued) ?? 0) +
- (adjustmentType === "Positive Adjmt."
- ? -Number(quantityToIssue)
- : Number(quantityToIssue)),
+ quantityIssued: round(
+ round(Number(material?.quantityIssued) ?? 0) +
+ (adjustmentType === "Positive Adjmt."
+ ? -quantityToIssue
+ : quantityToIssue)
+ ),
})
.where("id", "=", materialId)
.execute();
@@ -2899,7 +2923,7 @@ serve(async (req: Request) => {
storageUnitId: storageUnitId ?? undefined,
methodType: "Pull from Inventory",
quantity: 0,
- quantityIssued: Number(quantity ?? 0),
+ quantityIssued: round(Number(quantity ?? 0)),
unitCost: itemCost?.unitCost ?? 0,
})
.returning("id")
@@ -3352,11 +3376,16 @@ serve(async (req: Request) => {
// Reopen the requirement — the consumed part is gone, so the
// assembly needs a replacement issued.
- const currentQuantityIssued = Number(material.quantityIssued) || 0;
+ const currentQuantityIssued = round(
+ Number(material.quantityIssued) || 0
+ );
await trx
.updateTable("jobMaterial")
.set({
- quantityIssued: Math.max(0, currentQuantityIssued - quantity),
+ quantityIssued: Math.max(
+ 0,
+ round(currentQuantityIssued - round(quantity))
+ ),
})
.where("id", "=", materialId)
.execute();
@@ -4152,13 +4181,14 @@ serve(async (req: Request) => {
}
}
- const totalChildQuantity = children.reduce((sum, child) => {
- return sum + Number(child.quantity);
- }, 0);
+ const totalChildQuantity = roundedChildTotal(children);
- const currentQuantityIssued =
- Number(jobMaterial?.quantityIssued) || 0;
- const newQuantityIssued = currentQuantityIssued - totalChildQuantity;
+ const currentQuantityIssued = round(
+ Number(jobMaterial?.quantityIssued) || 0
+ );
+ const newQuantityIssued = round(
+ currentQuantityIssued - totalChildQuantity
+ );
await trx
.updateTable("jobMaterial")
@@ -4654,7 +4684,13 @@ serve(async (req: Request) => {
if (!trackedEntity) {
throw new Error("Tracked entity not found");
}
- const { trackedEntityId, quantity } = child;
+ const { trackedEntityId } = child;
+
+ // Same canonical quantity as the job-consumption loop above: a
+ // full draw books the lot's own rounded on-hand.
+ const entityQuantity = round(Number(trackedEntity.quantity));
+ const fullDraw = isFullDraw(entityQuantity, child.quantity);
+ const quantity = fullDraw ? entityQuantity : round(child.quantity);
// Book against the entity's ACTUAL bin (net on-hand), not an
// arbitrary first ledger row — aligns with the job-consumption
@@ -4670,7 +4706,7 @@ serve(async (req: Request) => {
// Maintenance Consumption ledger, junction row) books against
// the child.
let consumedEntityId = trackedEntityId;
- if (Number(trackedEntity.quantity) !== quantity) {
+ if (!fullDraw) {
const consumedChildId = nanoid();
consumedEntityId = consumedChildId;
@@ -4678,7 +4714,7 @@ serve(async (req: Request) => {
parent: {
id: trackedEntity.id!,
readableId: trackedEntity.readableId,
- quantity: Number(trackedEntity.quantity),
+ quantity: entityQuantity,
sourceDocument: trackedEntity.sourceDocument,
sourceDocumentId: trackedEntity.sourceDocumentId,
sourceDocumentReadableId:
@@ -5004,12 +5040,13 @@ serve(async (req: Request) => {
}
// Update the dispatch item quantity
- const totalChildQuantity = children.reduce((sum, child) => {
- return sum + Number(child.quantity);
- }, 0);
+ const totalChildQuantity = roundedChildTotal(children);
- const currentQuantity = Number(dispatchItem.quantity) || 0;
- const newQuantity = Math.max(0, currentQuantity - totalChildQuantity);
+ const currentQuantity = round(Number(dispatchItem.quantity) || 0);
+ const newQuantity = Math.max(
+ 0,
+ round(currentQuantity - totalChildQuantity)
+ );
await trx
.updateTable("maintenanceDispatchItem")
diff --git a/packages/database/supabase/functions/post-inventory-adjustment/index.ts b/packages/database/supabase/functions/post-inventory-adjustment/index.ts
index 745b092ef9..594348fef3 100644
--- a/packages/database/supabase/functions/post-inventory-adjustment/index.ts
+++ b/packages/database/supabase/functions/post-inventory-adjustment/index.ts
@@ -3,19 +3,44 @@ 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 { buildBatchSplitRecords, isFullDraw } 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";
import { getFunctionLogger } from "../lib/logging.ts";
import { requirePermissions } from "../lib/supabase.ts";
-import type { Json } from "../lib/types.ts";
+import type { Database, 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 { settleQuantity } from "../shared/entity-drain.ts";
import { round } from "../shared/precision.ts";
import { resolveUnscrapUnitCost } from "./resolve-unscrap-cost.ts";
+// settleQuantity needs the lot's CURRENT status to know whether to preserve it
+// (a Scrapped lot stays Scrapped at zero). get_item_quantities_by_tracking_id
+// doesn't carry status, so read it off the row — one PK lookup inside the open
+// transaction, next to the write it informs.
+//
+// LOCKED: the caller feeds this status straight back through settleQuantity, so
+// an unlocked read is a read-modify-write on `status`. Without the lock a
+// concurrent transaction that Scraps the lot between our read and our update is
+// silently overwritten with the stale `Available` we read.
+async function currentEntityStatus(
+ trx: Transaction<DB>,
+ trackedEntityId: string,
+ companyId: string
+): Promise<Database["public"]["Enums"]["trackedEntityStatus"]> {
+ const row = await trx
+ .selectFrom("trackedEntity")
+ .select("status")
+ .where("id", "=", trackedEntityId)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .executeTakeFirstOrThrow();
+ return row.status;
+}
+
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
const logger = getFunctionLogger("post-inventory-adjustment");
@@ -400,9 +425,9 @@ serve(async (req: Request) => {
"Only available tracked entities can be scrapped"
);
}
- const entityQuantity = Number(entity.quantity) || 0;
+ const entityQuantity = round(Number(entity.quantity) || 0);
// quantity 0 ⇒ scrap the whole entity (serial UIs don't send a qty)
- const scrapQuantity = quantity > 0 ? quantity : entityQuantity;
+ const scrapQuantity = quantity > 0 ? round(quantity) : entityQuantity;
if (scrapQuantity > entityQuantity) {
throw new ValidationError("Insufficient quantity for scrap");
}
@@ -410,7 +435,7 @@ serve(async (req: Request) => {
currentQuantity?.storageUnitId ?? storageUnitId ?? null;
let scrappedEntityId = trackedEntityId;
- if (scrapQuantity < entityQuantity) {
+ if (!isFullDraw(entityQuantity, scrapQuantity)) {
// Partial batch scrap: identity-flip split — the parent keeps its
// id and is decremented; the departing child is the Scrapped
// record of what left.
@@ -838,18 +863,28 @@ serve(async (req: Request) => {
throw new ValidationError("Serial number not found");
}
const resolvedId = resolvedQtyRow.trackedEntityId as string;
- const resolvedQty = resolvedQtyRow.quantity ?? 0;
- if (adjustmentQuantity > resolvedQty) {
+ const resolvedQty = round(resolvedQtyRow.quantity ?? 0);
+ if (round(adjustmentQuantity) > resolvedQty) {
throw new ValidationError(
"Insufficient quantity for negative adjustment"
);
}
- await trx
- .updateTable("trackedEntity")
- .set({ quantity: resolvedQty - adjustmentQuantity, readableId })
- .where("id", "=", resolvedId)
- .where("companyId", "=", companyId)
- .execute();
+ // A negative adjustment draws down Available stock; when it lands
+ // on zero the lot is Consumed, not a zero-quantity Available husk.
+ // settleQuantity is the shared rule, so this path also preserves a
+ // Scrapped lot — which the inline flip it replaces did not.
+ await trx
+ .updateTable("trackedEntity")
+ .set({
+ ...settleQuantity({
+ quantity: resolvedQty - adjustmentQuantity,
+ status: await currentEntityStatus(trx, resolvedId, companyId),
+ }),
+ readableId,
+ })
+ .where("id", "=", resolvedId)
+ .where("companyId", "=", companyId)
+ .execute();
const booked = await bookAdjustment(trx, {
ledger: {
...ledgerBase,
@@ -910,8 +945,8 @@ serve(async (req: Request) => {
);
}
const targetRow = trackedRowsInUnit[0];
- const targetQty = targetRow.quantity ?? 0;
- if (adjustmentQuantity > targetQty) {
+ const targetQty = round(targetRow.quantity ?? 0);
+ if (round(adjustmentQuantity) > targetQty) {
throw new ValidationError(
"Insufficient quantity for negative adjustment"
);
@@ -919,7 +954,12 @@ serve(async (req: Request) => {
const targetId = targetRow.trackedEntityId as string;
await trx
.updateTable("trackedEntity")
- .set({ quantity: targetQty - adjustmentQuantity })
+ .set(
+ settleQuantity({
+ quantity: targetQty - adjustmentQuantity,
+ status: await currentEntityStatus(trx, targetId, companyId),
+ })
+ )
.where("id", "=", targetId)
.where("companyId", "=", companyId)
.execute();
@@ -950,9 +990,14 @@ serve(async (req: Request) => {
if (trackedEntityId) {
if (currentQuantity) {
- const entityUpdate: Record<string, unknown> = {
+ // Draining a lot to zero Consumes it (a Set Quantity to 0 or a full
+ // negative adjustment); above zero its status is untouched. This path
+ // takes an arbitrary trackedEntityId from the payload, so it is the
+ // one that can land on a Scrapped lot — settleQuantity preserves it.
+ const entityUpdate: Record<string, unknown> = settleQuantity({
quantity: signedQuantity + currentQuantityOnHand,
- };
+ status: await currentEntityStatus(trx, trackedEntityId, companyId),
+ });
if (readableId !== undefined && readableId !== null) {
entityUpdate.readableId = readableId;
}
@@ -964,6 +1009,12 @@ serve(async (req: Request) => {
.execute();
await applyExpirationOverride(trx, trackedEntityId);
} else {
+ // Nothing to create for a zero-quantity new entity: the physical
+ // state is already zero, so skip the insert AND the ledger row and
+ // return a success no-op (keeps repeated scanners idempotent).
+ if (round(signedQuantity) === 0) {
+ return;
+ }
const expirationDate = resolveExpirationForNewEntity();
// Stamp the trace blob so the popover Source / Override steps can
// show the entity originated from a manual inventory adjustment.
@@ -1001,7 +1052,7 @@ serve(async (req: Request) => {
// sales-return picker); omitting it made this stock unreturnable.
itemId,
readableId: readableId ?? null,
- quantity: signedQuantity,
+ quantity: round(signedQuantity),
status: "Available",
expirationDate,
attributes: attributes as unknown as Json,
diff --git a/packages/database/supabase/functions/post-inventory-count/count-guards.test.ts b/packages/database/supabase/functions/post-inventory-count/count-guards.test.ts
new file mode 100644
index 0000000000..2bccce1304
--- /dev/null
+++ b/packages/database/supabase/functions/post-inventory-count/count-guards.test.ts
@@ -0,0 +1,49 @@
+import {
+ assertEquals,
+ assertThrows
+} from "https://deno.land/[email protected]/testing/asserts.ts";
+import { resolveCountedEntity } from "./count-guards.ts";
+
+Deno.test("applies the delta to the live quantity", () => {
+ assertEquals(
+ resolveCountedEntity({
+ currentQuantity: 10,
+ delta: -3,
+ currentStatus: "Available"
+ }),
+ { quantity: 7, status: "Available" }
+ );
+});
+
+Deno.test("landing on exactly zero Consumes the lot", () => {
+ assertEquals(
+ resolveCountedEntity({
+ currentQuantity: 4,
+ delta: -4,
+ currentStatus: "Available"
+ }),
+ { quantity: 0, status: "Consumed" }
+ );
+});
+
+Deno.test("a delta that would drive the quantity negative is refused", () => {
+ // Stock moved since the snapshot — recount rather than clamp/desync.
+ assertThrows(() =>
+ resolveCountedEntity({
+ currentQuantity: 2,
+ delta: -5,
+ currentStatus: "Available"
+ })
+ );
+});
+
+Deno.test("a Scrapped lot counted to zero stays Scrapped", () => {
+ assertEquals(
+ resolveCountedEntity({
+ currentQuantity: 1,
+ delta: -1,
+ currentStatus: "Scrapped"
+ }),
+ { quantity: 0, status: "Scrapped" }
+ );
+});
diff --git a/packages/database/supabase/functions/post-inventory-count/count-guards.ts b/packages/database/supabase/functions/post-inventory-count/count-guards.ts
new file mode 100644
index 0000000000..da4edbfe7a
--- /dev/null
+++ b/packages/database/supabase/functions/post-inventory-count/count-guards.ts
@@ -0,0 +1,21 @@
+// Pure decision for how a counted tracked entity's quantity and status settle.
+// A count books its ledger delta from the SNAPSHOT taken when the count was
+// generated; the entity's live quantity may have moved since. Applying the same
+// delta to the live quantity keeps entity and ledger in step — but if that lands
+// below zero the two have genuinely diverged, so we refuse (recount) rather than
+// clamp, which would desync the entity from the already-booked ledger delta.
+
+import { settleQuantity } from "../shared/entity-drain.ts";
+
+export function resolveCountedEntity<S extends string>(input: {
+ currentQuantity: number;
+ delta: number;
+ currentStatus: S;
+}): { quantity: number; status: S | "Consumed" } {
+ return settleQuantity({
+ quantity: input.currentQuantity + input.delta,
+ status: input.currentStatus,
+ refusal:
+ "Stock moved since the count was taken; recount this line before posting",
+ });
+}
diff --git a/packages/database/supabase/functions/post-inventory-count/index.ts b/packages/database/supabase/functions/post-inventory-count/index.ts
index aa7060358c..58dd7120b2 100644
--- a/packages/database/supabase/functions/post-inventory-count/index.ts
+++ b/packages/database/supabase/functions/post-inventory-count/index.ts
@@ -8,6 +8,7 @@ import { requirePermissions } from "../lib/supabase.ts";
import type { Database } from "../lib/types.ts";
import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";
+import { resolveCountedEntity } from "./count-guards.ts";
import {
bookAdjustment,
createAdjustmentJournal
@@ -308,10 +309,27 @@ serve(async (req: Request) => {
// Tracked lines: apply the same delta to the entity's quantity (not a
// set-to-counted) so movements since the snapshot aren't overwritten.
+ // Lock and read the live row so the guard sees the current quantity;
+ // a delta that would drive it negative means stock moved since the
+ // count, so we throw to roll back rather than clamp (which would desync
+ // the entity from the ledger delta already booked above). Landing on
+ // zero flips the lot Consumed.
if (line.trackedEntityId) {
+ const entity = await trx
+ .selectFrom("trackedEntity")
+ .select(["quantity", "status"])
+ .where("id", "=", line.trackedEntityId)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .executeTakeFirst();
+ const settled = resolveCountedEntity({
+ currentQuantity: Number(entity?.quantity ?? 0),
+ delta,
+ currentStatus: entity?.status ?? "Available",
+ });
await trx
.updateTable("trackedEntity")
- .set((eb) => ({ quantity: eb("quantity", "+", delta) }))
+ .set({ quantity: settled.quantity, status: settled.status })
.where("id", "=", line.trackedEntityId)
.where("companyId", "=", companyId)
.execute();
diff --git a/packages/database/supabase/functions/post-picking/index.ts b/packages/database/supabase/functions/post-picking/index.ts
index f4bec87215..2693f76670 100644
--- a/packages/database/supabase/functions/post-picking/index.ts
+++ b/packages/database/supabase/functions/post-picking/index.ts
@@ -9,8 +9,15 @@ import type { Database } from "../lib/types.ts";
import { resolveTrackedEntityBin } from "../issue/resolve-tracked-entity-bin.ts";
import {
buildBatchSplitRecords,
- buildMergeRecords
+ buildMergeRecords,
+ isFullDraw
} from "../shared/batch-split.ts";
+import { settleQuantity } from "../shared/entity-drain.ts";
+import {
+ assertEntityCoversPick,
+ PickGuardError,
+ resolvePick
+} from "../shared/pick-guards.ts";
import { round } from "../shared/precision.ts";
import { getPickedBudgets, orderOldFirst } from "../lib/picked-consumption.ts";
@@ -138,11 +145,16 @@ serve(async (req: Request) => {
} = validatedPayload;
await db.transaction().execute(async (trx) => {
+ // Lock the line: every case here read-modify-writes its picked or
+ // returned counter, so two concurrent scans of the same line would
+ // both add to the same stale total and the ledger would double. Same
+ // lock post-stock-transfer takes.
const line = await trx
.selectFrom("pickingListLine")
.where("id", "=", pickingListLineId)
.where("companyId", "=", companyId)
.selectAll()
+ .forUpdate()
.executeTakeFirstOrThrow();
const inserts: ItemLedgerInsert[] = [
@@ -177,7 +189,11 @@ serve(async (req: Request) => {
await trx
.updateTable("pickingListLine")
.set({
- quantityPicked: Number(line.quantityPicked ?? 0) + quantity,
+ quantityPicked: resolvePick({
+ lineQuantity: Number(line.quantityToPick ?? 0),
+ pickedQuantity: Number(line.quantityPicked ?? 0),
+ transferQuantity: quantity
+ }),
status: "Picked",
updatedBy: userId,
updatedAt: new Date().toISOString()
@@ -203,11 +219,16 @@ serve(async (req: Request) => {
} = validatedPayload;
await db.transaction().execute(async (trx) => {
+ // Lock the line: every case here read-modify-writes its picked or
+ // returned counter, so two concurrent scans of the same line would
+ // both add to the same stale total and the ledger would double. Same
+ // lock post-stock-transfer takes.
const line = await trx
.selectFrom("pickingListLine")
.where("id", "=", pickingListLineId)
.where("companyId", "=", companyId)
.selectAll()
+ .forUpdate()
.executeTakeFirstOrThrow();
const inserts: ItemLedgerInsert[] = [
@@ -244,7 +265,7 @@ serve(async (req: Request) => {
.set({
quantityPicked: Math.max(
0,
- Number(line.quantityPicked ?? 0) - quantity
+ round(round(Number(line.quantityPicked ?? 0)) - round(quantity))
),
status: "Pending",
updatedBy: userId,
@@ -272,11 +293,16 @@ serve(async (req: Request) => {
} = validatedPayload;
await db.transaction().execute(async (trx) => {
+ // Lock the line: every case here read-modify-writes its picked or
+ // returned counter, so two concurrent scans of the same line would
+ // both add to the same stale total and the ledger would double. Same
+ // lock post-stock-transfer takes.
const line = await trx
.selectFrom("pickingListLine")
.where("id", "=", pickingListLineId)
.where("companyId", "=", companyId)
.selectAll()
+ .forUpdate()
.executeTakeFirstOrThrow();
const activityId = nanoid();
@@ -342,7 +368,11 @@ serve(async (req: Request) => {
await trx
.updateTable("pickingListLine")
.set({
- quantityPicked: Number(line.quantityPicked ?? 0) + 1,
+ quantityPicked: resolvePick({
+ lineQuantity: Number(line.quantityToPick ?? 0),
+ pickedQuantity: Number(line.quantityPicked ?? 0),
+ transferQuantity: 1
+ }),
status: "Picked",
updatedBy: userId,
updatedAt: new Date().toISOString()
@@ -388,29 +418,59 @@ serve(async (req: Request) => {
} = validatedPayload;
await db.transaction().execute(async (trx) => {
+ // Lock the line: every case here read-modify-writes its picked or
+ // returned counter, so two concurrent scans of the same line would
+ // both add to the same stale total and the ledger would double. Same
+ // lock post-stock-transfer takes.
const line = await trx
.selectFrom("pickingListLine")
.where("id", "=", pickingListLineId)
.where("companyId", "=", companyId)
.selectAll()
+ .forUpdate()
.executeTakeFirstOrThrow();
+ // Lock the source lot too: the split below draws against this
+ // on-hand, and a concurrent pick of the same lot must not spend it.
const trackedEntity = await trx
.selectFrom("trackedEntity")
.where("id", "=", trackedEntityId)
.where("companyId", "=", companyId)
.selectAll()
+ .forUpdate()
.executeTakeFirstOrThrow();
- const entityQuantity = Number(trackedEntity.quantity);
- const transferQuantity = quantity;
+ // Refuse an over-pick before any record is written; resolvePick
+ // returns the new running total (the UI caps the picker at the same
+ // outstanding figure, so this only fires on a stale page or a
+ // double submit — which is exactly when it matters).
+ const newQuantityPicked = resolvePick({
+ lineQuantity: Number(line.quantityToPick ?? 0),
+ pickedQuantity: Number(line.quantityPicked ?? 0),
+ transferQuantity: quantity
+ });
+
+ // Round BOTH operands once: the split gate, the split records, the
+ // Pick activity input, the allocation row and the two ledger rows
+ // all derive from these.
+ const entityQuantity = round(Number(trackedEntity.quantity));
+ const transferQuantity = round(quantity);
+
+ // resolvePick bounds the pick by the LINE's outstanding quantity, not
+ // by what this lot holds. A line outstanding larger than the lot would
+ // fall through isFullDraw into buildBatchSplitRecords, which throws a
+ // plain Error on `draw >= parentQty` — surfaced as a 500. This is the
+ // same guard post-stock-transfer's batch case takes, and it makes the
+ // refusal a 400 the scan UI can show.
+ assertEntityCoversPick({ entityQuantity, transferQuantity });
+
const inserts: ItemLedgerInsert[] = [];
// Split the batch when picking less than the whole entity: the shelf
// entity keeps its id and is decremented; a NEW child entity departs
// to the lineside bin carrying the drawn quantity.
let pickedEntityId = trackedEntityId;
- if (entityQuantity !== transferQuantity) {
+ if (!isFullDraw(entityQuantity, transferQuantity)) {
const childId = nanoid();
splitEntityId = childId;
pickedEntityId = childId;
@@ -543,8 +603,7 @@ serve(async (req: Request) => {
await trx
.updateTable("pickingListLine")
.set({
- quantityPicked:
- Number(line.quantityPicked ?? 0) + transferQuantity,
+ quantityPicked: newQuantityPicked,
status: "Picked",
updatedBy: userId,
updatedAt: new Date().toISOString()
@@ -595,11 +654,16 @@ serve(async (req: Request) => {
} = validatedPayload;
await db.transaction().execute(async (trx) => {
+ // Lock the line: every case here read-modify-writes its picked or
+ // returned counter, so two concurrent scans of the same line would
+ // both add to the same stale total and the ledger would double. Same
+ // lock post-stock-transfer takes.
const line = await trx
.selectFrom("pickingListLine")
.where("id", "=", pickingListLineId)
.where("companyId", "=", companyId)
.selectAll()
+ .forUpdate()
.executeTakeFirstOrThrow();
const trackedEntity = await trx
@@ -670,7 +734,7 @@ serve(async (req: Request) => {
.set({
quantityPicked: Math.max(
0,
- Number(line.quantityPicked ?? 0) - qty
+ round(round(Number(line.quantityPicked ?? 0)) - round(qty))
),
status: "Pending",
updatedBy: userId,
@@ -703,11 +767,16 @@ serve(async (req: Request) => {
} = validatedPayload;
await db.transaction().execute(async (trx) => {
+ // Lock the line: every case here read-modify-writes its picked or
+ // returned counter, so two concurrent scans of the same line would
+ // both add to the same stale total and the ledger would double. Same
+ // lock post-stock-transfer takes.
const line = await trx
.selectFrom("pickingListLine")
.where("id", "=", pickingListLineId)
.where("companyId", "=", companyId)
.selectAll()
+ .forUpdate()
.executeTakeFirstOrThrow();
const trackedEntity = await trx
@@ -801,13 +870,16 @@ serve(async (req: Request) => {
.executeTakeFirst();
if (parent && parent.readableId === trackedEntity.readableId) {
- const childRemaining =
- Number(trackedEntity.quantity) - unpickQuantity;
- if (childRemaining < 0) {
- throw new Error(
- `Cannot unpick batch: entity ${trackedEntityId} holds ${trackedEntity.quantity} but ${unpickQuantity} was picked — partial consumption must be unconsumed first`
- );
- }
+ // Round before comparing: a residue child (holding
+ // 0.020000000000000018 after an earlier split) giving back its
+ // 0.02 lands on −1.7e-17, and a raw `< 0` refuses a legitimate
+ // full unpick. settleQuantity rounds, refuses a REAL negative,
+ // and Consumes the emptied child in one decision.
+ const childSettled = settleQuantity({
+ quantity: Number(trackedEntity.quantity) - unpickQuantity,
+ status: trackedEntity.status,
+ refusal: `Cannot unpick batch: entity ${trackedEntityId} holds ${trackedEntity.quantity} but ${unpickQuantity} was picked — partial consumption must be unconsumed first`
+ });
const splitActivity = await trx
.selectFrom("trackedActivity")
@@ -821,17 +893,17 @@ serve(async (req: Request) => {
await trx
.updateTable("trackedEntity")
- .set({ quantity: Number(parent.quantity) + unpickQuantity })
+ .set({
+ quantity: round(
+ round(Number(parent.quantity)) + round(unpickQuantity)
+ )
+ })
.where("id", "=", parent.id)
.execute();
await trx
.updateTable("trackedEntity")
- .set(
- childRemaining === 0
- ? { quantity: 0, status: "Consumed" }
- : { quantity: childRemaining }
- )
+ .set(childSettled)
.where("id", "=", trackedEntityId)
.execute();
@@ -901,7 +973,7 @@ serve(async (req: Request) => {
.set({
quantityPicked: Math.max(
0,
- Number(line.quantityPicked ?? 0) - unpickQuantity
+ round(round(Number(line.quantityPicked ?? 0)) - round(unpickQuantity))
),
status: "Pending",
updatedBy: userId,
@@ -928,11 +1000,16 @@ serve(async (req: Request) => {
validatedPayload;
await db.transaction().execute(async (trx) => {
+ // Lock the line: every case here read-modify-writes its picked or
+ // returned counter, so two concurrent scans of the same line would
+ // both add to the same stale total and the ledger would double. Same
+ // lock post-stock-transfer takes.
const line = await trx
.selectFrom("pickingListLine")
.where("id", "=", pickingListLineId)
.where("companyId", "=", companyId)
.selectAll()
+ .forUpdate()
.executeTakeFirstOrThrow();
const totalReturned = await returnTrackedAllocationRemainder(trx, {
@@ -1029,7 +1106,11 @@ serve(async (req: Request) => {
return jsonResponse({ success: true, splitEntityId });
} catch (err) {
- return errorResponse(err, 500);
+ // A pick guard is a caller-input refusal, not a server fault — surface it
+ // as a 400 with its message so the scan UI can show "already fully picked"
+ // instead of a generic failure. Matches post-stock-transfer.
+ const status = err instanceof PickGuardError ? 400 : 500;
+ return errorResponse(err, status);
}
});
@@ -1253,7 +1334,10 @@ async function returnTrackedAllocationRemainder(
parent &&
parent.status === "Available" &&
parent.readableId === entity.readableId &&
- onHand <= Number(entity.quantity)
+ // Rounded: buildMergeRecords refuses merge > childQty at scale, so a
+ // raw compare here could skip a merge the builder would have accepted
+ // (0.30000000000000004 of a 0.3 lot) and silently fall back.
+ round(onHand) <= round(Number(entity.quantity))
) {
const parentLedgers = await trx
.selectFrom("itemLedger")
diff --git a/packages/database/supabase/functions/post-shipment/index.ts b/packages/database/supabase/functions/post-shipment/index.ts
index 85e2c291e9..e41600441e 100644
--- a/packages/database/supabase/functions/post-shipment/index.ts
+++ b/packages/database/supabase/functions/post-shipment/index.ts
@@ -7,7 +7,7 @@ import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import type { Database, Json } from "../lib/types.ts";
import { TrackedEntityAttributes, credit, debit, journalReference } from "../lib/utils.ts";
-import { buildBatchSplitRecords } from "../shared/batch-split.ts";
+import { buildBatchSplitRecords, isFullDraw } from "../shared/batch-split.ts";
import {
buildJournalLineDimensionInserts,
type JournalDimensionMeta,
@@ -741,10 +741,20 @@ serve(async (req: Request) => {
]
);
+ // Round both, then ask isFullDraw first: a residue lot
+ // (holding 0.020000000000000018 after an earlier split)
+ // shipped in full reads as `shipped < quantity` on a raw
+ // compare, and the split loop below then throws the builder's
+ // `draw >= parentQty` guard on a legitimate full shipment.
+ const entityQuantity = round(Number(trackedEntity.quantity));
+ const shippedQuantity = round(
+ Number(shipmentLine?.shippedQuantity)
+ );
if (
shipmentLine?.shippedQuantity !== undefined &&
trackedEntity.quantity !== undefined &&
- shipmentLine.shippedQuantity < trackedEntity.quantity
+ !isFullDraw(entityQuantity, shippedQuantity) &&
+ shippedQuantity < entityQuantity
) {
// Partial shipment → split. The shelf entity keeps its id
// and is only decremented (split loop below); the SHIPPED
@@ -752,10 +762,9 @@ serve(async (req: Request) => {
// update on the parent here.
trackedEntitySplits[trackedEntity.id] = {
originalEntityId: trackedEntity.id,
- originalQuantity: trackedEntity.quantity,
- shippedQuantity: shipmentLine.shippedQuantity,
- remainingQuantity:
- trackedEntity.quantity - shipmentLine.shippedQuantity,
+ originalQuantity: entityQuantity,
+ shippedQuantity,
+ remainingQuantity: round(entityQuantity - shippedQuantity),
readableId: trackedEntity.readableId,
attributes:
trackedEntity.attributes as TrackedEntityAttributes,
@@ -772,8 +781,14 @@ serve(async (req: Request) => {
acc[trackedEntity.id] = {
status: "Consumed",
- quantity:
- shipmentLine?.shippedQuantity ?? trackedEntity.quantity,
+ // Keep the ?? fallback exactly as it was and just round it:
+ // a null shippedQuantity must still fall through to the
+ // entity's own quantity, which `!== undefined` would not do.
+ quantity: round(
+ Number(
+ shipmentLine?.shippedQuantity ?? trackedEntity.quantity
+ )
+ ),
};
return acc;
@@ -1391,10 +1406,20 @@ serve(async (req: Request) => {
]
);
+ // Round both, then ask isFullDraw first: a residue lot
+ // (holding 0.020000000000000018 after an earlier split)
+ // shipped in full reads as `shipped < quantity` on a raw
+ // compare, and the split loop below then throws the builder's
+ // `draw >= parentQty` guard on a legitimate full shipment.
+ const entityQuantity = round(Number(trackedEntity.quantity));
+ const shippedQuantity = round(
+ Number(shipmentLine?.shippedQuantity)
+ );
if (
shipmentLine?.shippedQuantity !== undefined &&
trackedEntity.quantity !== undefined &&
- shipmentLine.shippedQuantity < trackedEntity.quantity
+ !isFullDraw(entityQuantity, shippedQuantity) &&
+ shippedQuantity < entityQuantity
) {
// Partial shipment → split. The shelf entity keeps its id
// and is only decremented (split loop below); the SHIPPED
@@ -1402,10 +1427,9 @@ serve(async (req: Request) => {
// the parent here.
trackedEntitySplits[trackedEntity.id] = {
originalEntityId: trackedEntity.id,
- originalQuantity: trackedEntity.quantity,
- shippedQuantity: shipmentLine.shippedQuantity,
- remainingQuantity:
- trackedEntity.quantity - shipmentLine.shippedQuantity,
+ originalQuantity: entityQuantity,
+ shippedQuantity,
+ remainingQuantity: round(entityQuantity - shippedQuantity),
readableId: trackedEntity.readableId,
attributes:
trackedEntity.attributes as TrackedEntityAttributes,
@@ -1421,8 +1445,14 @@ serve(async (req: Request) => {
}
acc[trackedEntity.id] = {
- quantity:
- shipmentLine?.shippedQuantity ?? trackedEntity.quantity,
+ // Keep the ?? fallback exactly as it was and just round it:
+ // a null shippedQuantity must still fall through to the
+ // entity's own quantity, which `!== undefined` would not do.
+ quantity: round(
+ Number(
+ shipmentLine?.shippedQuantity ?? trackedEntity.quantity
+ )
+ ),
};
return acc;
@@ -2396,17 +2426,17 @@ serve(async (req: Request) => {
createdBy: userId,
companyId,
});
- if (draw + 0.00001 >= entityQty) {
+ if (isFullDraw(entityQty, draw)) {
trackedEntityUpdates[entity.id] = {
status: "Consumed",
- quantity: entityQty,
+ quantity: round(entityQty),
};
} else {
// Partial → split at post; the negative ledger row above is
// retargeted to the departing child in the transaction.
trackedEntitySplits.push({
entity,
- drawQuantity: draw,
+ drawQuantity: round(draw),
storageUnitId: shipmentLine.storageUnitId,
itemId: shipmentLine.itemId,
ledgerIndex,
diff --git a/packages/database/supabase/functions/post-stock-transfer/index.ts b/packages/database/supabase/functions/post-stock-transfer/index.ts
index d0269995a6..2d4fc6db3e 100644
--- a/packages/database/supabase/functions/post-stock-transfer/index.ts
+++ b/packages/database/supabase/functions/post-stock-transfer/index.ts
@@ -7,8 +7,13 @@ import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import type { Database } from "../lib/types.ts";
-import { buildBatchSplitRecords } from "../shared/batch-split.ts";
+import { buildBatchSplitRecords, isFullDraw } from "../shared/batch-split.ts";
import { round } from "../shared/precision.ts";
+import {
+ assertEntityCoversPick,
+ PickGuardError,
+ resolvePick,
+} from "../shared/pick-guards.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -305,14 +310,56 @@ serve(async (req: Request) => {
} = validatedPayload;
await db.transaction().execute(async (trx) => {
- // Get stock transfer line details
+ // Get stock transfer line details. Lock the row so concurrent scans
+ // of the same line cannot both write a +1 over a stale read.
const stockTransferLine = await trx
.selectFrom("stockTransferLine")
.where("id", "=", stockTransferLineId)
.where("companyId", "=", companyId)
.selectAll()
+ .forUpdate()
.executeTakeFirstOrThrow();
+ // Refuse a scan that would exceed the line's serial count.
+ const newPickedQuantity = resolvePick({
+ lineQuantity: Number(stockTransferLine.quantity ?? 0),
+ pickedQuantity: Number(stockTransferLine.pickedQuantity ?? 0),
+ transferQuantity: 1,
+ });
+
+ // Lock the serial itself BEFORE the repeat-scan query: the guard
+ // below reads trackedActivityInput, and two concurrent scans of the
+ // same serial would both read "not on this transfer" and both post a
+ // Transfer activity + ledger pair. The batch case takes the same
+ // lock; here it serializes the guard rather than an on-hand draw.
+ const trackedEntity = await trx
+ .selectFrom("trackedEntity")
+ .where("id", "=", trackedEntityId)
+ .where("companyId", "=", companyId)
+ .select(["id", "readableId"])
+ .forUpdate()
+ .executeTakeFirstOrThrow();
+
+ // Refuse a REPEAT scan of the same serial on this transfer. Each scan
+ // posts a Transfer activity + a −1/+1 ledger pair, so a silent no-op
+ // would let the ledger double; the guard is an explicit 400.
+ const alreadyOnTransfer = await trx
+ .selectFrom("trackedActivityInput as tai")
+ .innerJoin("trackedActivity as ta", "ta.id", "tai.trackedActivityId")
+ .where("tai.trackedEntityId", "=", trackedEntityId)
+ .where("tai.companyId", "=", companyId)
+ .where("ta.type", "=", "Transfer")
+ .where("ta.sourceDocument", "=", "Stock Transfer")
+ .where("ta.sourceDocumentId", "=", stockTransferId)
+ .select("tai.trackedEntityId")
+ .executeTakeFirst();
+ if (alreadyOnTransfer) {
+ throw new PickGuardError(
+ "already-picked",
+ `Serial ${trackedEntity.readableId ?? trackedEntityId} is already picked on this transfer`
+ );
+ }
+
const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =
[];
@@ -389,13 +436,13 @@ serve(async (req: Request) => {
.execute();
}
- // Update stock transfer line with picked quantity
+ // Update stock transfer line with the accumulated picked quantity.
await trx
.updateTable("stockTransferLine")
.set({
trackedEntityId,
fromStorageUnitId: fromStorageUnitId,
- pickedQuantity: (stockTransferLine.pickedQuantity ?? 0) + 1,
+ pickedQuantity: newPickedQuantity,
updatedBy: userId,
updatedAt: new Date().toISOString(),
})
@@ -424,22 +471,39 @@ serve(async (req: Request) => {
const policy = await getExpiredEntityPolicy(companyId);
await db.transaction().execute(async (trx) => {
- // Get stock transfer line details
+ // Get stock transfer line details. Lock the row so two concurrent
+ // scans of the same line accumulate instead of racing to overwrite
+ // pickedQuantity (the ledger would double otherwise).
const stockTransferLine = await trx
.selectFrom("stockTransferLine")
.where("id", "=", stockTransferLineId)
.where("companyId", "=", companyId)
.selectAll()
+ .forUpdate()
.executeTakeFirstOrThrow();
- // Get tracked entity details
+ // Get tracked entity details. Lock it too so the on-hand this pick
+ // draws against cannot be spent by a concurrent transaction.
const trackedEntity = await trx
.selectFrom("trackedEntity")
.where("id", "=", trackedEntityId)
.where("companyId", "=", companyId)
.selectAll()
+ .forUpdate()
.executeTakeFirstOrThrow();
+ // Refuse a pick that over-draws the line or the source lot before any
+ // record is written; resolvePick returns the new running total.
+ const newPickedQuantity = resolvePick({
+ lineQuantity: Number(stockTransferLine.quantity ?? 0),
+ pickedQuantity: Number(stockTransferLine.pickedQuantity ?? 0),
+ transferQuantity: quantity,
+ });
+ assertEntityCoversPick({
+ entityQuantity: Number(trackedEntity.quantity),
+ transferQuantity: quantity,
+ });
+
// Expiry policy gate (throws on hard reject; returns warning for 'Warn').
const expiredCheck = checkExpiredEntity(
{ id: trackedEntity.id, expirationDate: trackedEntity.expirationDate },
@@ -451,8 +515,12 @@ serve(async (req: Request) => {
expiredWarning = expiredCheck.warning;
}
- const entityQuantity = Number(trackedEntity.quantity);
- const transferQuantity = quantity;
+ // Round BOTH operands once, here: everything downstream — the split
+ // gate, the split records, the Transfer activity input and the two
+ // ledger rows — derives from these, so a residue draw can never book
+ // an unrounded quantity against a lot the gate treated as whole.
+ const entityQuantity = round(Number(trackedEntity.quantity));
+ const transferQuantity = round(quantity);
const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =
[];
@@ -460,7 +528,7 @@ serve(async (req: Request) => {
// source entity keeps its id and is decremented; a NEW child entity
// departs to the destination bin with the transfer quantity.
let transferredEntityId = trackedEntityId;
- if (entityQuantity !== transferQuantity) {
+ if (!isFullDraw(entityQuantity, transferQuantity)) {
const childId = nanoid();
splitEntityId = childId;
transferredEntityId = childId;
@@ -606,14 +674,16 @@ serve(async (req: Request) => {
.execute();
}
- // Update stock transfer line with picked quantity — the line
- // references the entity that physically arrives at the destination.
+ // Update stock transfer line with the accumulated picked quantity.
+ // trackedEntityId is keep-last: each partial pick mints a fresh child
+ // entity, so the line points at the newest departing lot (matching
+ // serial). Unpick reverses only the last activity on such a line.
await trx
.updateTable("stockTransferLine")
.set({
trackedEntityId: transferredEntityId,
fromStorageUnitId: fromStorageUnitId,
- pickedQuantity: transferQuantity,
+ pickedQuantity: newPickedQuantity,
updatedBy: userId,
updatedAt: new Date().toISOString(),
})
@@ -636,20 +706,25 @@ serve(async (req: Request) => {
} = validatedPayload;
await db.transaction().execute(async (trx) => {
- // Get stock transfer line details
+ // Lock the line AND the entity: an unpick read-modify-writes the
+ // entity's quantity/status and the line's pickedQuantity, so two
+ // concurrent unpicks of the same child would both credit the parent
+ // and both decrement the line off the same stale read. Same locks the
+ // pick paths take.
const stockTransferLine = await trx
.selectFrom("stockTransferLine")
.where("id", "=", stockTransferLineId)
.where("companyId", "=", companyId)
.selectAll()
+ .forUpdate()
.executeTakeFirstOrThrow();
- // Get tracked entity details
const trackedEntity = await trx
.selectFrom("trackedEntity")
.where("id", "=", trackedEntityId)
.where("companyId", "=", companyId)
.selectAll()
+ .forUpdate()
.executeTakeFirstOrThrow();
// Find the transfer activity for this tracked entity
@@ -765,20 +840,25 @@ serve(async (req: Request) => {
} = validatedPayload;
await db.transaction().execute(async (trx) => {
- // Get stock transfer line details
+ // Lock the line AND the entity: an unpick read-modify-writes the
+ // entity's quantity/status and the line's pickedQuantity, so two
+ // concurrent unpicks of the same child would both credit the parent
+ // and both decrement the line off the same stale read. Same locks the
+ // pick paths take.
const stockTransferLine = await trx
.selectFrom("stockTransferLine")
.where("id", "=", stockTransferLineId)
.where("companyId", "=", companyId)
.selectAll()
+ .forUpdate()
.executeTakeFirstOrThrow();
- // Get tracked entity details
const trackedEntity = await trx
.selectFrom("trackedEntity")
.where("id", "=", trackedEntityId)
.where("companyId", "=", companyId)
.selectAll()
+ .forUpdate()
.executeTakeFirstOrThrow();
// Find the transfer activity for this tracked entity
@@ -797,7 +877,21 @@ serve(async (req: Request) => {
.selectAll("trackedActivity")
.executeTakeFirstOrThrow();
- const transferQuantity = Number(trackedEntity.quantity);
+ // The whole child returns to its parent, so round once here and let
+ // the parent increase, the ledger pair and the pickedQuantity
+ // decrement all derive from the same value.
+ const transferQuantity = round(Number(trackedEntity.quantity));
+
+ // Re-checked UNDER the lock: a lot holding nothing has either already
+ // been unpicked or been consumed at production. Either way there is
+ // nothing to return, and proceeding would delete the transfer
+ // activity and reset pickedQuantity for a no-op.
+ if (transferQuantity <= 0) {
+ throw new PickGuardError(
+ "already-picked",
+ `Lot ${trackedEntity.readableId ?? trackedEntityId} has no quantity left to unpick`
+ );
+ }
const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =
[];
@@ -819,17 +913,19 @@ serve(async (req: Request) => {
if (splitFromParentId) {
// Merge the child fully back into its parent and delete the Split
// — a clean undo, as if the partial transfer never happened.
+ // Locked too — its quantity is incremented from this read.
const parent = await trx
.selectFrom("trackedEntity")
.where("id", "=", splitFromParentId)
.where("companyId", "=", companyId)
.selectAll()
+ .forUpdate()
.executeTakeFirstOrThrow();
await trx
.updateTable("trackedEntity")
.set({
- quantity: Number(parent.quantity) + transferQuantity,
+ quantity: round(round(Number(parent.quantity)) + transferQuantity),
})
.where("id", "=", parent.id)
.execute();
@@ -913,8 +1009,9 @@ serve(async (req: Request) => {
.selectAll()
.executeTakeFirstOrThrow();
- const originalQuantity =
- Number(originalEntity.quantity) + transferQuantity;
+ const originalQuantity = round(
+ round(Number(originalEntity.quantity)) + transferQuantity
+ );
// Find the split activity — scoped to the remainder entity this
// pointer names, not just the transfer (multi-line safety).
@@ -1079,7 +1176,7 @@ serve(async (req: Request) => {
trackedEntityId: null,
pickedQuantity: Math.max(
0,
- (stockTransferLine.pickedQuantity ?? 0) - transferQuantity
+ round(round(stockTransferLine.pickedQuantity ?? 0) - transferQuantity)
),
updatedBy: userId,
updatedAt: new Date().toISOString(),
@@ -1099,6 +1196,10 @@ serve(async (req: Request) => {
splitEntityId,
});
} catch (err) {
- return errorResponse(err, 500);
+ // A pick guard is a caller-input refusal, not a server fault — surface it
+ // as a 400 with its message so the scan UI can show "already fully picked"
+ // instead of a generic failure.
+ const status = err instanceof PickGuardError ? 400 : 500;
+ return errorResponse(err, status);
}
});
diff --git a/packages/database/supabase/functions/shared/batch-merge.test.ts b/packages/database/supabase/functions/shared/batch-merge.test.ts
index 64eb45bbc0..4547deac1a 100644
--- a/packages/database/supabase/functions/shared/batch-merge.test.ts
+++ b/packages/database/supabase/functions/shared/batch-merge.test.ts
@@ -237,3 +237,53 @@ Deno.test("partially received merge moves exactly the received balance", () => {
0
);
});
+
+Deno.test("sums parents at the persist boundary: 0.1 + 0.2 => exactly 0.3", () => {
+ const records = buildBatchMergeRecords({
+ ...base,
+ parents: [
+ parent({ id: "p1", quantity: 0.1, receivedQuantity: 0.1 }),
+ parent({ id: "p2", readableId: "LOT-B", quantity: 0.2, receivedQuantity: 0.2 })
+ ]
+ });
+ assertEquals(records.mergedEntityInsert.quantity, 0.3);
+ assertEquals(records.activityInsert.attributes["Merged Quantity"], 0.3);
+ assertEquals(records.activityOutputInsert.quantity, 0.3);
+ // The positive lands in one bin (both parents share it) and nets the negatives.
+ const positives = records.ledgerInserts.filter((r) => r.quantity > 0);
+ const negatives = records.ledgerInserts.filter((r) => r.quantity < 0);
+ assertEquals(positives.length, 1);
+ assertEquals(positives[0].quantity, 0.3);
+ // Each row is a clean 5dp value; the pool balances (the raw float sum of
+ // -0.1 + -0.2 + 0.3 carries ~5e-17 noise, which is not a stored value).
+ assertEquals(negatives.map((r) => r.quantity), [-0.1, -0.2]);
+ assertEquals(
+ Math.abs(records.ledgerInserts.reduce((acc, r) => acc + r.quantity, 0)) <
+ 1e-9,
+ true
+ );
+});
+
+Deno.test("rounds received quantity PER PARENT so the bin rows net to zero", () => {
+ // Three parents sharing one bin, each holding a third of a unit. Rounding
+ // only the bin total gives 1 against negatives of 0.33333 × 3 = 0.99999 —
+ // the Batch Merge pair leaks a minor unit. Per-parent rounding nets exactly.
+ const third = 1 / 3;
+ const records = buildBatchMergeRecords({
+ ...base,
+ parents: [
+ parent({ id: "p1", quantity: third, receivedQuantity: third }),
+ parent({ id: "p2", readableId: "LOT-B", quantity: third, receivedQuantity: third }),
+ parent({ id: "p3", readableId: "LOT-C", quantity: third, receivedQuantity: third })
+ ]
+ });
+ const positives = records.ledgerInserts.filter((r) => r.quantity > 0);
+ const negatives = records.ledgerInserts.filter((r) => r.quantity < 0);
+ assertEquals(negatives.map((r) => r.quantity), [-0.33333, -0.33333, -0.33333]);
+ assertEquals(positives.length, 1);
+ assertEquals(positives[0].quantity, 0.99999);
+ assertEquals(
+ records.ledgerInserts.reduce((acc, r) => acc + r.quantity, 0) < 1e-9,
+ true
+ );
+});
diff --git a/packages/database/supabase/functions/shared/batch-merge.ts b/packages/database/supabase/functions/shared/batch-merge.ts
index e270fe1b31..8366484147 100644
--- a/packages/database/supabase/functions/shared/batch-merge.ts
+++ b/packages/database/supabase/functions/shared/batch-merge.ts
@@ -6,10 +6,14 @@
// quantity and output = the merged entity, and the ledger gets net-zero Batch
// Merge rows (−q at each parent's bin, +Σq at the merged entity's bin).
//
-// No imports — consumed from Deno edge functions AND node-side app code, so it
-// must not touch lib/database.ts or any Deno API.
+// Consumed from Deno edge functions AND node-side app code, so it must not
+// touch lib/database.ts or any Deno API — its only dependency is the sibling
+// precision module (dependency-free, re-exported through @carbon/utils), so
+// the merged quantity rounds once at this persist boundary.
// See .ai/specs/2026-09-16-batch-materials-and-output-lots.md.
+import { round } from "./precision.ts";
+
export type BatchMergeParent = {
id: string;
readableId: string | null;
@@ -139,7 +143,10 @@ export function buildBatchMergeRecords(input: {
throw new Error("Only lots of the same item can be merged");
}
- const totalQuantity = parents.reduce((sum, p) => sum + p.quantity, 0);
+ // Sum first, round once — the three-boundary rule. Summing N raw quantities
+ // then rounding the total keeps the merged lot a clean 5dp value even when
+ // the parents carry float residue (0.1 + 0.2 → 0.3, not 0.30000000000000004).
+ const totalQuantity = round(parents.reduce((sum, p) => sum + p.quantity, 0));
// Earliest parent expiry wins — the conservative policy for a blended lot.
let expirationDate: string | null = null;
@@ -227,7 +234,7 @@ export function buildBatchMergeRecords(input: {
(p): MergeLedgerRecord => ({
postingDate,
itemId: p.itemId ?? p.sourceDocumentId,
- quantity: -p.receivedQuantity,
+ quantity: -round(p.receivedQuantity),
locationId: p.bin.locationId,
storageUnitId: p.bin.storageUnitId,
entryType: "Negative Adjmt.",
@@ -269,8 +276,17 @@ function receivedByBin(parents: BatchMergeParent[]) {
if (p.receivedQuantity <= 0) continue;
const key = `${p.bin.locationId}|${p.bin.storageUnitId}`;
const entry = byBin.get(key) ?? { bin: p.bin, quantity: 0 };
- entry.quantity += p.receivedQuantity;
+ // Round PER PARENT, the same way the negative rows above do — a bin total
+ // rounded only at the end can differ from the sum of the per-parent
+ // negatives by a minor unit, and the Batch Merge pair stops netting to
+ // zero. Each parent's received quantity is its own persist boundary.
+ entry.quantity += round(p.receivedQuantity);
byBin.set(key, entry);
}
- return [...byBin.values()];
+ // Round the accumulated total too: summing already-rounded parts is exact in
+ // decimal but not in binary float (0.1 + 0.2).
+ return [...byBin.values()].map((entry) => ({
+ bin: entry.bin,
+ quantity: round(entry.quantity)
+ }));
}
diff --git a/packages/database/supabase/functions/shared/batch-split.test.ts b/packages/database/supabase/functions/shared/batch-split.test.ts
index 2883ce6696..5011455464 100644
--- a/packages/database/supabase/functions/shared/batch-split.test.ts
+++ b/packages/database/supabase/functions/shared/batch-split.test.ts
@@ -5,7 +5,8 @@ import {
import {
type BatchSplitInput,
buildBatchSplitRecords,
- buildMergeRecords
+ buildMergeRecords,
+ isFullDraw
} from "./batch-split.ts";
const splitInput = (
@@ -191,3 +192,76 @@ Deno.test("merge: throws when mergeQuantity exceeds child quantity or is <= 0",
assertThrows(() => buildMergeRecords({ ...base, mergeQuantity: 2 }));
assertThrows(() => buildMergeRecords({ ...base, mergeQuantity: 0 }));
});
+
+// --- persist-boundary rounding (PR C) --------------------------------------
+
+Deno.test("split: a float-residue draw persists clean 5dp quantities", () => {
+ // Drawing 0.98 from 1 leaves 0.020000000000000018 in raw float; the parent,
+ // child, ledger, edges and Split blob must all read the rounded values.
+ const r = buildBatchSplitRecords(
+ splitInput({ parent: { id: "parent-1", quantity: 1 }, drawQuantity: 0.98 })
+ );
+ assertEquals(r.parentUpdate, { quantity: 0.02 });
+ assertEquals(r.childEntityInsert.quantity, 0.98);
+ assertEquals(r.activityInsert.attributes, {
+ "Original Quantity": 1,
+ "Drawn Quantity": 0.98,
+ "Remaining Quantity": 0.02,
+ "Split Entity ID": "child-1"
+ });
+ assertEquals(r.activityInputInsert.quantity, 0.98);
+ assertEquals(r.activityOutputInsert.quantity, 0.98);
+ const [minus, plus] = r.ledgerInserts;
+ assertEquals(minus.quantity, -0.98);
+ assertEquals(plus.quantity, 0.98);
+ assertEquals(minus.quantity + plus.quantity, 0);
+});
+
+Deno.test("merge: a 0.30000000000000004 child settles the parent to a clean quantity", () => {
+ const r = buildMergeRecords({
+ child: { id: "child-1", quantity: 0.1 + 0.2 },
+ parent: { id: "parent-1", quantity: 0.1 },
+ mergeQuantity: 0.1 + 0.2,
+ mergeActivityId: "merge-1",
+ companyId: "co-1",
+ userId: "user-1"
+ });
+ assertEquals(r.activityInputInsert.quantity, 0.3);
+ assertEquals(r.activityOutputInsert.quantity, 0.3);
+ assertEquals(r.parentUpdate, { quantity: 0.4 });
+ // Draining the whole (rounded) child flips it Consumed via an exact === 0.
+ assertEquals(r.childUpdate, { quantity: 0, status: "Consumed" });
+});
+
+Deno.test("isFullDraw: an exact whole draw is full", () => {
+ assertEquals(isFullDraw(10, 10), true);
+ assertEquals(isFullDraw(0.02, 0.02), true);
+});
+
+Deno.test("isFullDraw: a residue draw is full, and would otherwise throw", () => {
+ // The lot left after drawing 0.98 from 1 holds 0.020000000000000018. Drawing
+ // 0.02 of it is the whole lot — a raw !== reads it as partial, and the
+ // builder then refuses `draw >= parentQty` on a legitimate full pick.
+ const residue = 1 - 0.98;
+ assertEquals(residue === 0.02, false);
+ assertEquals(isFullDraw(residue, 0.02), true);
+ assertThrows(
+ () =>
+ buildBatchSplitRecords(splitInput({
+ parent: { ...splitInput().parent, quantity: residue },
+ drawQuantity: 0.02
+ })),
+ Error,
+ "a full draw is not a split"
+ );
+});
+
+Deno.test("isFullDraw: one minor unit of real stock is still a partial draw", () => {
+ // 1e-5 is a storable difference at internal scale, not float noise.
+ assertEquals(isFullDraw(1, 0.99999), false);
+ assertEquals(isFullDraw(10, 9.99999), false);
+});
+
+Deno.test("isFullDraw: an over-draw is not reported as full", () => {
+ assertEquals(isFullDraw(1, 1.5), false);
+});
diff --git a/packages/database/supabase/functions/shared/batch-split.ts b/packages/database/supabase/functions/shared/batch-split.ts
index c35cfd6f1b..68b930720e 100644
--- a/packages/database/supabase/functions/shared/batch-split.ts
+++ b/packages/database/supabase/functions/shared/batch-split.ts
@@ -1,6 +1,9 @@
-// Pure record builders for the batch split/merge convention. No imports — this
-// module is consumed from Deno edge functions AND node-side app code (ERP
-// quality-disposition), so it must not touch lib/database.ts or any Deno API.
+// Pure record builders for the batch split/merge convention. Consumed from Deno
+// edge functions AND node-side app code (ERP quality-disposition), so it must
+// not touch lib/database.ts or any Deno API — its only dependency is the
+// sibling precision module (itself dependency-free, re-exported through
+// @carbon/utils for the node side), so quantities round at THIS persist
+// boundary and every caller inherits it.
//
// Convention (spec .ai/specs/2026-08-04-batch-split-identity-flip.md): on a
// partial draw of quantity q from a parent batch, the PARENT KEEPS its id and
@@ -10,6 +13,24 @@
// exactly two net-zero Batch Split rows (−q parent, +q child) at the parent's
// resolved bin. Returns MERGE quantity back into the parent (Merge activity).
+import { equals, round } from "./precision.ts";
+
+/**
+ * The ONE split gate: is this draw the entity's whole quantity?
+ *
+ * Every caller decides "split or take the whole entity" with this, so the gate
+ * and `buildBatchSplitRecords`' own `draw < parentQty` guard can never
+ * disagree. A raw `===`/`<` on two float quantities can: a residue draw (an
+ * entity left holding 0.020000000000000018 after an earlier split, drawn for
+ * 0.02) reads as a PARTIAL draw, and the builder then throws `draw >= parentQty`
+ * on what the operator sees as a legitimate full pick — or mints a phantom
+ * child holding 1.8e-17. Both sides round to internal scale first, so two 5dp
+ * quantities that differ by real stock (one minor unit, 1e-5) still split.
+ */
+export function isFullDraw(entityQuantity: number, drawQuantity: number): boolean {
+ return equals(round(entityQuantity), round(drawQuantity));
+}
+
export type BatchSplitInput = {
parent: {
id: string;
@@ -110,14 +131,22 @@ export function buildBatchSplitRecords(input: BatchSplitInput): {
extraChildAttributes
} = input;
- // The callers' split gates (full draws take the no-split fast path) should
- // make these unreachable — loud beats silent.
- if (drawQuantity <= 0) {
+ // Round at the persist boundary so a float-residue draw (0.98 from 1.0 leaves
+ // 0.020000000000000018, not 0.02) never reaches storage. The child departs
+ // with `draw`, the parent keeps `remaining`, and both ledger rows book `draw`
+ // — all derived from the same rounded values so the two stay net-zero.
+ const draw = round(drawQuantity);
+ const parentQty = round(parent.quantity);
+ const remaining = round(parentQty - draw);
+
+ // The callers' split gates (full draws take the no-split fast path, compared
+ // with equals() at scale) should make these unreachable — loud beats silent.
+ if (draw <= 0) {
throw new Error(
`buildBatchSplitRecords: drawQuantity must be > 0, got ${drawQuantity}`
);
}
- if (drawQuantity >= parent.quantity) {
+ if (draw >= parentQty) {
throw new Error(
`buildBatchSplitRecords: drawQuantity (${drawQuantity}) must be < parent quantity (${parent.quantity}) — a full draw is not a split`
);
@@ -138,7 +167,7 @@ export function buildBatchSplitRecords(input: BatchSplitInput): {
sourceDocument: parent.sourceDocument,
sourceDocumentId: parent.sourceDocumentId,
sourceDocumentReadableId: parent.sourceDocumentReadableId,
- quantity: drawQuantity,
+ quantity: draw,
status: childStatus,
attributes: {
...inheritedAttributes,
@@ -150,16 +179,16 @@ export function buildBatchSplitRecords(input: BatchSplitInput): {
companyId,
createdBy: userId
},
- parentUpdate: { quantity: parent.quantity - drawQuantity },
+ parentUpdate: { quantity: remaining },
activityInsert: {
id: splitActivityId,
type: "Split",
sourceDocument: activitySourceDocument,
sourceDocumentId: activitySourceDocumentId,
attributes: {
- "Original Quantity": parent.quantity,
- "Drawn Quantity": drawQuantity,
- "Remaining Quantity": parent.quantity - drawQuantity,
+ "Original Quantity": parentQty,
+ "Drawn Quantity": draw,
+ "Remaining Quantity": remaining,
"Split Entity ID": childId
},
companyId,
@@ -168,14 +197,14 @@ export function buildBatchSplitRecords(input: BatchSplitInput): {
activityInputInsert: {
trackedActivityId: splitActivityId,
trackedEntityId: parent.id,
- quantity: drawQuantity,
+ quantity: draw,
companyId,
createdBy: userId
},
activityOutputInsert: {
trackedActivityId: splitActivityId,
trackedEntityId: childId,
- quantity: drawQuantity,
+ quantity: draw,
companyId,
createdBy: userId
},
@@ -183,7 +212,7 @@ export function buildBatchSplitRecords(input: BatchSplitInput): {
{
postingDate,
itemId: itemLedgerItemId,
- quantity: -drawQuantity,
+ quantity: -draw,
locationId: bin.locationId,
storageUnitId: bin.storageUnitId,
entryType: "Negative Adjmt.",
@@ -196,7 +225,7 @@ export function buildBatchSplitRecords(input: BatchSplitInput): {
{
postingDate,
itemId: itemLedgerItemId,
- quantity: drawQuantity,
+ quantity: draw,
locationId: bin.locationId,
storageUnitId: bin.storageUnitId,
entryType: "Positive Adjmt.",
@@ -233,25 +262,31 @@ export function buildMergeRecords(input: {
const { child, parent, mergeQuantity, mergeActivityId, companyId, userId } =
input;
- if (mergeQuantity <= 0) {
+ // Round at the persist boundary: a merge of a 0.30000000000000004 float
+ // child settles the parent back to a clean quantity and lets the drain-to-
+ // zero short-circuit compare exactly.
+ const merge = round(mergeQuantity);
+ const childQty = round(child.quantity);
+
+ if (merge <= 0) {
throw new Error(
`buildMergeRecords: mergeQuantity must be > 0, got ${mergeQuantity}`
);
}
- if (mergeQuantity > child.quantity) {
+ if (merge > childQty) {
throw new Error(
`buildMergeRecords: mergeQuantity (${mergeQuantity}) exceeds child quantity (${child.quantity})`
);
}
- const childRemaining = child.quantity - mergeQuantity;
+ const childRemaining = round(childQty - merge);
return {
activityInsert: {
id: mergeActivityId,
type: "Merge",
attributes: {
- "Merged Quantity": mergeQuantity,
+ "Merged Quantity": merge,
"Merged From Entity ID": child.id
},
companyId,
@@ -260,21 +295,24 @@ export function buildMergeRecords(input: {
activityInputInsert: {
trackedActivityId: mergeActivityId,
trackedEntityId: child.id,
- quantity: mergeQuantity,
+ quantity: merge,
companyId,
createdBy: userId
},
activityOutputInsert: {
trackedActivityId: mergeActivityId,
trackedEntityId: parent.id,
- quantity: mergeQuantity,
+ quantity: merge,
companyId,
createdBy: userId
},
- parentUpdate: { quantity: parent.quantity + mergeQuantity },
+ parentUpdate: { quantity: round(round(parent.quantity) + merge) },
+ // childRemaining is already rounded, so `=== 0` is exact here — but go
+ // through the shared drain rule so a merge that empties a lot settles the
+ // same way every other quantity writer does.
childUpdate:
- childRemaining === 0
- ? { quantity: 0, status: "Consumed" }
+ childRemaining <= 0
+ ? { quantity: 0, status: "Consumed" as const }
: { quantity: childRemaining }
};
}
diff --git a/packages/database/supabase/functions/shared/entity-drain.test.ts b/packages/database/supabase/functions/shared/entity-drain.test.ts
new file mode 100644
index 0000000000..c9c60d02fe
--- /dev/null
+++ b/packages/database/supabase/functions/shared/entity-drain.test.ts
@@ -0,0 +1,80 @@
+import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
+import {
+ settleQuantity,
+ statusAfterQuantityChange
+} from "./entity-drain.ts";
+import { assertThrows } from "https://deno.land/[email protected]/testing/asserts.ts";
+
+Deno.test("draining to zero Consumes the lot", () => {
+ assertEquals(statusAfterQuantityChange(0, "Available"), "Consumed");
+});
+
+Deno.test("a positive quantity keeps the current status", () => {
+ assertEquals(statusAfterQuantityChange(3, "Available"), "Available");
+ assertEquals(statusAfterQuantityChange(3, "On Hold"), "On Hold");
+ assertEquals(statusAfterQuantityChange(3, "Reserved"), "Reserved");
+});
+
+Deno.test("a Scrapped lot stays Scrapped even at zero", () => {
+ assertEquals(statusAfterQuantityChange(0, "Scrapped"), "Scrapped");
+ assertEquals(statusAfterQuantityChange(5, "Scrapped"), "Scrapped");
+});
+
+Deno.test("a float-residue zero still Consumes", () => {
+ // round(1 - 0.98 - 0.02) is exactly 0 → Consumed.
+ assertEquals(
+ statusAfterQuantityChange(1 - 0.98 - 0.02, "Available"),
+ "Consumed"
+ );
+});
+
+Deno.test("settleQuantity: rounds and Consumes a residue drain in one step", () => {
+ // The unpick residue case: a child holding 0.020000000000000018 gives back
+ // 0.02 — the settled quantity is an exact 0, so the lot is Consumed, not an
+ // Available husk holding 1.8e-17.
+ assertEquals(
+ settleQuantity({ quantity: 0.020000000000000018 - 0.02, status: "Available" }),
+ { quantity: 0, status: "Consumed" }
+ );
+});
+
+Deno.test("settleQuantity: a surviving remainder keeps its status", () => {
+ assertEquals(settleQuantity({ quantity: 1 - 0.98, status: "Available" }), {
+ quantity: 0.02,
+ status: "Available"
+ });
+});
+
+Deno.test("settleQuantity: a Scrapped lot stays Scrapped at zero", () => {
+ assertEquals(settleQuantity({ quantity: 0, status: "Scrapped" }), {
+ quantity: 0,
+ status: "Scrapped"
+ });
+});
+
+Deno.test("settleQuantity: refuses a negative settle rather than clamping", () => {
+ assertThrows(
+ () => settleQuantity({ quantity: -0.5, status: "Available" }),
+ Error,
+ "refusing to write a negative tracked quantity"
+ );
+ // A caller-supplied refusal wins, so each writer explains its own divergence.
+ assertThrows(
+ () =>
+ settleQuantity({
+ quantity: -1,
+ status: "Available",
+ refusal: "partial consumption must be unconsumed first"
+ }),
+ Error,
+ "partial consumption must be unconsumed first"
+ );
+});
+
+Deno.test("settleQuantity: float noise below a minor unit is not negative", () => {
+ // round(-1e-17) is 0, so this settles instead of refusing.
+ assertEquals(settleQuantity({ quantity: -1e-17, status: "Available" }), {
+ quantity: 0,
+ status: "Consumed"
+ });
+});
diff --git a/packages/database/supabase/functions/shared/entity-drain.ts b/packages/database/supabase/functions/shared/entity-drain.ts
new file mode 100644
index 0000000000..096cad90a2
--- /dev/null
+++ b/packages/database/supabase/functions/shared/entity-drain.ts
@@ -0,0 +1,49 @@
+// The one rule for a tracked entity's status after its quantity changes, shared
+// by the writers that can drain an entity to zero (post-inventory-count, the
+// receipt split in create, correct-stock-movement; post-inventory-adjustment
+// applies the same drain inline on its Available-stock paths). A lot with no
+// quantity left is Consumed, not a husk that still reads Available and clutters
+// every on-hand list; a Scrapped lot stays Scrapped even at zero — it is a
+// historical record and unscrap is the only way back. Pure, dependency-free
+// aside from the sibling precision module.
+
+import { round } from "./precision.ts";
+
+export function statusAfterQuantityChange<S extends string>(
+ newQuantity: number,
+ currentStatus: S
+): S | "Consumed" {
+ if (currentStatus === "Scrapped") return currentStatus;
+ return round(newQuantity) <= 0 ? "Consumed" : currentStatus;
+}
+
+/**
+ * The whole settle for one quantity write: round at the persist boundary,
+ * refuse a negative result, and apply the drain rule above. Every writer that
+ * moves a tracked entity's quantity goes through this so the rounded value and
+ * the status flip can never be derived from different numbers — a residue
+ * quantity that reads as 0 after rounding must ALSO be Consumed.
+ *
+ * `quantity` is the settled (post-arithmetic) figure, not a delta: callers that
+ * hold a delta pass `current + delta`, which is what makes one signature serve
+ * both the count path (snapshot delta) and the adjustment/unpick paths.
+ */
+export function settleQuantity<S extends string>(input: {
+ quantity: number;
+ status: S;
+ /** Message for a below-zero result. Landing there means the caller's own
+ * guard and this write disagree, so we refuse rather than clamp. */
+ refusal?: string;
+}): { quantity: number; status: S | "Consumed" } {
+ const quantity = round(input.quantity);
+ if (quantity < 0) {
+ throw new Error(
+ input.refusal ??
+ `Quantity would fall to ${quantity} — refusing to write a negative tracked quantity`
+ );
+ }
+ return {
+ quantity,
+ status: statusAfterQuantityChange(quantity, input.status),
+ };
+}
diff --git a/packages/database/supabase/functions/shared/pick-guards.test.ts b/packages/database/supabase/functions/shared/pick-guards.test.ts
new file mode 100644
index 0000000000..01b692e4de
--- /dev/null
+++ b/packages/database/supabase/functions/shared/pick-guards.test.ts
@@ -0,0 +1,140 @@
+import {
+ assertEquals,
+ assertThrows
+} from "https://deno.land/[email protected]/testing/asserts.ts";
+import {
+ assertEntityCoversPick,
+ PickGuardError,
+ resolvePick
+} from "./pick-guards.ts";
+
+Deno.test("resolvePick: a partial pick accumulates onto the running total", () => {
+ // Pick 4 then 6 on a 10-unit line → 4, then 10.
+ const afterFirst = resolvePick({
+ lineQuantity: 10,
+ pickedQuantity: 0,
+ transferQuantity: 4
+ });
+ assertEquals(afterFirst, 4);
+ const afterSecond = resolvePick({
+ lineQuantity: 10,
+ pickedQuantity: afterFirst,
+ transferQuantity: 6
+ });
+ assertEquals(afterSecond, 10);
+});
+
+Deno.test("resolvePick: an exact full pick is allowed", () => {
+ assertEquals(
+ resolvePick({ lineQuantity: 10, pickedQuantity: 0, transferQuantity: 10 }),
+ 10
+ );
+});
+
+Deno.test("resolvePick: a float-residue full pick still lands exactly", () => {
+ // 0.98 then 0.02 on a 1-unit line: the second pick equals the remainder at
+ // scale, so it is allowed and totals exactly 1.
+ const afterFirst = resolvePick({
+ lineQuantity: 1,
+ pickedQuantity: 0,
+ transferQuantity: 0.98
+ });
+ assertEquals(
+ resolvePick({
+ lineQuantity: 1,
+ pickedQuantity: afterFirst,
+ transferQuantity: 1 - 0.98
+ }),
+ 1
+ );
+});
+
+Deno.test("resolvePick: an over-pick is refused", () => {
+ const err = assertThrows(
+ () =>
+ resolvePick({
+ lineQuantity: 10,
+ pickedQuantity: 0,
+ transferQuantity: 11
+ }),
+ PickGuardError
+ );
+ assertEquals((err as PickGuardError).kind, "over-pick");
+});
+
+Deno.test("resolvePick: a pick on a fully-picked line is refused", () => {
+ const err = assertThrows(
+ () =>
+ resolvePick({
+ lineQuantity: 10,
+ pickedQuantity: 10,
+ transferQuantity: 1
+ }),
+ PickGuardError
+ );
+ assertEquals((err as PickGuardError).kind, "already-picked");
+});
+
+Deno.test("resolvePick: even a tiny pick after full is refused", () => {
+ assertThrows(
+ () =>
+ resolvePick({
+ lineQuantity: 10,
+ pickedQuantity: 10,
+ transferQuantity: 0.02
+ }),
+ PickGuardError
+ );
+});
+
+Deno.test("assertEntityCoversPick: drawing more than the lot holds is refused", () => {
+ const err = assertThrows(
+ () => assertEntityCoversPick({ entityQuantity: 5, transferQuantity: 6 }),
+ PickGuardError
+ );
+ assertEquals((err as PickGuardError).kind, "over-pick");
+});
+
+Deno.test("assertEntityCoversPick: an exact (or equal-at-scale) full draw is allowed", () => {
+ assertEntityCoversPick({ entityQuantity: 5, transferQuantity: 5 });
+ assertEntityCoversPick({ entityQuantity: 1, transferQuantity: 0.98 + 0.02 });
+});
+
+Deno.test("resolvePick: refuses a pick that rounds to zero", () => {
+ // Below half a minor unit at internal scale — accumulating it flips the line
+ // to Picked and books a zero ledger pair for nothing.
+ const err = assertThrows(
+ () =>
+ resolvePick({
+ lineQuantity: 10,
+ pickedQuantity: 0,
+ transferQuantity: 0.000001
+ }),
+ PickGuardError,
+ "rounds to zero"
+ );
+ assertEquals((err as PickGuardError).kind, "empty-pick");
+ assertThrows(
+ () => resolvePick({ lineQuantity: 10, pickedQuantity: 0, transferQuantity: 0 }),
+ PickGuardError,
+ "rounds to zero"
+ );
+});
+
+Deno.test("resolvePick: an empty pick is refused before the already-picked check", () => {
+ // A fully picked line scanned with a zero quantity reports the ZERO, not
+ // "already fully picked" — the operator's input is what is wrong.
+ const err = assertThrows(
+ () =>
+ resolvePick({ lineQuantity: 10, pickedQuantity: 10, transferQuantity: 0 }),
+ PickGuardError
+ );
+ assertEquals((err as PickGuardError).kind, "empty-pick");
+});
+
+Deno.test("resolvePick: a smallest-storable pick is allowed", () => {
+ assertEquals(
+ resolvePick({ lineQuantity: 10, pickedQuantity: 0, transferQuantity: 0.00001 }),
+ 0.00001
+ );
+});
diff --git a/packages/database/supabase/functions/shared/pick-guards.ts b/packages/database/supabase/functions/shared/pick-guards.ts
new file mode 100644
index 0000000000..5d9b4662c1
--- /dev/null
+++ b/packages/database/supabase/functions/shared/pick-guards.ts
@@ -0,0 +1,83 @@
+// Pure idempotency guards for a pick against a document line — shared by
+// post-stock-transfer and post-picking, so both accumulate the same way.
+// Compares at internal scale
+// (round/equals from the shared precision module) so a float-residue draw never
+// reads as an over-pick, and a line that is already fully picked is refused
+// before any ledger row is written — a repeat scan would otherwise double-post
+// the transfer. Dependency-free aside from the sibling precision module.
+
+import { equals, EPSILON, round } from "./precision.ts";
+
+export type PickGuardKind = "over-pick" | "already-picked" | "empty-pick";
+
+/** A guard refusal the caller turns into a 400 (never a 500). `kind` lets the
+ * edge function's outer catch distinguish it from a data-layer error. */
+export class PickGuardError extends Error {
+ readonly kind: PickGuardKind;
+ constructor(kind: PickGuardKind, message: string) {
+ super(message);
+ this.name = "PickGuardError";
+ this.kind = kind;
+ }
+}
+
+/**
+ * Resolve a pick against the line's running total. Returns the NEW accumulated
+ * `pickedQuantity` (never a replacement), or throws a typed `PickGuardError`:
+ * - "already-picked" — the line has no outstanding quantity left.
+ * - "over-pick" — this pick exceeds what is still outstanding.
+ * - "empty-pick" — the pick rounds to nothing at internal scale.
+ * A serial pick (transferQuantity 1) is the same rule: it is refused once
+ * pickedQuantity has reached the line quantity.
+ */
+export function resolvePick(input: {
+ lineQuantity: number;
+ pickedQuantity: number;
+ transferQuantity: number;
+}): number {
+ const line = round(input.lineQuantity);
+ const already = round(input.pickedQuantity);
+ const pick = round(input.transferQuantity);
+ const outstanding = round(line - already);
+
+ // A quantity below half a minor unit rounds to 0: accumulating it would
+ // write a "Picked" status and a zero ledger pair for nothing. Refuse it
+ // here rather than let the split builder throw its `draw > 0` guard as a 500.
+ if (pick <= 0) {
+ throw new PickGuardError(
+ "empty-pick",
+ `Pick of ${input.transferQuantity} rounds to zero — nothing to pick`
+ );
+ }
+ if (equals(outstanding, 0) || outstanding < 0) {
+ throw new PickGuardError(
+ "already-picked",
+ "This line is already fully picked"
+ );
+ }
+ // An equal-at-scale pick of the whole remainder is allowed; only a pick that
+ // exceeds it beyond float noise is an over-pick.
+ if (!equals(pick, outstanding) && pick - outstanding > EPSILON) {
+ throw new PickGuardError(
+ "over-pick",
+ `Pick of ${pick} exceeds outstanding ${outstanding}`
+ );
+ }
+ return round(already + pick);
+}
+
+/** Guard a batch pick against the SOURCE entity's on-hand: a transfer may never
+ * draw more than the entity holds. Equal-at-scale is fine (a full draw). */
+export function assertEntityCoversPick(input: {
+ entityQuantity: number;
+ transferQuantity: number;
+}): void {
+ const entity = round(input.entityQuantity);
+ const pick = round(input.transferQuantity);
+ if (!equals(pick, entity) && pick - entity > EPSILON) {
+ throw new PickGuardError(
+ "over-pick",
+ `Pick of ${pick} exceeds the ${entity} on hand for this lot`
+ );
+ }
+}
diff --git a/packages/database/supabase/functions/shared/precision.ts b/packages/database/supabase/functions/shared/precision.ts
index ed59f014e1..13954f3da5 100644
--- a/packages/database/supabase/functions/shared/precision.ts
+++ b/packages/database/supabase/functions/shared/precision.ts
@@ -34,6 +34,20 @@ export function round(
return shift(fn(shift(value, scale)), -scale);
}
+/** Value equality at the one float-noise tolerance. Two 5dp quantities that
+ * differ only by ~1e-12 float residue (0.98 + 0.02 vs 1) are the SAME
+ * quantity — use this instead of `===`/`!==` when a raw compare would mistake
+ * that residue for a real difference (e.g. deciding whether a draw is a full
+ * draw). `tolerance` defaults to EPSILON; pass a business tolerance only where
+ * the caller decides what a difference MEANS. */
+export function equals(
+ a: number,
+ b: number,
+ tolerance: number = EPSILON
+): boolean {
+ return Math.abs(a - b) <= tolerance;
+}
+
/** Round every part to `scale` so the results sum EXACTLY to `target`, moving at
* most ONE minor unit per part (largest-remainder / Hamilton apportionment).
*
diff --git a/packages/database/supabase/migrations/20260922191138_tracked-entity-quantity-nonnegative.sql b/packages/database/supabase/migrations/20260922191138_tracked-entity-quantity-nonnegative.sql
new file mode 100644
index 0000000000..97c2ceedd3
--- /dev/null
+++ b/packages/database/supabase/migrations/20260922191138_tracked-entity-quantity-nonnegative.sql
@@ -0,0 +1,17 @@
+-- A tracked entity must never hold a negative quantity: the pick/adjust/count/
+-- correction paths now round at the persist boundary and refuse over-draws, so
+-- a negative quantity can only be corruption. Added NOT VALID so existing bad
+-- prod rows (the ZeroFarms −20 husk) do not fail the deploy; a later migration
+-- VALIDATEs it once the historical rows are repaired (same convention as
+-- 20260805152353_timezone-validity-check.sql / the 20260827115500 VALIDATE step).
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM "pg_constraint"
+ WHERE "conname" = 'trackedEntity_quantity_nonnegative'
+ ) THEN
+ ALTER TABLE "trackedEntity"
+ ADD CONSTRAINT "trackedEntity_quantity_nonnegative"
+ CHECK ("quantity" >= 0) NOT VALID;
+ END IF;
+END $$;
diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.po
index c1b5ff4c81..159332d160 100644
--- a/packages/locale/locales/de/mes.po
+++ b/packages/locale/locales/de/mes.po
@@ -642,6 +642,9 @@ msgstr "Mit nicht gepicktem Material abschließen?"
msgid "First due {0}"
msgstr "Zuerst fällig {0}"
+msgid "Fix the highlighted quantities before completing."
+msgstr "Korrigieren Sie die markierten Mengen vor dem Fertigstellen."
+
msgid "Forgot to Clock Out?"
msgstr "Ausstempeln vergessen?"
diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.po
index ad6390a8ef..12917fce06 100644
--- a/packages/locale/locales/en/mes.po
+++ b/packages/locale/locales/en/mes.po
@@ -642,6 +642,9 @@ msgstr "Finish with material unpicked?"
msgid "First due {0}"
msgstr "First due {0}"
+msgid "Fix the highlighted quantities before completing."
+msgstr "Fix the highlighted quantities before completing."
+
msgid "Forgot to Clock Out?"
msgstr "Forgot to Clock Out?"
diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.po
index f12ee58ccc..556f1baac8 100644
--- a/packages/locale/locales/es/mes.po
+++ b/packages/locale/locales/es/mes.po
@@ -642,6 +642,9 @@ msgstr "¿Finalizar con material sin recoger?"
msgid "First due {0}"
msgstr "Primer vencimiento {0}"
+msgid "Fix the highlighted quantities before completing."
+msgstr "Corrija las cantidades resaltadas antes de completar."
+
msgid "Forgot to Clock Out?"
msgstr "¿Olvidó fichar salida?"
diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.po
index 7c4e6c783a..305fbe7794 100644
--- a/packages/locale/locales/fr/mes.po
+++ b/packages/locale/locales/fr/mes.po
@@ -642,6 +642,9 @@ msgstr "Terminer avec du matériel non prélevé?"
msgid "First due {0}"
msgstr "Première échéance {0}"
+msgid "Fix the highlighted quantities before completing."
+msgstr "Corrigez les quantités surlignées avant de continuer."
+
msgid "Forgot to Clock Out?"
msgstr "Avez-vous oublié le pointage fin ?"
diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.po
index 06f2a4ae6d..a8e7d2fa94 100644
--- a/packages/locale/locales/hi/mes.po
+++ b/packages/locale/locales/hi/mes.po
@@ -642,6 +642,9 @@ msgstr "सामग्री बिना चुने समाप्त क
msgid "First due {0}"
msgstr "पहली देय {0}"
+msgid "Fix the highlighted quantities before completing."
+msgstr "पूर्ण करने से पहले हाइलाइट की गई मात्राओं को ठीक करें।"
+
msgid "Forgot to Clock Out?"
msgstr "कार्य समाप्त करना भूल गए?"
diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.po
index e92ad039e5..fba04e0e75 100644
--- a/packages/locale/locales/it/mes.po
+++ b/packages/locale/locales/it/mes.po
@@ -642,6 +642,9 @@ msgstr "Terminare con il materiale non prelevato?"
msgid "First due {0}"
msgstr "Prima scadenza {0}"
+msgid "Fix the highlighted quantities before completing."
+msgstr "Correggi le quantità evidenziate prima di completare."
+
msgid "Forgot to Clock Out?"
msgstr "Hai dimenticato il timbra fine?"
diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.po
index 07cdc144d2..81bf031007 100644
--- a/packages/locale/locales/ja/mes.po
+++ b/packages/locale/locales/ja/mes.po
@@ -642,6 +642,9 @@ msgstr "材料がピッキングされていない状態で終了しますか?"
msgid "First due {0}"
msgstr "最初の期日 {0}"
+msgid "Fix the highlighted quantities before completing."
+msgstr "完了する前に、ハイライトされた数量を修正してください。"
+
msgid "Forgot to Clock Out?"
msgstr "作業終了を忘れていませんか?"
diff --git a/packages/locale/locales/ko/mes.po b/packages/locale/locales/ko/mes.po
index 9dbd9bc3a0..c2ce71bfa0 100644
--- a/packages/locale/locales/ko/mes.po
+++ b/packages/locale/locales/ko/mes.po
@@ -642,6 +642,9 @@ msgstr "미선택 재료가 있는 상태로 완료하시겠습니까?"
msgid "First due {0}"
msgstr "첫 번째 기한 {0}"
+msgid "Fix the highlighted quantities before completing."
+msgstr "완료하기 전에 강조된 수량을 수정하세요."
+
msgid "Forgot to Clock Out?"
msgstr "작업 종료를 잊었나요?"
diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.po
index 27b872350a..49ecc899f1 100644
--- a/packages/locale/locales/pl/mes.po
+++ b/packages/locale/locales/pl/mes.po
@@ -642,6 +642,9 @@ msgstr "Zakończyć bez wybranego materiału?"
msgid "First due {0}"
msgstr "Pierwszy termin {0}"
+msgid "Fix the highlighted quantities before completing."
+msgstr "Popraw podświetlone ilości przed sfinalizowaniem."
+
msgid "Forgot to Clock Out?"
msgstr "Zapomniano o zakończeniu pracy?"
diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.po
index b7562824f3..b2a19ddd00 100644
--- a/packages/locale/locales/pt/mes.po
+++ b/packages/locale/locales/pt/mes.po
@@ -642,6 +642,9 @@ msgstr "Finalizar com material não selecionado?"
msgid "First due {0}"
msgstr "Primeiro prazo {0}"
+msgid "Fix the highlighted quantities before completing."
+msgstr "Corrija as quantidades realçadas antes de concluir."
+
msgid "Forgot to Clock Out?"
msgstr "Esqueceu de apontar fim?"
diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.po
index 2ff15367f3..ec6cbf3a2f 100644
--- a/packages/locale/locales/ru/mes.po
+++ b/packages/locale/locales/ru/mes.po
@@ -642,6 +642,9 @@ msgstr "Завершить с неподобранным материалом?"
msgid "First due {0}"
msgstr "Первый срок {0}"
+msgid "Fix the highlighted quantities before completing."
+msgstr "Исправьте выделенные количества перед завершением."
+
msgid "Forgot to Clock Out?"
msgstr "Забыли отметить окончание работы?"
diff --git a/packages/locale/locales/tr/mes.po b/packages/locale/locales/tr/mes.po
index 4e9006e2e7..7e2e04726c 100644
--- a/packages/locale/locales/tr/mes.po
+++ b/packages/locale/locales/tr/mes.po
@@ -642,6 +642,9 @@ msgstr "Malzeme seçilmeden bitir?"
msgid "First due {0}"
msgstr "İlk vade {0}"
+msgid "Fix the highlighted quantities before completing."
+msgstr "Tamamlamadan önce vurgulanan miktarları düzeltin."
+
msgid "Forgot to Clock Out?"
msgstr "İş bitişini unutmuş musunuz?"
diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.po
index 162d0f60ec..d3712038dd 100644
--- a/packages/locale/locales/zh/mes.po
+++ b/packages/locale/locales/zh/mes.po
@@ -642,6 +642,9 @@ msgstr "物料未拣货的情况下要完成吗?"
msgid "First due {0}"
msgstr "最早应交期 {0}"
+msgid "Fix the highlighted quantities before completing."
+msgstr "完成前请修正突出显示的数量。"
+
msgid "Forgot to Clock Out?"
msgstr "忘记收工了吗?"