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(inventory): settle receipt batch-tracking status with quantity + zero-available invariant (#1715)

Sid76ea8a00f964
diff --git a/.claude/rules/traceability-model.md b/.claude/rules/traceability-model.md
index 3504a0f678..76d0ce91fb 100644
--- a/.claude/rules/traceability-model.md
+++ b/.claude/rules/traceability-model.md
@@ -261,6 +261,19 @@ both read "not on this transfer" and both post a Transfer pair).
pre-check that mirrors the same rounding so the two cannot disagree; the lock
is what makes the edge function authoritative.
+**The drain rule is not only a TypeScript concern.** `update_receipt_line_batch_tracking`
+upserted a receipt lot with `ON CONFLICT … DO UPDATE SET "quantity" = EXCLUDED."quantity"`
+and never touched `status`, so editing a batch line down to 0 on a receipt whose lot
+had already gone Available left `0` + `Available` — the exact husk this rule forbids
+(fixed in `20260923220000_receipt-batch-tracking-settle-status.sql`, which drains to
+`Consumed` and revives a re-entered quantity to `On Hold`). Neither `settleQuantity`
+nor the `no-unrounded-tracked-quantity` check could see it: the check scans TypeScript
+only. The net that DOES cover SQL functions and triggers is the data-driven invariant
+`packages/checks/src/invariants/tracked-entity-zero-available.sql` — run it after
+touching any tracked-entity writer, in either language. The serial twin
+(`update_receipt_line_serial_tracking`) is unaffected: it always inserts quantity 1 and
+its UPDATE branch never writes quantity.
+
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
diff --git a/packages/checks/AGENTS.md b/packages/checks/AGENTS.md
index 09b0d0733b..2a82f2862e 100644
--- a/packages/checks/AGENTS.md
+++ b/packages/checks/AGENTS.md
@@ -37,6 +37,7 @@ pnpm --filter @carbon/checks baseline # regenerate baseline (careful!)
- **Clobber detection**: `findClobbers(branch, main)` — identifies DB objects redefined on both sides
- **Baseline**: `src/baseline.ts` — grandfathered violations keyed by `checkId + file + line + snippet`
- **Invariants**: SQL queries loaded from directory, injected `Query` for testability
+- **`tracked-entity-zero-available.sql`**: a lot whose quantity is gone must be `Consumed`, never a live status. `Scrapped`/`Rejected` are excluded — both are quality markers kept as historical record and already excluded from on-hand. Enforcement of the drain rule is per-writer, so this is the net that catches husks from ANY source: rows predating the rule, and any writer that revives a drained lot (unconsume, shipment void, disposition Use As Is / Rework). Run it before deciding whether to promote the rule to a DB CHECK
- **Workflows**: two DB-backed drift checks, answering different questions.
`src/invariants/workflow-trigger-event-drift.sql` (via `pnpm --filter @carbon/checks invariants`)
compares each active workflow's `workflowTriggerEvent` rows against its active version's trigger
diff --git a/packages/checks/src/invariants/tracked-entity-zero-available.sql b/packages/checks/src/invariants/tracked-entity-zero-available.sql
new file mode 100644
index 0000000000..e70bc3a66a
--- /dev/null
+++ b/packages/checks/src/invariants/tracked-entity-zero-available.sql
@@ -0,0 +1,29 @@
+-- invariant: a lot with no quantity left is Consumed, never a live status
+-- returns rows that VIOLATE the rule (none = healthy)
+--
+-- The drain rule (functions/shared/entity-drain.ts `settleQuantity` /
+-- `statusAfterQuantityChange`): a tracked entity whose quantity rounds to zero
+-- is Consumed, not a zero-quantity husk that still reads Available and clutters
+-- every on-hand list. `Scrapped` and `Rejected` are deliberately EXCLUDED — both
+-- are quality markers kept as historical record and are already excluded from
+-- on-hand, so a zero-quantity Scrapped/Rejected lot is expected, not a defect.
+--
+-- Enforcement today is per-writer, so this finds husks from ANY source: rows
+-- that predate the drain rule, and any writer that revives a drained lot to a
+-- live status (unconsume, shipment void, disposition Use As Is / Rework).
+-- `createdAt` and `attributes` tell you which flow minted each one.
+SELECT
+ "id",
+ "companyId",
+ "itemId",
+ "readableId",
+ "quantity",
+ "status",
+ "sourceDocument",
+ "sourceDocumentId",
+ "createdAt",
+ "attributes"
+FROM "trackedEntity"
+WHERE ROUND("quantity", 5) <= 0
+ AND "status" NOT IN ('Consumed', 'Scrapped', 'Rejected')
+ORDER BY "createdAt" DESC;
diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.ts
index 4eab9cc055..cdfd203504 100644
--- a/packages/database/supabase/functions/post-receipt/index.ts
+++ b/packages/database/supabase/functions/post-receipt/index.ts
@@ -13,6 +13,7 @@ import {
TrackedEntityAttributes,
} from "../lib/utils.ts";
import { calculateCOGS } from "../shared/calculate-cogs.ts";
+import { settleQuantity } from "../shared/entity-drain.ts";
import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
import { getNextSequence } from "../shared/get-next-sequence.ts";
import {
@@ -730,10 +731,19 @@ serve(async (req: Request) => {
Database["public"]["Tables"]["trackedEntity"]["Update"]
>
>((acc, trackedEntity) => {
- acc[trackedEntity.id] = {
- status: "Available",
- quantity: trackedEntity.quantity,
- };
+ // Voiding restores the lot, but a lot with nothing in it must not
+ // come back Available — that is the zero-quantity husk the drain
+ // rule forbids. Scrapped/Rejected are terminal quality states and
+ // must survive a void, so keep them; everything else returns to
+ // Available (the helper then drains a zero-quantity lot to Consumed).
+ acc[trackedEntity.id] = settleQuantity({
+ quantity: Number(trackedEntity.quantity ?? 0),
+ status:
+ trackedEntity.status === "Scrapped" ||
+ trackedEntity.status === "Rejected"
+ ? trackedEntity.status
+ : ("Available" as const),
+ });
return acc;
}, {}) ?? {};
diff --git a/packages/database/supabase/migrations/20260923220000_receipt-batch-tracking-settle-status.sql b/packages/database/supabase/migrations/20260923220000_receipt-batch-tracking-settle-status.sql
new file mode 100644
index 0000000000..d7641e09ca
--- /dev/null
+++ b/packages/database/supabase/migrations/20260923220000_receipt-batch-tracking-settle-status.sql
@@ -0,0 +1,145 @@
+-- A receipt-line batch write must settle the lot's STATUS with its quantity.
+--
+-- `update_receipt_line_batch_tracking` upserted the entity with
+-- `ON CONFLICT ... DO UPDATE SET "quantity" = EXCLUDED."quantity"` and never
+-- touched `status`. Editing a batch line's quantity down to 0 on a receipt
+-- whose lot had already gone Available therefore left `quantity = 0` with
+-- `status = 'Available'` — exactly the zero-quantity husk the tracked-entity
+-- drain rule exists to prevent (shared/entity-drain.ts `settleQuantity`).
+--
+-- Reproduced against a live lot: 10/Available -> 0/Available after one call
+-- with p_quantity = 0. The TypeScript writers were all fixed to drain through
+-- settleQuantity; this one is SQL, so neither that helper nor the
+-- `no-unrounded-tracked-quantity` conformance check (TypeScript only) covered it.
+--
+-- The serial twin (`update_receipt_line_serial_tracking`) is unaffected: it
+-- always inserts quantity 1 and its UPDATE branch never writes quantity.
+
+CREATE OR REPLACE FUNCTION public.update_receipt_line_batch_tracking(p_receipt_line_id text, p_receipt_id text, p_batch_number text, p_quantity numeric, p_tracked_entity_id text DEFAULT NULL::text, p_properties jsonb DEFAULT '{}'::jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_tracked_entity_id TEXT;
+ v_item_id TEXT;
+ v_item_readable_id TEXT;
+ v_company_id TEXT;
+ v_created_by TEXT;
+ v_supplier_id TEXT;
+ v_attributes JSONB;
+ v_resolved_expiry DATE;
+ v_expiration_date DATE;
+BEGIN
+ PERFORM pg_advisory_xact_lock(hashtext(p_receipt_line_id));
+
+ SELECT
+ rl."itemId",
+ i."readableIdWithRevision",
+ rl."companyId",
+ rl."createdBy",
+ r."supplierId"
+ INTO
+ v_item_id,
+ v_item_readable_id,
+ v_company_id,
+ v_created_by,
+ v_supplier_id
+ FROM "receiptLine" rl
+ JOIN "receipt" r ON r.id = rl."receiptId"
+ JOIN "item" i ON i.id = rl."itemId"
+ WHERE rl.id = p_receipt_line_id;
+
+ IF p_tracked_entity_id IS NOT NULL THEN
+ v_tracked_entity_id := p_tracked_entity_id;
+ ELSE
+ SELECT id INTO v_tracked_entity_id
+ FROM "trackedEntity"
+ WHERE attributes->>'Receipt Line' = p_receipt_line_id
+ AND "companyId" = v_company_id
+ LIMIT 1;
+
+ IF v_tracked_entity_id IS NULL THEN
+ v_tracked_entity_id := nanoid();
+ END IF;
+ END IF;
+
+ v_attributes := jsonb_build_object(
+ 'Receipt Line', p_receipt_line_id,
+ 'Receipt', p_receipt_id
+ );
+
+ IF v_supplier_id IS NOT NULL THEN
+ v_attributes := v_attributes || jsonb_build_object('Supplier', v_supplier_id);
+ END IF;
+
+ IF (p_properties ? 'expirationDate') THEN
+ BEGIN
+ v_expiration_date := (p_properties->>'expirationDate')::DATE;
+ EXCEPTION WHEN OTHERS THEN
+ v_expiration_date := NULL;
+ END;
+ v_attributes := v_attributes || (p_properties - 'expirationDate');
+ ELSE
+ v_attributes := v_attributes || p_properties;
+ END IF;
+
+ IF v_expiration_date IS NULL THEN
+ v_resolved_expiry := resolve_shelf_life_start_for_receipt(v_item_id, p_receipt_id);
+ IF v_resolved_expiry IS NOT NULL THEN
+ v_expiration_date := v_resolved_expiry;
+ END IF;
+ END IF;
+
+ INSERT INTO "trackedEntity" (
+ "id",
+ "quantity",
+ "status",
+ "sourceDocument",
+ "sourceDocumentId",
+ "sourceDocumentReadableId",
+ "readableId",
+ "attributes",
+ "companyId",
+ "createdBy",
+ "itemId",
+ "expirationDate"
+ )
+ VALUES (
+ v_tracked_entity_id,
+ p_quantity,
+ -- A receipt lot with nothing in it is not a live lot. Same drain rule as
+ -- shared/entity-drain.ts: no quantity ⇒ not Available/On Hold.
+ CASE WHEN p_quantity > 0 THEN 'On Hold' ELSE 'Consumed' END::"trackedEntityStatus",
+ 'Item',
+ v_item_id,
+ v_item_readable_id,
+ p_batch_number,
+ v_attributes,
+ v_company_id,
+ v_created_by,
+ v_item_id,
+ v_expiration_date
+ )
+ ON CONFLICT (id) DO UPDATE SET
+ "quantity" = EXCLUDED."quantity",
+ -- Settle the status with the quantity. Without this, editing a batch line
+ -- down to 0 overwrote the quantity and left the lot Available — a
+ -- zero-quantity husk on every on-hand list. Scrapped/Rejected are
+ -- preserved (quality markers, already off on-hand), and re-entering a
+ -- quantity revives the lot to On Hold rather than stranding it Consumed
+ -- with stock on it; posting the receipt is what makes it Available.
+ "status" = CASE
+ WHEN EXCLUDED."quantity" <= 0
+ AND "trackedEntity"."status" NOT IN ('Scrapped', 'Rejected')
+ THEN 'Consumed'
+ WHEN EXCLUDED."quantity" > 0
+ AND "trackedEntity"."status" = 'Consumed'
+ THEN 'On Hold'
+ ELSE "trackedEntity"."status"
+ END::"trackedEntityStatus",
+ "readableId" = EXCLUDED."readableId",
+ "attributes" = EXCLUDED."attributes",
+ "itemId" = EXCLUDED."itemId",
+ "expirationDate" = COALESCE(EXCLUDED."expirationDate", "trackedEntity"."expirationDate");
+END;
+$function$